file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// SPDX-License-Identifier: GPL-3.0
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.0 (utils/Strings.sol)
pragma solidity ^0.8.13;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.0 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.0 (access/Ownable.sol)
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.0 (utils/Address.sol)
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721Receiver.sol)
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.0 (utils/introspection/IERC165.sol)
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.0 (utils/introspection/ERC165.sol)
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/IERC721.sol)
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Enumerable.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);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/IERC721Metadata.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);
}
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath#mul: OVERFLOW");
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath#div: DIVISION_BY_ZERO");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath#sub: UNDERFLOW");
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath#add: OVERFLOW");
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath#mod: DIVISION_BY_ZERO");
return a % b;
}
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/ERC721.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);
}
/**
* @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 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 {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Enumerable.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();
}
}
// File: contracts/drcc.sol
contract DurianciClubNFT is ERC721Enumerable, Ownable {
using Strings for uint256;
using SafeMath for uint256;
string public baseURI;
string public baseExtension = ".json";
string public notRevealedUri;
uint256 public cost = 0.05 ether;
uint256 public maxSupply = 10000;
uint256 public phaseSellingLimit1 = 3300;
uint256 public phaseSellingLimit2 = 3300;
uint256 public phaseSellingLimit3 = 2920;
uint256 public totalmint1 = 0;
uint256 public totalmint2 = 0;
uint256 public totalmint3 = 0;
uint256 public presalesMaxToken = 2;
bool public paused = false;
bool public revealed = false;
uint256 private totalReserve = 480;
uint256 private reserved = 0;
uint256 private sold = 0;
uint16 public salesStage = 1; //1-presales1 , 2-presales2 , 3-presales3 , 4-public
address payable companyWallet;
address private signerAddress = 0xD6321754CdFDd74298F68e79E0c09b93E2dB15d0;
mapping(address => uint256) public addressMintedBalance;
mapping (uint256 => bool) public reserveNo;
mapping(uint256 => uint256) private _presalesPrice;
mapping(address => uint256) public presales1minted; // To check how many tokens an address has minted during presales
mapping(address => uint256) public presales2minted; // To check how many tokens an address has minted during presales
mapping(address => uint256) public presales3minted; // To check how many tokens an address has minted during presales
mapping(address => uint256) public presales4minted; // To check how many tokens an address has minted during presales
mapping(address => uint256) public minted; // To check how many tokens an address has minted
mapping (uint256 => address) public creators;
event URI(string _amount, uint256 indexed _id);
event CurrentSalesStage(uint indexed _salesstage, uint256 indexed _id);
constructor(
) ERC721("Durianci Club NFT", "DRCC NFT") {
setBaseURI("https://api.durianci.club/nft/");
setNotRevealedURI("https://api.durianci.club/nft/");
}
// internal
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
/**
* @dev Creates a new token type and assigns _initialSupply to an address
* NOTE: remove onlyOwner if you want third parties to create new tokens on your contract (which may change your IDs)
* @param _initialOwner address of the first owner of the token
* @param _initialSupply amount to supply the first owner
* @param _uri Optional URI for this token type
* @return The newly created token ID
*/
function reserve(
address _initialOwner,
uint256 _initialSupply,
string memory _uri
// bytes memory _data
) public onlyOwner returns (uint256) {
require(reserved + _initialSupply <= totalReserve, "Reserve Empty");
sold += _initialSupply;
for (uint256 i = 0; i < _initialSupply; i++) {
uint256 supply = reserved;
reserved++;
uint256 _id = reserved;
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
creators[_id] = msg.sender;
_safeMint(_initialOwner, supply + 1);
}
return 0;
}
// Function to receive Ether. msg.data must be empty
receive() external payable {}
// Fallback function is called when msg.data is not empty
fallback() external payable {}
function presales(
address _initialOwner,
uint256 _mintAmount,
bytes calldata _sig
// bytes calldata _data
) external payable returns (uint256) {
require(salesStage == 1 || salesStage == 2 || salesStage == 3, "Presales is closed");
if(salesStage == 1){
require(presales1minted[_initialOwner] + _mintAmount <= presalesMaxToken, "Max 2 Token Per User");
require(totalmint1 + _mintAmount <= phaseSellingLimit1, "phase NFT limit exceeded");
totalmint1 += _mintAmount;
}else if(salesStage == 2){
require(presales2minted[_initialOwner] + _mintAmount <= presalesMaxToken, "Max 2 Token Per User");
require(totalmint2 + _mintAmount <= phaseSellingLimit2, "phase NFT limit exceeded");
totalmint2 += _mintAmount;
}else if(salesStage == 3){
require(presales3minted[_initialOwner] + _mintAmount <= presalesMaxToken, "Max 2 Token Per User");
require(totalmint3 + _mintAmount <= phaseSellingLimit3, "phase NFT limit exceeded");
totalmint3 += _mintAmount;
}
uint256 supply = totalSupply().add(totalReserve).sub(reserved);
require(_mintAmount > 0, "need to mint at least 1 NFT");
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
require(minted[_initialOwner] + _mintAmount <= maxSupply, "Max Token Per User");
require(isValidData(addressToString(_initialOwner), _sig), addressToString(_initialOwner));
require(msg.value == _mintAmount.mul(cost), "Incorrect msg.value");
sold += _mintAmount;
if(salesStage == 1){
presales1minted[_initialOwner] += _mintAmount;
}else if(salesStage == 2){
presales2minted[_initialOwner] += _mintAmount;
}
else if(salesStage == 3){
presales3minted[_initialOwner] += _mintAmount;
}
minted[_initialOwner] += _mintAmount;
for (uint256 i = 0; i < _mintAmount; i++) {
uint256 _id = totalSupply().add(totalReserve).add(1).sub(reserved);
creators[_id] = _initialOwner;
addressMintedBalance[_initialOwner]++;
_safeMint(_initialOwner, _id);
emit CurrentSalesStage(salesStage, _id);
}
return 0;
}
function publicsales(
address _initialOwner,
uint256 _mintAmount,
string calldata _uri
// bytes calldata _data
) external payable returns (uint256) {
require(salesStage == 4 , "Public Sales Is Closed");
uint256 supply = totalSupply().add(totalReserve).sub(reserved);
require(_mintAmount > 0, "need to mint at least 1 NFT");
require(supply + _mintAmount <= maxSupply, "max NFT limit exceeded");
require(presales4minted[_initialOwner] + _mintAmount <= presalesMaxToken, "Max 2 Token Per User");
presales4minted[_initialOwner] += _mintAmount;
require(msg.value == _mintAmount.mul(cost), "Incorrect msg.value");
sold += _mintAmount;
minted[_initialOwner] += _mintAmount;
for (uint256 i = 0; i < _mintAmount; i++) {
uint256 _id = totalSupply().add(totalReserve).add(1).sub(reserved);
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
creators[_id] = _initialOwner;
addressMintedBalance[_initialOwner]++;
_safeMint(_initialOwner, _id);
emit CurrentSalesStage(salesStage, _id);
}
return 0;
}
function setSalesStage(
uint16 stage
) public onlyOwner {
salesStage = stage;
}
function setCompanyWallet(
address payable newWallet
) public onlyOwner {
companyWallet = newWallet;
}
function ownerMint(
address _initialOwner,
uint256 _initialSupply,
string calldata _uri
// bytes calldata _data
) external onlyOwner returns (uint256) {
require(sold + _initialSupply <= maxSupply, "Max Token Minted");
sold += _initialSupply;
for (uint256 i = 0; i < _initialSupply; i++) {
uint256 _id = totalSupply().add(totalReserve).add(1).sub(reserved);
if (bytes(_uri).length > 0) {
emit URI(_uri, _id);
}
creators[_id] = msg.sender;
addressMintedBalance[_initialOwner]++;
_safeMint(_initialOwner, _id);
emit CurrentSalesStage(salesStage, _id);
}
return 0;
}
function walletOfOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 ownerTokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](ownerTokenCount);
for (uint256 i; i < ownerTokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
if(revealed == false) {
return notRevealedUri;
}
string memory currentBaseURI = _baseURI();
return bytes(currentBaseURI).length > 0
? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension))
: "";
}
//only owner
function reveal() public onlyOwner() {
revealed = true;
}
function setPhaseSellingLimit1(uint256 _newAmount) public onlyOwner() {
phaseSellingLimit1 = _newAmount;
}
function setPhaseSellingLimit2(uint256 _newAmount) public onlyOwner() {
phaseSellingLimit2 = _newAmount;
}
function setPhaseSellingLimit3(uint256 _newAmount) public onlyOwner() {
phaseSellingLimit3 = _newAmount;
}
function setNFTPrice(uint256 _newAmount) public onlyOwner() {
cost = _newAmount;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function setBaseExtension(string memory _newBaseExtension) public onlyOwner {
baseExtension = _newBaseExtension;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedUri = _notRevealedURI;
}
function pause(bool _state) public onlyOwner {
paused = _state;
}
function withdraw() public payable onlyOwner {
(bool success, ) = payable(msg.sender).call{value: address(this).balance}("");
require(success);
}
function toBytes(address a) public pure returns (bytes memory b){
assembly {
let m := mload(0x40)
a := and(a, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, a))
mstore(0x40, add(m, 52))
b := m
}
}
function addressToString(address _addr) public pure returns(string memory) {
bytes32 value = bytes32(uint(uint160(_addr)));
bytes memory alphabet = "0123456789abcdef";
bytes memory str = new bytes(42);
str[0] = "0";
str[1] = "x";
for (uint i = 0; i < 20; i++) {
str[2+i*2] = alphabet[uint(uint8(value[i + 12] >> 4))];
str[3+i*2] = alphabet[uint(uint8(value[i + 12] & 0x0f))];
}
return string(str);
}
function toAsciiString(address x) public pure returns (string memory) {
bytes memory s = new bytes(40);
for (uint i = 0; i < 20; i++) {
bytes1 b = bytes1(uint8(uint(uint160(x)) / (2**(8*(19 - i)))));
bytes1 hi = bytes1(uint8(b) / 16);
bytes1 lo = bytes1(uint8(b) - 16 * uint8(hi));
s[2*i] = char(hi);
s[2*i+1] = char(lo);
}
return string(s);
}
function char(
bytes1 b
) internal pure returns (bytes1 c) {
if (uint8(b) < 10) return bytes1(uint8(b) + 0x30);
else return bytes1(uint8(b) + 0x57);
}
function bytes32ToString(bytes32 _bytes32) public pure returns (string memory) {
uint8 i = 0;
bytes memory bytesArray = new bytes(64);
for (i = 0; i < bytesArray.length; i++) {
uint8 _f = uint8(_bytes32[i/2] & 0x0f);
uint8 _l = uint8(_bytes32[i/2] >> 4);
bytesArray[i] = toByte(_f);
i = i + 1;
bytesArray[i] = toByte(_l);
}
return string(bytesArray);
}
function stringToBytes32(string memory source) public pure returns (bytes32 result) {
bytes memory tempEmptyStringTest = bytes(source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(source, 32))
}
}
function splitSignature(bytes memory sig)
public
pure
returns (uint8, bytes32, bytes32)
{
require(sig.length == 65);
bytes32 r;
bytes32 s;
uint8 v;
assembly {
// first 32 bytes, after the length prefix
r := mload(add(sig, 32))
// second 32 bytes
s := mload(add(sig, 64))
// final byte (first byte of the next 32 bytes)
v := byte(0, mload(add(sig, 96)))
}
return (v, r, s);
}
function recoverSigner(bytes32 message, bytes memory sig)
public
pure
returns (address)
{
uint8 v;
bytes32 r;
bytes32 s;
(v, r, s) = splitSignature(sig);
return ecrecover(message, v, r, s);
}
function isValidData(string memory _word, bytes memory sig) public view returns(bool){
bytes32 message = keccak256(abi.encodePacked(_word));
return (recoverSigner(message, sig) == signerAddress);
}
function toByte(uint8 _uint8) public pure returns (bytes1) {
if(_uint8 < 10) {
return bytes1(_uint8 + 48);
} else {
return bytes1(_uint8 + 87);
}
}
}
|
Integer division of two unsigned integers truncating the quotient, reverts on division by zero./ Solidity only automatically asserts when dividing by 0 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) {
require(b > 0, "SafeMath#div: DIVISION_BY_ZERO");
uint256 c = a / b;
return c;
}
| 8,953 |
pragma solidity 0.4.25;
contract TokenConfig {
string public constant NAME = "MANGO";
string public constant SYMBOL = "MANG";
uint8 public constant DECIMALS = 5;
uint public constant DECIMALSFACTOR = 10 ** uint(DECIMALS);
uint public constant TOTALSUPPLY = 10000000000 * DECIMALSFACTOR;
}
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
);
}
/**
* @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, "can't mul");
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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "can't sub with zero.");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two 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, "can't sub");
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, "add overflow");
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "can't mod with zero");
return a % b;
}
}
library SafeERC20 {
using SafeMath for uint256;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
require(token.transfer(to, value), "safeTransfer");
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
require(token.transferFrom(from, to, value), "safeTransferFrom");
}
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), "safeApprove");
require(token.approve(spender, value), "safeApprove");
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
require(token.approve(spender, newAllowance), "safeIncreaseAllowance");
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value);
require(token.approve(spender, newAllowance), "safeDecreaseAllowance");
}
}
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
constructor () internal {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "nonReentrant.");
}
}
/**
* @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, "only for 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), "address is zero.");
owner = newOwner;
emit OwnershipTransferred(owner, newOwner);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Paused(address account);
event Unpaused(address account);
bool private _paused;
constructor() internal {
_paused = false;
}
/**
* @return true if the contract is paused, false otherwise.
*/
function paused() public view returns(bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "paused.");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Not paused.");
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() public onlyOwner whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() public onlyOwner whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
/**
* @title Crowdsale white list address
*/
contract Whitelist is Ownable {
event WhitelistAdded(address addr);
event WhitelistRemoved(address addr);
mapping (address => bool) private _whitelist;
/**
* @dev add addresses to the whitelist
* @param addrs addresses
*/
function addWhiteListAddr(address[] addrs)
public
{
uint256 len = addrs.length;
for (uint256 i = 0; i < len; i++) {
_addAddressToWhitelist(addrs[i]);
}
}
/**
* @dev remove an address from the whitelist
* @param addr address
*/
function removeWhiteListAddr(address addr)
public
{
_removeAddressToWhitelist(addr);
}
/**
* @dev getter to determine if address is in whitelist
*/
function isWhiteListAddr(address addr)
public
view
returns (bool)
{
require(addr != address(0), "address is zero");
return _whitelist[addr];
}
modifier onlyAuthorised(address beneficiary) {
require(isWhiteListAddr(beneficiary),"Not authorised");
_;
}
/**
* @dev add an address to the whitelist
* @param addr address
*/
function _addAddressToWhitelist(address addr)
internal
onlyOwner
{
require(addr != address(0), "address is zero");
_whitelist[addr] = true;
emit WhitelistAdded(addr);
}
/**
* @dev remove an address from the whitelist
* @param addr address
*/
function _removeAddressToWhitelist(address addr)
internal
onlyOwner
{
require(addr != address(0), "address is zero");
_whitelist[addr] = false;
emit WhitelistRemoved(addr);
}
}
/**
* @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 / overridden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropriate to concatenate
* behavior.
*/
contract Crowdsale is TokenConfig, Pausable, ReentrancyGuard, Whitelist {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// The token being sold
IERC20 private _token;
// Address where funds are collected
address private _wallet;
// Address where funds are collected
address private _tokenholder;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 private _rate;
// Amount of contribution wei raised
uint256 private _weiRaised;
// Amount of token sold
uint256 private _tokenSoldAmount;
// Minimum contribution amount of fund
uint256 private _minWeiAmount;
// balances of user should be sent
mapping (address => uint256) private _tokenBalances;
// balances of user fund
mapping (address => uint256) private _weiBalances;
// ICO period timestamp
uint256 private _openingTime;
uint256 private _closingTime;
// Amount of token hardcap
uint256 private _hardcap;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokensPurchased(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
event TokensDelivered(address indexed beneficiary, uint256 amount);
event RateChanged(uint256 rate);
event MinWeiChanged(uint256 minWei);
event PeriodChanged(uint256 open, uint256 close);
event HardcapChanged(uint256 hardcap);
constructor(
uint256 rate,
uint256 minWeiAmount,
address wallet,
address tokenholder,
IERC20 token,
uint256 hardcap,
uint256 openingTime,
uint256 closingTime
) public {
require(rate > 0, "Rate is lower than zero.");
require(wallet != address(0), "Wallet address is zero");
require(tokenholder != address(0), "Tokenholder address is zero");
require(token != address(0), "Token address is zero");
_rate = rate;
_minWeiAmount = minWeiAmount;
_wallet = wallet;
_tokenholder = tokenholder;
_token = token;
_hardcap = hardcap;
_openingTime = openingTime;
_closingTime = closingTime;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
* Note that other contracts will transfer fund with a base gas stipend
* of 2300, which is not enough to call buyTokens. Consider calling
* buyTokens directly when purchasing tokens from a contract.
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @return the token being sold.
*/
function token() public view returns(IERC20) {
return _token;
}
/**
* @return token hardcap.
*/
function hardcap() public view returns(uint256) {
return _hardcap;
}
/**
* @return the address where funds are collected.
*/
function wallet() public view returns(address) {
return _wallet;
}
/**
* @return the number of token units a buyer gets per wei.
*/
function rate() public view returns(uint256) {
return _rate;
}
/**
* @return the amount of wei raised.
*/
function weiRaised() public view returns (uint256) {
return _weiRaised;
}
/**
* @return ICO opening time.
*/
function openingTime() public view returns (uint256) {
return _openingTime;
}
/**
* @return ICO closing time.
*/
function closingTime() public view returns (uint256) {
return _closingTime;
}
/**
* @return the amount of token raised.
*/
function tokenSoldAmount() public view returns (uint256) {
return _tokenSoldAmount;
}
/**
* @return the number of minimum amount buyer can fund.
*/
function minWeiAmount() public view returns(uint256) {
return _minWeiAmount;
}
/**
* @return is ICO period
*/
function isOpen() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return now >= _openingTime && now <= _closingTime;
}
/**
* @dev Gets the token balance of the specified address for deliver
* @param owner The address to query the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function tokenBalanceOf(address owner) public view returns (uint256) {
return _tokenBalances[owner];
}
/**
* @dev Gets the ETH 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 weiBalanceOf(address owner) public view returns (uint256) {
return _weiBalances[owner];
}
function setRate(uint256 value) public onlyOwner {
_rate = value;
emit RateChanged(value);
}
function setMinWeiAmount(uint256 value) public onlyOwner {
_minWeiAmount = value;
emit MinWeiChanged(value);
}
function setPeriodTimestamp(uint256 open, uint256 close)
public
onlyOwner
{
_openingTime = open;
_closingTime = close;
emit PeriodChanged(open, close);
}
function setHardcap(uint256 value) public onlyOwner {
_hardcap = value;
emit HardcapChanged(value);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* This function has a non-reentrancy guard, so it shouldn't be called by
* another `nonReentrant` function.
* @param beneficiary Recipient of the token purchase
*/
function buyTokens(address beneficiary)
public
nonReentrant
whenNotPaused
payable
{
uint256 weiAmount = msg.value;
_preValidatePurchase(beneficiary, weiAmount);
// Calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
require(_hardcap > _tokenSoldAmount.add(tokens), "Over hardcap");
// Update state
_weiRaised = _weiRaised.add(weiAmount);
_tokenSoldAmount = _tokenSoldAmount.add(tokens);
_weiBalances[beneficiary] = _weiBalances[beneficiary].add(weiAmount);
_tokenBalances[beneficiary] = _tokenBalances[beneficiary].add(tokens);
emit TokensPurchased(
msg.sender,
beneficiary,
weiAmount,
tokens
);
_forwardFunds();
}
/**
* @dev method that deliver token to user
*/
function deliverTokens(address[] users)
public
whenNotPaused
onlyOwner
{
uint256 len = users.length;
for (uint256 i = 0; i < len; i++) {
address user = users[i];
uint256 tokenAmount = _tokenBalances[user];
_deliverTokens(user, tokenAmount);
_tokenBalances[user] = 0;
emit TokensDelivered(user, tokenAmount);
}
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use `super` in contracts that inherit from Crowdsale to extend their validations.
* @param beneficiary Address performing the token purchase
* @param weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address beneficiary,
uint256 weiAmount
)
internal
view
onlyAuthorised(beneficiary)
{
require(weiAmount != 0, "Zero ETH");
require(weiAmount >= _minWeiAmount, "Must be equal or higher than minimum");
require(beneficiary != address(0), "Beneficiary address is zero");
require(isOpen(), "Sales is close");
}
/**
* @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.safeTransferFrom(_tokenholder, beneficiary, tokenAmount);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 weiAmount) internal view returns (uint256)
{
uint ethDecimals = 18;
require(DECIMALS <= ethDecimals, "");
uint256 covertedTokens = weiAmount;
if (DECIMALS != ethDecimals) {
covertedTokens = weiAmount.div((10 ** uint256(ethDecimals - DECIMALS)));
}
return covertedTokens.mul(_rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
_wallet.transfer(msg.value);
}
}
|
getter to determine if address is in whitelist/
|
function isWhiteListAddr(address addr)
public
view
returns (bool)
{
require(addr != address(0), "address is zero");
return _whitelist[addr];
}
| 6,439,316 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
interface IUniswapV2Pair {
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
}
interface IDroplet {
function drip () external;
}
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ADD_OVERFLOW');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'SUB_OVERFLOW');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'MUL_OVERFLOW');
}
}
library UniswapV2Library {
using SafeMath for uint;
// fetches and sorts the reserves for a pair
function getReserves (uint256 pair) internal view returns (uint reserveA, uint reserveB) {
address addr = address(pair >> 1);
uint direction = pair & 1;
(uint reserve0, uint reserve1,) = IUniswapV2Pair(addr).getReserves();
(reserveA, reserveB) = direction == 0 ? (reserve0, reserve1) : (reserve1, reserve0);
}
// 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, 'INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn.mul(997);
uint numerator = amountInWithFee.mul(reserveOut);
uint denominator = reserveIn.mul(1000).add(amountInWithFee);
amountOut = numerator / denominator;
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut (uint amountIn, uint256[] memory pairs) internal view returns (uint[] memory amounts) {
amounts = new uint[](pairs.length);
amounts[0] = amountIn;
for (uint i = 1; i < pairs.length; i++) {
(uint reserveIn, uint reserveOut) = getReserves(pairs[i]);
amounts[i] = getAmountOut(amounts[i - 1], reserveIn, reserveOut);
}
}
}
contract Utilities {
bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256)
bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256)
bytes4 private constant SIG_APPROVE = 0x095ea7b3; // approve(address,uint256)
bytes4 private constant SIG_BALANCE = 0x70a08231; // balanceOf(address)
/// @dev Provides a safe ERC-20.transfer version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function _safeTransfer (address token, address to, uint256 amount) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SIG_TRANSFER, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TRANSFER');
}
/// @dev Provides a safe ERC-20.transferFrom version for different ERC-20 implementations.
/// Reverts on a failed transfer.
/// @param token The address of the ERC-20 token.
/// @param from Transfer tokens from.
/// @param to Transfer tokens to.
/// @param amount The token amount.
function _safeTransferFrom (address token, address from, address to, uint256 amount) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SIG_TRANSFER_FROM, from, to, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TRANSFER_FROM');
}
/// @dev Provides a ETH transfer wrapper.
/// Reverts on a failed transfer.
/// @param to Transfer ETH to.
/// @param amount The ETH amount.
function _safeTransferETH (address to, uint256 amount) internal {
(bool success,) = to.call{value:amount}("");
require(success, 'TRANSFER_ETH');
}
/// @dev Provides a safe ERC-20.approve version for different ERC-20 implementations.
/// Reverts if failed.
/// @param token The address of the ERC-20 token.
/// @param spender of tokens.
/// @param amount Allowance amount.
function _safeApprove (address token, address spender, uint256 amount) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SIG_APPROVE, spender, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'APPROVE');
}
/// @dev Provides a wrapper for ERC-20.balanceOf.
/// Reverts if failed.
/// @param token The address of the ERC-20 token.
/// @param account Address of the account to query.
function _safeBalance (address token, address account) internal returns (uint256) {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SIG_BALANCE, account));
require(success, 'BALANCE');
return abi.decode(data, (uint256));
}
/// @dev Wrapper for `_safeTransfer` or `_safeTransferFrom` depending on `from`.
function _safeTransferWrapper (address token, address from, address to, uint256 amount) internal {
if (from == address(this)) {
_safeTransfer(token, to, amount);
} else {
_safeTransferFrom(token, from, to, amount);
}
}
/// @dev Helper function for redeeming EIP-2612 and DAI-style permits.
function _maybeRedeemPermit (address token, bytes memory permitData) internal {
if (permitData.length > 0) {
bool success;
assembly {
let dataPtr := add(permitData, 32)
let functionSig := shr(224, mload(dataPtr))
{
// check if permit.owner is address(this). Yes, paranoia.
// offset is <functionSig 4 bytes> + 12 bytes left-side part of permit.owner.
// shift it to the right by 12 bytes so that we can *safely* compare
let _owner := shr(96, mload(add(dataPtr, 16)))
if eq(_owner, address()) {
// even if a correct signature for this contract is just possible in theory,
// attempting this deserves no error message
revert(0, 0)
}
}
// EIP-2612 = 0xd505accf || dai-like (old) permit = 0x8fcbaf0c
if or( eq(functionSig, 0xd505accf), eq(functionSig, 0x8fcbaf0c) ) {
let size := mload(permitData)
success := call(gas(), token, 0, dataPtr, size, 0, 0)
}
}
require(success, 'PERMIT');
}
}
/// @dev Requires the initial amount to have already been sent to the first pair.
function _swap (uint[] memory amounts, uint256[] memory path, address _to) internal {
for (uint i = 1; i < path.length; i++) {
uint amountOut = amounts[i];
address pair = address(path[i] >> 1);
uint direction = path[i] & 1;
(uint amount0Out, uint amount1Out) = direction == 0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 1 ? address(path[i + 1] >> 1) : _to;
IUniswapV2Pair(pair).swap(
amount0Out, amount1Out, to, ""
);
}
}
function _swapExactTokensForTokens (
uint256[] memory path,
uint amountIn,
address from,
address to
) internal returns (uint[] memory amounts)
{
amounts = UniswapV2Library.getAmountsOut(amountIn, path);
_safeTransferWrapper(address(path[0]), from, address(path[1] >> 1), amounts[0]);
_swap(amounts, path, to);
}
function _swapExactETHForTokens (
uint256[] memory path,
uint amountIn,
address to
) internal returns (uint[] memory amounts)
{
amounts = UniswapV2Library.getAmountsOut(amountIn, path);
IWETH(path[0]).deposit{value: amounts[0]}();
_safeTransferWrapper(address(path[0]), address(this), address(path[1] >> 1), amounts[0]);
_swap(amounts, path, to);
}
function _swapExactTokensForETH (
uint256[] memory path,
uint amountIn,
address from,
address to,
address weth
) internal returns (uint[] memory amounts)
{
amounts = UniswapV2Library.getAmountsOut(amountIn, path);
_safeTransferWrapper(address(path[0]), from, address(path[1] >> 1), amounts[0]);
_swap(amounts, path, address(this));
uint256 finalOutputAmount = amounts[amounts.length - 1];
IWETH(weth).withdraw(finalOutputAmount);
_safeTransferETH(to, finalOutputAmount);
}
}
|
Provides a safe ERC-20.approve version for different ERC-20 implementations. Reverts if failed. token The address of the ERC-20 token. spender of tokens. amount Allowance amount.
|
function _safeApprove (address token, address spender, uint256 amount) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(SIG_APPROVE, spender, amount));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'APPROVE');
}
| 7,289,159 |
// An Ethereum Dapp that:
// i. Allows a real estate agent to register a new person
// ii. Allows a real estate agent to register a property sale against a registered person
//Note this app is used to help the author develop their skills in Solidity and is not meant to be used in any
//production environment
pragma solidity ^0.4.11;
//Define the RealEstate contract
contract RealEstate {
//Define the owner of the contract
address public owner;
//Create a variable to count the number of persons
uint personCount;
//Create a variable to count the number of property
uint PropertyCount;
//A modifier to restrict usage of functions to owner
modifier restricted() {
if (msg.sender == owner) _;
}
//Create an event which registers the latest number of property listings
event PropertyCounter(uint ActivePropertyCounter);
//Create an event which registers the latest number of persons registered
event PersonsCounter(uint CurrentPersonsCounter);
//Define RealEstate function
function RealEstate(uint initial) {
//Entering a person count parameter for initializing testing purposes in Truffle
personCount = initial;
//Define the owner as the one deploying the contract
owner = msg.sender;
}
// returns the personCount
function getpersonCount() constant returns (uint){
return personCount;
}
// returns the PropertyCount
function getPropertyCount() constant returns (uint){
return PropertyCount;
}
//=================Persons Map, Struct and Arrays START=================//
//Create a mapping table to store persons
mapping (bytes32 => Persons) public PersonMap;
//Create a struct to store the details of a person
struct Persons{
bytes32 FirstName; //First name of person
bytes32 LastName; //Last name of person
bytes32 Gender; //Gender of person
uint DateOfBirth; //Date of birth of person
bytes32 ImageLink; //File name to retreive person photo from the Sia storage network
address PersonAddress; //Register the Ethereum
}
//Create an array to store the person keys
bytes32[] PersonsArray;
// Add person
function addPerson(bytes32 NationalID, bytes32 FirstName, bytes32 LastName, bytes32 Gender, uint DateOfBirth, bytes32 ImageLink, address PersonAddress) {
var NewPerson = Persons(FirstName, LastName, Gender, DateOfBirth, ImageLink, PersonAddress);
PersonMap[NationalID] = NewPerson;
personCount++;
PersonsCounter(personCount);
PersonsArray.push(NationalID);
}
//Delete person
function removePerson(bytes32 NationalID) restricted {
delete PersonMap[NationalID];
personCount--;
}
//Return the details of a given person
function getPerson(bytes32 NationalID) constant returns (bytes32 FirstName, bytes32 LastName, bytes32 Gender, uint DateOfBirth, bytes32 ImageLink, address PersonAddress) {
return (PersonMap[NationalID].FirstName, PersonMap[NationalID].LastName, PersonMap[NationalID].Gender, PersonMap[NationalID].DateOfBirth, PersonMap[NationalID].ImageLink, PersonMap[NationalID].PersonAddress);
}
//List all registered persons
function listPersons() constant returns (
bytes32[] NationalID, bytes32[] FirstName, bytes32[] LastName, bytes32[] Gender, uint[] DateOfBirth, bytes32[] ImageLink, address[] Addresses
) {
//Create arrays to store each of the individual details of a person
bytes32[] memory NationalIDArray= new bytes32[](personCount);
bytes32[] memory FirstNameArray= new bytes32[](personCount);
bytes32[] memory LastNameArray= new bytes32[](personCount);
bytes32[] memory GenderArray= new bytes32[](personCount);
uint256[] memory DateOfBirthArray= new uint256[](personCount);
bytes32[] memory ImageLinkArray= new bytes32[](personCount);
address[] memory AddressArray= new address[](personCount);
//Store the persons details into the arrays
for(uint i = 0; i<personCount; i++){
NationalIDArray[i] = PersonsArray[i];
FirstNameArray[i] = PersonMap[PersonsArray[i]].FirstName;
LastNameArray[i] = PersonMap[PersonsArray[i]].LastName;
GenderArray[i] = PersonMap[PersonsArray[i]].Gender;
DateOfBirthArray[i] = PersonMap[PersonsArray[i]].DateOfBirth;
ImageLinkArray[i] = PersonMap[PersonsArray[i]].ImageLink;
AddressArray[i] = PersonMap[PersonsArray[i]].PersonAddress;
}
//Return the arrays containing person information
return ( NationalIDArray,FirstNameArray,LastNameArray,GenderArray,DateOfBirthArray,ImageLinkArray,AddressArray
);
}
//=================Persons Map, Struct and Arrays END=================//
//=================Properties Map, Struct and Arrays START=================//
//Create a mapping table to store property
mapping (bytes32 => Property) public PropertyMap;
//Create a struct to store the details of a property
struct Property{
bytes32 PropertyType;
bytes32 Address;
bytes32 City;
uint ZipCode;
bytes32 Country;
bytes32 ImageLink;
bytes32 NationalID;
uint SaleValue;
}
//Create an array to store the property keys
bytes32[] PropertyArray;
// Add property
function addProperty(bytes32 NationalID, bytes32 PropertyID, bytes32 PropertyType, bytes32 Address, bytes32 City, uint ZipCode, bytes32 Country, bytes32 ImageLink, uint SaleValue) {
var NewProperty = Property(PropertyType, Address, City, ZipCode, Country, ImageLink, NationalID, SaleValue);
PropertyMap[PropertyID] = NewProperty;
PropertyCount++;
PropertyCounter(PropertyCount);//Add the number properties to the event
PropertyArray.push(PropertyID);
}
//Delete property
function removeProperty(bytes32 PropertyID) restricted {
delete PropertyMap[PropertyID];
PropertyCount--;
}
//Return the details of a given property
function getProperty(bytes32 PropertyID) constant returns (bytes32 PropertyType, bytes32 Address, bytes32 City, uint ZipCode, uint SaleValue) {
return (PropertyMap[PropertyID].PropertyType, PropertyMap[PropertyID].Address, PropertyMap[PropertyID].City, PropertyMap[PropertyID].ZipCode, PropertyMap[PropertyID].SaleValue);
}
//List all properties
function listProperty() constant returns (
bytes32[] PropertyID, bytes32[] NationalID, bytes32[] PropertyType, bytes32[] Address, bytes32[] City, uint[] ZipCode, uint[] SaleValue
) {
//Create arrays to store each of the individual details of a property
bytes32[] memory PropertyIDArray= new bytes32[](PropertyCount);
bytes32[] memory NationalIDArray= new bytes32[](PropertyCount);
bytes32[] memory PropertyTypeArray= new bytes32[](PropertyCount);
bytes32[] memory AddressArray= new bytes32[](PropertyCount);
bytes32[] memory CityArray= new bytes32[](PropertyCount);
uint256[] memory ZipCodeArray= new uint256[](PropertyCount);
uint256[] memory SaleValueArray= new uint256[](PropertyCount);
//Store the properties details into the arrays
for(uint i = 0; i<PropertyCount; i++){
PropertyIDArray[i] = PropertyArray[i];
NationalIDArray[i] = PropertyMap[PropertyArray[i]].NationalID;
PropertyTypeArray[i] = PropertyMap[PropertyArray[i]].PropertyType;
AddressArray[i] = PropertyMap[PropertyArray[i]].Address;
CityArray[i] = PropertyMap[PropertyArray[i]].City;
ZipCodeArray[i] = PropertyMap[PropertyArray[i]].ZipCode;
SaleValueArray[i] = PropertyMap[PropertyArray[i]].SaleValue;
}
//Return property details arrays
return ( PropertyIDArray,NationalIDArray,PropertyTypeArray,AddressArray,CityArray,ZipCodeArray,SaleValueArray
);
}
//=================Properties Map, Struct and Arrays END=================//
}
|
Return the details of a given property
|
function getProperty(bytes32 PropertyID) constant returns (bytes32 PropertyType, bytes32 Address, bytes32 City, uint ZipCode, uint SaleValue) {
return (PropertyMap[PropertyID].PropertyType, PropertyMap[PropertyID].Address, PropertyMap[PropertyID].City, PropertyMap[PropertyID].ZipCode, PropertyMap[PropertyID].SaleValue);
}
| 7,284,749 |
./full_match/5/0xBE030626Ff369F4dd8FE5c272EFfEDE7a5A08c69/sources/contracts/abstracts/ERC20Abstract.sol
|
See {IERC20-totalSupply}./
|
function totalSupply() public view virtual override returns (uint256) {
return _erc20_totalSupply;
}
| 1,882,329 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721Tradable.sol";
/**
* @title Rocketeer
* Rocketeer - a contract for my non-fungible rocketeers
*/
contract Rocketeer is ERC721Tradable {
// ///////////////////////////////
// Globals
// ///////////////////////////////
// Max supply is the diameter of the moon in KM
uint256 private ROCKETEER_MAX_SUPPLY = 3475;
// Construct as Opensea tradable item
constructor(address _proxyRegistryAddress)
ERC721Tradable("Rocketeer", "RCT", _proxyRegistryAddress)
{
// Birth the genesis Rocketeers
spawnRocketeer( owner() );
}
// ///////////////////////////////
// Oracles
// ///////////////////////////////
// TODO: add Api data
// https://docs.opensea.io/docs/metadata-standards
function baseTokenURI() override public pure returns (string memory) {
// return "https://rocketeer.fans/testnetapi/rocketeer/";
return "https://rocketeer.fans/api/rocketeer/";
}
// TODO: add API link
// https://docs.opensea.io/docs/contract-level-metadata
function contractURI() public pure returns (string memory) {
// return "https://rocketeer.fans/testnetapi/collection/";
return "https://rocketeer.fans/api/rocketeer/";
}
// ///////////////////////////////
// Minting
// ///////////////////////////////
function spawnRocketeer( address _to ) public {
uint256 nextTokenId = _getNextTokenId();
// Every 42nd unit becomes a special edition, gas fees paid for but not owned by the minter
if( nextTokenId % 42 == 0 ) {
mintTo( owner() );
}
// No more than max supply
require( nextTokenId <= ROCKETEER_MAX_SUPPLY, "Maximum Rocketeer supply reached" );
mintTo( _to );
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {SafeMath} from "@openzeppelin/contracts/utils/math/SafeMath.sol";
import {EIP712Base} from "./EIP712Base.sol";
contract NativeMetaTransaction is EIP712Base {
using SafeMath for uint256;
bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256(
bytes(
"MetaTransaction(uint256 nonce,address from,bytes functionSignature)"
)
);
event MetaTransactionExecuted(
address userAddress,
address payable relayerAddress,
bytes functionSignature
);
mapping(address => uint256) nonces;
/*
* Meta transaction structure.
* No point of including value field here as if user is doing value transfer then he has the funds to pay for gas
* He should call the desired function directly in that case.
*/
struct MetaTransaction {
uint256 nonce;
address from;
bytes functionSignature;
}
function executeMetaTransaction(
address userAddress,
bytes memory functionSignature,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) public payable returns (bytes memory) {
MetaTransaction memory metaTx = MetaTransaction({
nonce: nonces[userAddress],
from: userAddress,
functionSignature: functionSignature
});
require(
verify(userAddress, metaTx, sigR, sigS, sigV),
"Signer and signature do not match"
);
// increase nonce for user (to avoid re-use)
nonces[userAddress] = nonces[userAddress].add(1);
emit MetaTransactionExecuted(
userAddress,
payable(msg.sender),
functionSignature
);
// Append userAddress and relayer address at the end to extract it from calling context
(bool success, bytes memory returnData) = address(this).call(
abi.encodePacked(functionSignature, userAddress)
);
require(success, "Function call not successful");
return returnData;
}
function hashMetaTransaction(MetaTransaction memory metaTx)
internal
pure
returns (bytes32)
{
return
keccak256(
abi.encode(
META_TRANSACTION_TYPEHASH,
metaTx.nonce,
metaTx.from,
keccak256(metaTx.functionSignature)
)
);
}
function getNonce(address user) public view returns (uint256 nonce) {
nonce = nonces[user];
}
function verify(
address signer,
MetaTransaction memory metaTx,
bytes32 sigR,
bytes32 sigS,
uint8 sigV
) internal view returns (bool) {
require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER");
return
signer ==
ecrecover(
toTypedMessageHash(hashMetaTransaction(metaTx)),
sigV,
sigR,
sigS
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {Initializable} from "./Initializable.sol";
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string constant public ERC712_VERSION = "1";
bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256(
bytes(
"EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)"
)
);
bytes32 internal domainSeperator;
// supposed to be called once while initializing.
// one of the contracts that inherits this contract follows proxy pattern
// so it is not possible to do this in a constructor
function _initializeEIP712(
string memory name
)
internal
initializer
{
_setDomainSeperator(name);
}
function _setDomainSeperator(string memory name) internal {
domainSeperator = keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(name)),
keccak256(bytes(ERC712_VERSION)),
address(this),
bytes32(getChainId())
)
);
}
function getDomainSeperator() public view returns (bytes32) {
return domainSeperator;
}
function getChainId() public view returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* Accept message hash and returns hash message in EIP712 compatible form
* So that it can be used to recover signer from signature signed using EIP712 formatted data
* https://eips.ethereum.org/EIPS/eip-712
* "\\x19" makes the encoding deterministic
* "\\x01" is the version byte to make it compatible to EIP-191
*/
function toTypedMessageHash(bytes32 messageHash)
internal
view
returns (bytes32)
{
return
keccak256(
abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
abstract contract ContextMixin {
function msgSender()
internal
view
returns (address payable sender)
{
if (msg.sender == address(this)) {
bytes memory array = msg.data;
uint256 index = msg.data.length;
assembly {
// Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those.
sender := and(
mload(add(array, index)),
0xffffffffffffffffffffffffffffffffffffffff
)
}
} else {
sender = payable(msg.sender);
}
return sender;
}
}
// 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/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "./common/meta-transactions/ContentMixin.sol";
import "./common/meta-transactions/NativeMetaTransaction.sol";
contract OwnableDelegateProxy {}
contract ProxyRegistry {
mapping(address => OwnableDelegateProxy) public proxies;
}
/**
* @title ERC721Tradable
* ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality.
* @dev I added the _getCurrentTokenId manually, the rest of the contract is verbatim from https://github.com/ProjectOpenSea/opensea-creatures/blob/master/contracts/ERC721Tradable.sol
*/
abstract contract ERC721Tradable is ContextMixin, ERC721Enumerable, NativeMetaTransaction, Ownable {
using SafeMath for uint256;
address proxyRegistryAddress;
uint256 private _currentTokenId = 0;
constructor(
string memory _name,
string memory _symbol,
address _proxyRegistryAddress
) ERC721(_name, _symbol) {
proxyRegistryAddress = _proxyRegistryAddress;
_initializeEIP712(_name);
}
/**
* @dev Mints a token to an address with a tokenURI.
* @param _to address of the future owner of the token
*/
function mintTo(address _to) internal {
uint256 newTokenId = _getNextTokenId();
_mint(_to, newTokenId);
_incrementTokenId();
}
/**
* @dev calculates the next token ID based on value of _currentTokenId
* @return uint256 for the next token ID
*/
function _getNextTokenId() internal view returns (uint256) {
return _currentTokenId.add(1);
}
/**
* @dev increments the value of _currentTokenId
*/
function _incrementTokenId() private {
_currentTokenId++;
}
function baseTokenURI() virtual public pure returns (string memory);
function tokenURI(uint256 _tokenId) override public pure returns (string memory) {
return string(abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId)));
}
/**
* Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings.
*/
function isApprovedForAll(address owner, address operator)
override
public
view
returns (bool)
{
// Whitelist OpenSea proxy contract for easy trading.
ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress);
if (address(proxyRegistry.proxies(owner)) == operator) {
return true;
}
return super.isApprovedForAll(owner, operator);
}
/**
* This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea.
*/
function _msgSender()
internal
override
view
returns (address sender)
{
return ContextMixin.msgSender();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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);
}
}
|
Every 42nd unit becomes a special edition, gas fees paid for but not owned by the minter
|
function spawnRocketeer( address _to ) public {
uint256 nextTokenId = _getNextTokenId();
if( nextTokenId % 42 == 0 ) {
mintTo( owner() );
}
mintTo( _to );
}
| 388,539 |
./partial_match/1/0x42F1e313E544857047673872e2B4dc4822F6caF7/sources/VMRDepo.sol
|
можно раздавать награды в периоде _currentState
|
function getRewards() internal {
if (msg.sender == owner) return;
uint256 _currentState = currentState;
uint256 _maxState = _currentState;
if (_currentState > states.length) _currentState = states.length;
while (_currentState > 0) {
GlobalState storage activeState = states[_currentState - 1];
uint256 depositedVMR = activeState.investors[msg.sender];
if (depositedVMR > 0)
{
uint256 _startRewardDate = activeState.startRewardDate;
if (_startRewardDate > 0 && now > _startRewardDate + delayBeforeRewardWithdrawn)
{
activeState.investors[msg.sender] = 0;
uint256 effectiveTokens = min(depositedVMR, activeState.maxVMRPerUser);
uint256 reward = activeState.rewardPerToken.wmul(effectiveTokens);
if (reward > 0) {
}
if (_currentState == _maxState) {
currentState++;
emit NewPeriodStarted(currentState);
}
}
}
_currentState--;
}
}
| 2,811,461 |
./partial_match/42/0x9cC49b574070379B71817Aa34643CB78Ad90A932/sources/GebUniswapV2KeeperFlashProxyETH.sol
|
Bids in multiple auctions atomically auctionIds Auction IDs amounts Amounts to bid
|
function multipleBid(uint[] calldata auctionIds, uint[] calldata amounts) external {
require(msg.sender == address(this), "GebUniswapV2KeeperFlashProxyETH/only-self");
for (uint i = 0; i < auctionIds.length; i++) {
auctionHouse.buyCollateral(auctionIds[i], amounts[i]);
}
}
| 8,942,370 |
pragma solidity 0.5.11; // optimization runs: 200, evm version: petersburg
/**
* @title DTokenInterface
* @author 0age
* @notice Interface for dTokens (in addition to the standard ERC20 interface).
*/
interface DTokenInterface {
// Events bear similarity to Compound's supply-related events.
event Mint(address minter, uint256 mintAmount, uint256 mintDTokens);
event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemDTokens);
event Accrue(uint256 dTokenExchangeRate, uint256 cTokenExchangeRate);
event CollectSurplus(uint256 surplusAmount, uint256 surplusCTokens);
// The block number and cToken + dToken exchange rates are updated on accrual.
struct AccrualIndex {
uint112 dTokenExchangeRate;
uint112 cTokenExchangeRate;
uint32 block;
}
// These external functions trigger accrual on the dToken and backing cToken.
function mint(uint256 underlyingToSupply) external returns (uint256 dTokensMinted);
function redeem(uint256 dTokensToBurn) external returns (uint256 underlyingReceived);
function redeemUnderlying(uint256 underelyingToReceive) external returns (uint256 dTokensBurned);
function pullSurplus() external returns (uint256 cTokenSurplus);
// These external functions only trigger accrual on the dToken.
function mintViaCToken(uint256 cTokensToSupply) external returns (uint256 dTokensMinted);
function redeemToCToken(uint256 dTokensToBurn) external returns (uint256 cTokensReceived);
function redeemUnderlyingToCToken(uint256 underlyingToReceive) external returns (uint256 dTokensBurned);
function accrueInterest() external;
function transferUnderlying(
address recipient, uint256 underlyingEquivalentAmount
) external returns (bool success);
function transferUnderlyingFrom(
address sender, address recipient, uint256 underlyingEquivalentAmount
) external returns (bool success);
// This function provides basic meta-tx support and does not trigger accrual.
function modifyAllowanceViaMetaTransaction(
address owner,
address spender,
uint256 value,
bool increase,
uint256 expiration,
bytes32 salt,
bytes calldata signatures
) external returns (bool success);
// View and pure functions do not trigger accrual on the dToken or the cToken.
function getMetaTransactionMessageHash(
bytes4 functionSelector, bytes calldata arguments, uint256 expiration, bytes32 salt
) external view returns (bytes32 digest, bool valid);
function totalSupplyUnderlying() external view returns (uint256);
function balanceOfUnderlying(address account) external view returns (uint256 underlyingBalance);
function exchangeRateCurrent() external view returns (uint256 dTokenExchangeRate);
function supplyRatePerBlock() external view returns (uint256 dTokenInterestRate);
function accrualBlockNumber() external view returns (uint256 blockNumber);
function getSurplus() external view returns (uint256 cTokenSurplus);
function getSurplusUnderlying() external view returns (uint256 underlyingSurplus);
function getSpreadPerBlock() external view returns (uint256 rateSpread);
function getVersion() external pure returns (uint256 version);
function getCToken() external pure returns (address cToken);
function getUnderlying() external pure returns (address underlying);
}
interface ERC20Interface {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
}
interface ERC1271Interface {
function isValidSignature(
bytes calldata data, bytes calldata signature
) external view returns (bytes4 magicValue);
}
interface CTokenInterface {
function mint(uint256 mintAmount) external returns (uint256 err);
function redeem(uint256 redeemAmount) external returns (uint256 err);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256 err);
function accrueInterest() external returns (uint256 err);
function transfer(address recipient, uint256 value) external returns (bool);
function transferFrom(address sender, address recipient, uint256 value) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function balanceOfUnderlying(address account) external returns (uint256 balance);
function exchangeRateCurrent() external returns (uint256 exchangeRate);
function getCash() external view returns (uint256);
function totalSupply() external view returns (uint256 supply);
function totalBorrows() external view returns (uint256 borrows);
function totalReserves() external view returns (uint256 reserves);
function interestRateModel() external view returns (address model);
function reserveFactorMantissa() external view returns (uint256 factor);
function supplyRatePerBlock() external view returns (uint256 rate);
function exchangeRateStored() external view returns (uint256 rate);
function accrualBlockNumber() external view returns (uint256 blockNumber);
function balanceOf(address account) external view returns (uint256 balance);
function allowance(address owner, address spender) external view returns (uint256);
}
interface CUSDCInterestRateModelInterface {
function getBorrowRate(
uint256 cash, uint256 borrows, uint256 reserves
) external view returns (uint256 err, uint256 borrowRate);
}
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
return c;
}
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
/**
* @title DharmaTokenOverrides
* @author 0age
* @notice A collection of internal view and pure functions that should be
* overridden by the ultimate Dharma Token implementation.
*/
contract DharmaTokenOverrides {
/**
* @notice Internal view function to get the current cToken exchange rate and
* supply rate per block. This function is meant to be overridden by the
* dToken that inherits this contract.
* @return The current cToken exchange rate, or amount of underlying tokens
* that are redeemable for each cToken, and the cToken supply rate per block
* (with 18 decimal places added to each returned rate).
*/
function _getCurrentCTokenRates() internal view returns (
uint256 exchangeRate, uint256 supplyRate
);
/**
* @notice Internal pure function to supply the name of the underlying token.
* @return The name of the underlying token.
*/
function _getUnderlyingName() internal pure returns (string memory underlyingName);
/**
* @notice Internal pure function to supply the address of the underlying
* token.
* @return The address of the underlying token.
*/
function _getUnderlying() internal pure returns (address underlying);
/**
* @notice Internal pure function to supply the symbol of the backing cToken.
* @return The symbol of the backing cToken.
*/
function _getCTokenSymbol() internal pure returns (string memory cTokenSymbol);
/**
* @notice Internal pure function to supply the address of the backing cToken.
* @return The address of the backing cToken.
*/
function _getCToken() internal pure returns (address cToken);
/**
* @notice Internal pure function to supply the name of the dToken.
* @return The name of the dToken.
*/
function _getDTokenName() internal pure returns (string memory dTokenName);
/**
* @notice Internal pure function to supply the symbol of the dToken.
* @return The symbol of the dToken.
*/
function _getDTokenSymbol() internal pure returns (string memory dTokenSymbol);
/**
* @notice Internal pure function to supply the address of the vault that
* receives surplus cTokens whenever the surplus is pulled.
* @return The address of the vault.
*/
function _getVault() internal pure returns (address vault);
}
/**
* @title DharmaTokenHelpers
* @author 0age
* @notice A collection of constants and internal pure functions used by Dharma
* Tokens.
*/
contract DharmaTokenHelpers is DharmaTokenOverrides {
using SafeMath for uint256;
uint8 internal constant _DECIMALS = 8; // matches cToken decimals
uint256 internal constant _SCALING_FACTOR = 1e18;
uint256 internal constant _SCALING_FACTOR_MINUS_ONE = 999999999999999999;
uint256 internal constant _HALF_OF_SCALING_FACTOR = 5e17;
uint256 internal constant _COMPOUND_SUCCESS = 0;
uint256 internal constant _MAX_UINT_112 = 5192296858534827628530496329220095;
/* solhint-disable separate-by-one-line-in-contract */
uint256 internal constant _MAX_UNMALLEABLE_S = (
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
);
/* solhint-enable separate-by-one-line-in-contract */
/**
* @notice Internal pure function to determine if a call to Compound succeeded
* and to revert, supplying the reason, if it failed. Failure can be caused by
* a call that reverts, or by a call that does not revert but returns a
* non-zero error code.
* @param functionSelector bytes4 The function selector that was called.
* @param ok bool A boolean representing whether the call returned or
* reverted.
* @param data bytes The data provided by the returned or reverted call.
*/
function _checkCompoundInteraction(
bytes4 functionSelector, bool ok, bytes memory data
) internal pure {
CTokenInterface cToken;
if (ok) {
if (
functionSelector == cToken.transfer.selector ||
functionSelector == cToken.transferFrom.selector
) {
require(
abi.decode(data, (bool)), string(
abi.encodePacked(
"Compound ",
_getCTokenSymbol(),
" contract returned false on calling ",
_getFunctionName(functionSelector),
"."
)
)
);
} else {
uint256 compoundError = abi.decode(data, (uint256)); // throw on no data
if (compoundError != _COMPOUND_SUCCESS) {
revert(
string(
abi.encodePacked(
"Compound ",
_getCTokenSymbol(),
" contract returned error code ",
uint8((compoundError / 10) + 48),
uint8((compoundError % 10) + 48),
" on calling ",
_getFunctionName(functionSelector),
"."
)
)
);
}
}
} else {
revert(
string(
abi.encodePacked(
"Compound ",
_getCTokenSymbol(),
" contract reverted while attempting to call ",
_getFunctionName(functionSelector),
": ",
_decodeRevertReason(data)
)
)
);
}
}
/**
* @notice Internal pure function to get a Compound function name based on the
* selector.
* @param functionSelector bytes4 The function selector.
* @return The name of the function as a string.
*/
function _getFunctionName(
bytes4 functionSelector
) internal pure returns (string memory functionName) {
CTokenInterface cToken;
if (functionSelector == cToken.mint.selector) {
functionName = "mint";
} else if (functionSelector == cToken.redeem.selector) {
functionName = "redeem";
} else if (functionSelector == cToken.redeemUnderlying.selector) {
functionName = "redeemUnderlying";
} else if (functionSelector == cToken.transferFrom.selector) {
functionName = "transferFrom";
} else if (functionSelector == cToken.transfer.selector) {
functionName = "transfer";
} else if (functionSelector == cToken.accrueInterest.selector) {
functionName = "accrueInterest";
} else {
functionName = "an unknown function";
}
}
/**
* @notice Internal pure function to decode revert reasons. The revert reason
* prefix is removed and the remaining string argument is decoded.
* @param revertData bytes The raw data supplied alongside the revert.
* @return The decoded revert reason string.
*/
function _decodeRevertReason(
bytes memory revertData
) internal pure returns (string memory revertReason) {
// Solidity prefixes revert reason with 0x08c379a0 -> Error(string) selector
if (
revertData.length > 68 && // prefix (4) + position (32) + length (32)
revertData[0] == byte(0x08) &&
revertData[1] == byte(0xc3) &&
revertData[2] == byte(0x79) &&
revertData[3] == byte(0xa0)
) {
// Get the revert reason without the prefix from the revert data.
bytes memory revertReasonBytes = new bytes(revertData.length - 4);
for (uint256 i = 4; i < revertData.length; i++) {
revertReasonBytes[i - 4] = revertData[i];
}
// Decode the resultant revert reason as a string.
revertReason = abi.decode(revertReasonBytes, (string));
} else {
// Simply return the default, with no revert reason.
revertReason = "(no revert reason)";
}
}
/**
* @notice Internal pure function to construct a failure message string for
* the revert reason on transfers of underlying tokens that do not succeed.
* @return The failure message.
*/
function _getTransferFailureMessage() internal pure returns (
string memory message
) {
message = string(
abi.encodePacked(_getUnderlyingName(), " transfer failed.")
);
}
/**
* @notice Internal pure function to convert a uint256 to a uint112, reverting
* if the conversion would cause an overflow.
* @param input uint256 The unsigned integer to convert.
* @return The converted unsigned integer.
*/
function _safeUint112(uint256 input) internal pure returns (uint112 output) {
require(input <= _MAX_UINT_112, "Overflow on conversion to uint112.");
output = uint112(input);
}
/**
* @notice Internal pure function to convert an underlying amount to a dToken
* or cToken amount using an exchange rate and fixed-point arithmetic.
* @param underlying uint256 The underlying amount to convert.
* @param exchangeRate uint256 The exchange rate (multiplied by 10^18).
* @param roundUp bool Whether the final amount should be rounded up - it will
* instead be truncated (rounded down) if this value is false.
* @return The cToken or dToken amount.
*/
function _fromUnderlying(
uint256 underlying, uint256 exchangeRate, bool roundUp
) internal pure returns (uint256 amount) {
if (roundUp) {
amount = (
(underlying.mul(_SCALING_FACTOR)).add(exchangeRate.sub(1))
).div(exchangeRate);
} else {
amount = (underlying.mul(_SCALING_FACTOR)).div(exchangeRate);
}
}
/**
* @notice Internal pure function to convert a dToken or cToken amount to the
* underlying amount using an exchange rate and fixed-point arithmetic.
* @param amount uint256 The cToken or dToken amount to convert.
* @param exchangeRate uint256 The exchange rate (multiplied by 10^18).
* @param roundUp bool Whether the final amount should be rounded up - it will
* instead be truncated (rounded down) if this value is false.
* @return The underlying amount.
*/
function _toUnderlying(
uint256 amount, uint256 exchangeRate, bool roundUp
) internal pure returns (uint256 underlying) {
if (roundUp) {
underlying = (
(amount.mul(exchangeRate).add(_SCALING_FACTOR_MINUS_ONE)
) / _SCALING_FACTOR);
} else {
underlying = amount.mul(exchangeRate) / _SCALING_FACTOR;
}
}
/**
* @notice Internal pure function to convert an underlying amount to a dToken
* or cToken amount and back to the underlying, so as to properly capture
* rounding errors, by using an exchange rate and fixed-point arithmetic.
* @param underlying uint256 The underlying amount to convert.
* @param exchangeRate uint256 The exchange rate (multiplied by 10^18).
* @param roundUpOne bool Whether the intermediate dToken or cToken amount
* should be rounded up - it will instead be truncated (rounded down) if this
* value is false.
* @param roundUpTwo bool Whether the final underlying amount should be
* rounded up - it will instead be truncated (rounded down) if this value is
* false.
* @return The intermediate cToken or dToken amount and the final underlying
* amount.
*/
function _fromUnderlyingAndBack(
uint256 underlying, uint256 exchangeRate, bool roundUpOne, bool roundUpTwo
) internal pure returns (uint256 amount, uint256 adjustedUnderlying) {
amount = _fromUnderlying(underlying, exchangeRate, roundUpOne);
adjustedUnderlying = _toUnderlying(amount, exchangeRate, roundUpTwo);
}
}
/**
* @title DharmaTokenV2
* @author 0age (dToken mechanics derived from Compound cTokens, ERC20 mechanics
* derived from Open Zeppelin's ERC20 contract)
* @notice DharmaTokenV2 deprecates the interest-bearing component and prevents
* minting of new tokens or redeeming to cTokens. It also returns COMP in
* proportion to the respective dToken balance in relation to total supply.
*/
contract DharmaTokenV2 is ERC20Interface, DTokenInterface, DharmaTokenHelpers {
// Set the version of the Dharma Token as a constant.
uint256 private constant _DTOKEN_VERSION = 2;
ERC20Interface internal constant _COMP = ERC20Interface(
0xc00e94Cb662C3520282E6f5717214004A7f26888 // mainnet
);
// Set block number and dToken + cToken exchange rate in slot zero on accrual.
AccrualIndex private _accrualIndex;
// Slot one tracks the total issued dTokens.
uint256 private _totalSupply;
// Slots two and three are entrypoints into balance and allowance mappings.
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
// Slot four is an entrypoint into a mapping for used meta-transaction hashes.
mapping (bytes32 => bool) private _executedMetaTxs;
bool exchangeRateFrozen; // initially false
/**
* @notice Deprecated.
*/
function mint(
uint256 underlyingToSupply
) external returns (uint256 dTokensMinted) {
revert("Minting is no longer supported.");
}
/**
* @notice Deprecated.
*/
function mintViaCToken(
uint256 cTokensToSupply
) external returns (uint256 dTokensMinted) {
revert("Minting is no longer supported.");
}
/**
* @notice Redeem `dTokensToBurn` dTokens from `msg.sender`, use the
* corresponding cTokens to redeem the required underlying, and transfer the
* redeemed underlying tokens to `msg.sender`.
* @param dTokensToBurn uint256 The amount of dTokens to provide in exchange
* for underlying tokens.
* @return The amount of underlying received in return for the provided
* dTokens.
*/
function redeem(
uint256 dTokensToBurn
) external returns (uint256 underlyingReceived) {
require(exchangeRateFrozen, "Call `pullSurplus()` to freeze exchange rate first.");
// Instantiate interface for the underlying token.
ERC20Interface underlying = ERC20Interface(_getUnderlying());
require(dTokensToBurn > 0, "No funds specified to redeem.");
// Get the total supply, as well as current underlying and COMP balances.
uint256 originalSupply = _totalSupply;
uint256 underlyingBalance = underlying.balanceOf(address(this));
uint256 compBalance = _COMP.balanceOf(address(this));
// Apply dToken ratio to balances to determine amount to transfer out.
underlyingReceived = underlyingBalance.mul(dTokensToBurn) / originalSupply;
uint256 compReceived = compBalance.mul(dTokensToBurn) / originalSupply;
require(
underlyingReceived.add(compReceived) > 0,
"Supplied dTokens are insufficient to redeem."
);
// Burn the dTokens.
_burn(msg.sender, underlyingReceived, dTokensToBurn);
// Transfer out the proportion of each associated with the burned tokens.
if (underlyingReceived > 0) {
require(
underlying.transfer(msg.sender, underlyingReceived),
_getTransferFailureMessage()
);
}
if (compReceived > 0) {
require(
_COMP.transfer(msg.sender, compReceived),
"COMP transfer out failed."
);
}
}
/**
* @notice Deprecated.
*/
function redeemToCToken(
uint256 dTokensToBurn
) external returns (uint256 cTokensReceived) {
revert("Redeeming to cTokens is no longer supported.");
}
/**
* @notice Redeem the dToken equivalent value of the underlying token amount
* `underlyingToReceive` from `msg.sender`, use the corresponding cTokens to
* redeem the underlying, and transfer the underlying to `msg.sender`.
* @param underlyingToReceive uint256 The amount, denominated in the
* underlying token, of the cToken to redeem in exchange for the received
* underlying token.
* @return The amount of dTokens burned in exchange for the returned
* underlying tokens.
*/
function redeemUnderlying(
uint256 underlyingToReceive
) external returns (uint256 dTokensBurned) {
require(exchangeRateFrozen, "Call `pullSurplus()` to freeze exchange rate first.");
// Instantiate interface for the underlying token.
ERC20Interface underlying = ERC20Interface(_getUnderlying());
// Get the dToken exchange rate.
(uint256 dTokenExchangeRate, ) = _accrue(false);
// Determine dToken amount to burn using the exchange rate, rounded up.
dTokensBurned = _fromUnderlying(
underlyingToReceive, dTokenExchangeRate, true
);
// Determine dToken amount for returning COMP by rounding down.
uint256 dTokensForCOMP = _fromUnderlying(
underlyingToReceive, dTokenExchangeRate, false
);
// Get the total supply and current COMP balance.
uint256 originalSupply = _totalSupply;
uint256 compBalance = _COMP.balanceOf(address(this));
// Apply dToken ratio to COMP balance to determine amount to transfer out.
uint256 compReceived = compBalance.mul(dTokensForCOMP) / originalSupply;
require(
underlyingToReceive.add(compReceived) > 0,
"Supplied amount is insufficient to redeem."
);
// Burn the dTokens.
_burn(msg.sender, underlyingToReceive, dTokensBurned);
// Transfer out the proportion of each associated with the burned tokens.
if (underlyingToReceive > 0) {
require(
underlying.transfer(msg.sender, underlyingToReceive),
_getTransferFailureMessage()
);
}
if (compReceived > 0) {
require(
_COMP.transfer(msg.sender, compReceived),
"COMP transfer out failed."
);
}
}
/**
* @notice Deprecated.
*/
function redeemUnderlyingToCToken(
uint256 underlyingToReceive
) external returns (uint256 dTokensBurned) {
revert("Redeeming to cTokens is no longer supported.");
}
/**
* @notice Transfer cTokens with underlying value in excess of the total
* underlying dToken value to a dedicated "vault" account. A "hard" accrual
* will first be performed, triggering an accrual on both the cToken and the
* dToken.
* @return The amount of cTokens transferred to the vault account.
*/
function pullSurplus() external returns (uint256 cTokenSurplus) {
require(!exchangeRateFrozen, "No surplus left to pull.");
// Instantiate the interface for the backing cToken.
CTokenInterface cToken = CTokenInterface(_getCToken());
// Accrue interest on the cToken and ensure that the operation succeeds.
(bool ok, bytes memory data) = address(cToken).call(abi.encodeWithSelector(
cToken.accrueInterest.selector
));
_checkCompoundInteraction(cToken.accrueInterest.selector, ok, data);
// Accrue interest on the dToken, reusing the stored cToken exchange rate.
_accrue(false);
// Determine cToken surplus in underlying (cToken value - dToken value).
uint256 underlyingSurplus;
(underlyingSurplus, cTokenSurplus) = _getSurplus();
// Transfer cToken surplus to vault and ensure that the operation succeeds.
(ok, data) = address(cToken).call(abi.encodeWithSelector(
cToken.transfer.selector, _getVault(), cTokenSurplus
));
_checkCompoundInteraction(cToken.transfer.selector, ok, data);
emit CollectSurplus(underlyingSurplus, cTokenSurplus);
exchangeRateFrozen = true;
// Redeem all cTokens for underlying and ensure that the operation succeeds.
(ok, data) = address(cToken).call(abi.encodeWithSelector(
cToken.redeem.selector, cToken.balanceOf(address(this))
));
_checkCompoundInteraction(cToken.redeem.selector, ok, data);
}
/**
* @notice Deprecated.
*/
function accrueInterest() external {
revert("Interest accrual is longer supported.");
}
/**
* @notice Transfer `amount` dTokens from `msg.sender` to `recipient`.
* @param recipient address The account to transfer the dTokens to.
* @param amount uint256 The amount of dTokens to transfer.
* @return A boolean indicating whether the transfer was successful.
*/
function transfer(
address recipient, uint256 amount
) external returns (bool success) {
_transfer(msg.sender, recipient, amount);
success = true;
}
/**
* @notice Transfer dTokens equivalent to `underlyingEquivalentAmount`
* underlying from `msg.sender` to `recipient`.
* @param recipient address The account to transfer the dTokens to.
* @param underlyingEquivalentAmount uint256 The underlying equivalent amount
* of dTokens to transfer.
* @return A boolean indicating whether the transfer was successful.
*/
function transferUnderlying(
address recipient, uint256 underlyingEquivalentAmount
) external returns (bool success) {
// Accrue interest and retrieve the current dToken exchange rate.
(uint256 dTokenExchangeRate, ) = _accrue(true);
// Determine dToken amount to transfer using the exchange rate, rounded up.
uint256 dTokenAmount = _fromUnderlying(
underlyingEquivalentAmount, dTokenExchangeRate, true
);
// Transfer the dTokens.
_transfer(msg.sender, recipient, dTokenAmount);
success = true;
}
/**
* @notice Approve `spender` to transfer up to `value` dTokens on behalf of
* `msg.sender`.
* @param spender address The account to grant the allowance.
* @param value uint256 The size of the allowance to grant.
* @return A boolean indicating whether the approval was successful.
*/
function approve(
address spender, uint256 value
) external returns (bool success) {
_approve(msg.sender, spender, value);
success = true;
}
/**
* @notice Transfer `amount` dTokens from `sender` to `recipient` as long as
* `msg.sender` has sufficient allowance.
* @param sender address The account to transfer the dTokens from.
* @param recipient address The account to transfer the dTokens to.
* @param amount uint256 The amount of dTokens to transfer.
* @return A boolean indicating whether the transfer was successful.
*/
function transferFrom(
address sender, address recipient, uint256 amount
) external returns (bool success) {
_transferFrom(sender, recipient, amount);
success = true;
}
/**
* @notice Transfer dTokens eqivalent to `underlyingEquivalentAmount`
* underlying from `sender` to `recipient` as long as `msg.sender` has
* sufficient allowance.
* @param sender address The account to transfer the dTokens from.
* @param recipient address The account to transfer the dTokens to.
* @param underlyingEquivalentAmount uint256 The underlying equivalent amount
* of dTokens to transfer.
* @return A boolean indicating whether the transfer was successful.
*/
function transferUnderlyingFrom(
address sender, address recipient, uint256 underlyingEquivalentAmount
) external returns (bool success) {
// Accrue interest and retrieve the current dToken exchange rate.
(uint256 dTokenExchangeRate, ) = _accrue(true);
// Determine dToken amount to transfer using the exchange rate, rounded up.
uint256 dTokenAmount = _fromUnderlying(
underlyingEquivalentAmount, dTokenExchangeRate, true
);
// Transfer the dTokens and adjust allowance accordingly.
_transferFrom(sender, recipient, dTokenAmount);
success = true;
}
/**
* @notice Increase the current allowance of `spender` by `value` dTokens.
* @param spender address The account to grant the additional allowance.
* @param addedValue uint256 The amount to increase the allowance by.
* @return A boolean indicating whether the modification was successful.
*/
function increaseAllowance(
address spender, uint256 addedValue
) external returns (bool success) {
_approve(
msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)
);
success = true;
}
/**
* @notice Decrease the current allowance of `spender` by `value` dTokens.
* @param spender address The account to decrease the allowance for.
* @param subtractedValue uint256 The amount to subtract from the allowance.
* @return A boolean indicating whether the modification was successful.
*/
function decreaseAllowance(
address spender, uint256 subtractedValue
) external returns (bool success) {
_approve(
msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue)
);
success = true;
}
/**
* @notice Modify the current allowance of `spender` for `owner` by `value`
* dTokens, increasing it if `increase` is true otherwise decreasing it, via a
* meta-transaction that expires at `expiration` (or does not expire if the
* value is zero) and uses `salt` as an additional input, validated using
* `signatures`.
* @param owner address The account granting the modified allowance.
* @param spender address The account to modify the allowance for.
* @param value uint256 The amount to modify the allowance by.
* @param increase bool A flag that indicates whether the allowance will be
* increased by the specified value (if true) or decreased by it (if false).
* @param expiration uint256 A timestamp indicating how long the modification
* meta-transaction is valid for - a value of zero will signify no expiration.
* @param salt bytes32 An arbitrary salt to be provided as an additional input
* to the hash digest used to validate the signatures.
* @param signatures bytes A signature, or collection of signatures, that the
* owner must provide in order to authorize the meta-transaction. If the
* account of the owner does not have any runtime code deployed to it, the
* signature will be verified using ecrecover; otherwise, it will be supplied
* to the owner along with the message digest and context via ERC-1271 for
* validation.
* @return A boolean indicating whether the modification was successful.
*/
function modifyAllowanceViaMetaTransaction(
address owner,
address spender,
uint256 value,
bool increase,
uint256 expiration,
bytes32 salt,
bytes calldata signatures
) external returns (bool success) {
require(expiration == 0 || now <= expiration, "Meta-transaction expired.");
// Construct the meta-transaction's message hash based on relevant context.
bytes memory context = abi.encodePacked(
address(this),
// _DTOKEN_VERSION,
this.modifyAllowanceViaMetaTransaction.selector,
expiration,
salt,
abi.encode(owner, spender, value, increase)
);
bytes32 messageHash = keccak256(context);
// Ensure message hash has never been used before and register it as used.
require(!_executedMetaTxs[messageHash], "Meta-transaction already used.");
_executedMetaTxs[messageHash] = true;
// Construct the digest to compare signatures against using EIP-191 0x45.
bytes32 digest = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", messageHash)
);
// Calculate new allowance by applying modification to current allowance.
uint256 currentAllowance = _allowances[owner][spender];
uint256 newAllowance = (
increase ? currentAllowance.add(value) : currentAllowance.sub(value)
);
// Use EIP-1271 if owner is a contract - otherwise, use ecrecover.
if (_isContract(owner)) {
// Validate via ERC-1271 against the owner account.
bytes memory data = abi.encode(digest, context);
bytes4 magic = ERC1271Interface(owner).isValidSignature(data, signatures);
require(magic == bytes4(0x20c13b0b), "Invalid signatures.");
} else {
// Validate via ecrecover against the owner account.
_verifyRecover(owner, digest, signatures);
}
// Modify the allowance.
_approve(owner, spender, newAllowance);
success = true;
}
/**
* @notice View function to determine a meta-transaction message hash, and to
* determine if it is still valid (i.e. it has not yet been used and is not
* expired). The returned message hash will need to be prefixed using EIP-191
* 0x45 and hashed again in order to generate a final digest for the required
* signature - in other words, the same procedure utilized by `eth_Sign`.
* @param functionSelector bytes4 The function selector for the given
* meta-transaction. There is only one function selector available for V1:
* `0x2d657fa5` (the selector for `modifyAllowanceViaMetaTransaction`).
* @param arguments bytes The abi-encoded function arguments (aside from the
* `expiration`, `salt`, and `signatures` arguments) that should be supplied
* to the given function.
* @param expiration uint256 A timestamp indicating how long the given
* meta-transaction is valid for - a value of zero will signify no expiration.
* @param salt bytes32 An arbitrary salt to be provided as an additional input
* to the hash digest used to validate the signatures.
* @return The total supply.
*/
function getMetaTransactionMessageHash(
bytes4 functionSelector,
bytes calldata arguments,
uint256 expiration,
bytes32 salt
) external view returns (bytes32 messageHash, bool valid) {
// Construct the meta-transaction's message hash based on relevant context.
messageHash = keccak256(
abi.encodePacked(
address(this), functionSelector, expiration, salt, arguments
)
);
// The meta-transaction is valid if it has not been used and is not expired.
valid = (
!_executedMetaTxs[messageHash] && (expiration == 0 || now <= expiration)
);
}
/**
* @notice View function to get the total dToken supply.
* @return The total supply.
*/
function totalSupply() external view returns (uint256 dTokenTotalSupply) {
dTokenTotalSupply = _totalSupply;
}
/**
* @notice View function to get the total dToken supply, denominated in the
* underlying token.
* @return The total supply.
*/
function totalSupplyUnderlying() external view returns (
uint256 dTokenTotalSupplyInUnderlying
) {
(uint256 dTokenExchangeRate, ,) = _getExchangeRates(true);
// Determine total value of all issued dTokens, denominated as underlying.
dTokenTotalSupplyInUnderlying = _toUnderlying(
_totalSupply, dTokenExchangeRate, false
);
}
/**
* @notice View function to get the total dToken balance of an account.
* @param account address The account to check the dToken balance for.
* @return The balance of the given account.
*/
function balanceOf(address account) external view returns (uint256 dTokens) {
dTokens = _balances[account];
}
/**
* @notice View function to get the dToken balance of an account, denominated
* in the underlying equivalent value.
* @param account address The account to check the balance for.
* @return The total underlying-equivalent dToken balance.
*/
function balanceOfUnderlying(
address account
) external view returns (uint256 underlyingBalance) {
// Get most recent dToken exchange rate by determining accrued interest.
(uint256 dTokenExchangeRate, ,) = _getExchangeRates(true);
// Convert account balance to underlying equivalent using the exchange rate.
underlyingBalance = _toUnderlying(
_balances[account], dTokenExchangeRate, false
);
}
/**
* @notice View function to get the total allowance that `spender` has to
* transfer dTokens from the `owner` account using `transferFrom`.
* @param owner address The account that is granting the allowance.
* @param spender address The account that has been granted the allowance.
* @return The allowance of the given spender for the given owner.
*/
function allowance(
address owner, address spender
) external view returns (uint256 dTokenAllowance) {
dTokenAllowance = _allowances[owner][spender];
}
/**
* @notice View function to get the current dToken exchange rate (multiplied
* by 10^18).
* @return The current exchange rate.
*/
function exchangeRateCurrent() external view returns (
uint256 dTokenExchangeRate
) {
// Get most recent dToken exchange rate by determining accrued interest.
(dTokenExchangeRate, ,) = _getExchangeRates(true);
}
/**
* @notice View function to get the current dToken interest earned per block
* (multiplied by 10^18).
* @return The current interest rate.
*/
function supplyRatePerBlock() external view returns (
uint256 dTokenInterestRate
) {
(dTokenInterestRate,) = _getRatePerBlock();
}
/**
* @notice View function to get the block number where accrual was last
* performed.
* @return The block number where accrual was last performed.
*/
function accrualBlockNumber() external view returns (uint256 blockNumber) {
blockNumber = _accrualIndex.block;
}
/**
* @notice View function to get the total surplus, or the cToken balance that
* exceeds the aggregate underlying value of the total dToken supply.
* @return The total surplus in cTokens.
*/
function getSurplus() external view returns (uint256 cTokenSurplus) {
// Determine the cToken (cToken underlying value - dToken underlying value).
(, cTokenSurplus) = _getSurplus();
}
/**
* @notice View function to get the total surplus in the underlying, or the
* underlying equivalent of the cToken balance that exceeds the aggregate
* underlying value of the total dToken supply.
* @return The total surplus, denominated in the underlying.
*/
function getSurplusUnderlying() external view returns (
uint256 underlyingSurplus
) {
// Determine cToken surplus in underlying (cToken value - dToken value).
(underlyingSurplus, ) = _getSurplus();
}
/**
* @notice View function to get the interest rate spread taken by the dToken
* from the current cToken supply rate per block (multiplied by 10^18).
* @return The current interest rate spread.
*/
function getSpreadPerBlock() external view returns (uint256 rateSpread) {
(
uint256 dTokenInterestRate, uint256 cTokenInterestRate
) = _getRatePerBlock();
rateSpread = cTokenInterestRate.sub(dTokenInterestRate);
}
/**
* @notice Pure function to get the name of the dToken.
* @return The name of the dToken.
*/
function name() external pure returns (string memory dTokenName) {
dTokenName = _getDTokenName();
}
/**
* @notice Pure function to get the symbol of the dToken.
* @return The symbol of the dToken.
*/
function symbol() external pure returns (string memory dTokenSymbol) {
dTokenSymbol = _getDTokenSymbol();
}
/**
* @notice Pure function to get the number of decimals of the dToken.
* @return The number of decimals of the dToken.
*/
function decimals() external pure returns (uint8 dTokenDecimals) {
dTokenDecimals = _DECIMALS;
}
/**
* @notice Pure function to get the dToken version.
* @return The version of the dToken.
*/
function getVersion() external pure returns (uint256 version) {
version = _DTOKEN_VERSION;
}
/**
* @notice Pure function to get the address of the cToken backing this dToken.
* @return The address of the cToken backing this dToken.
*/
function getCToken() external pure returns (address cToken) {
cToken = _getCToken();
}
/**
* @notice Pure function to get the address of the underlying token of this
* dToken.
* @return The address of the underlying token for this dToken.
*/
function getUnderlying() external pure returns (address underlying) {
underlying = _getUnderlying();
}
/**
* @notice Private function to trigger accrual and to update the dToken and
* cToken exchange rates in storage if necessary. The `compute` argument can
* be set to false if an accrual has already taken place on the cToken before
* calling this function.
* @param compute bool A flag to indicate whether the cToken exchange rate
* needs to be computed - if false, it will simply be read from storage on the
* cToken in question.
* @return The current dToken and cToken exchange rates.
*/
function _accrue(bool compute) private returns (
uint256 dTokenExchangeRate, uint256 cTokenExchangeRate
) {
bool alreadyAccrued;
(
dTokenExchangeRate, cTokenExchangeRate, alreadyAccrued
) = _getExchangeRates(compute);
if (!alreadyAccrued) {
// Update storage with dToken + cToken exchange rates as of current block.
AccrualIndex storage accrualIndex = _accrualIndex;
accrualIndex.dTokenExchangeRate = _safeUint112(dTokenExchangeRate);
accrualIndex.cTokenExchangeRate = _safeUint112(cTokenExchangeRate);
accrualIndex.block = uint32(block.number);
emit Accrue(dTokenExchangeRate, cTokenExchangeRate);
}
}
/**
* @notice Private function to burn `amount` tokens by exchanging `exchanged`
* tokens from `account` and emit corresponding `Redeeem` & `Transfer` events.
* @param account address The account to burn tokens from.
* @param exchanged uint256 The amount of underlying tokens given for burning.
* @param amount uint256 The amount of tokens to burn.
*/
function _burn(address account, uint256 exchanged, uint256 amount) private {
require(
exchanged > 0 && amount > 0, "Redeem failed: insufficient funds supplied."
);
uint256 balancePriorToBurn = _balances[account];
require(
balancePriorToBurn >= amount, "Supplied amount exceeds account balance."
);
_totalSupply = _totalSupply.sub(amount);
_balances[account] = balancePriorToBurn - amount; // overflow checked above
emit Transfer(account, address(0), amount);
emit Redeem(account, exchanged, amount);
}
/**
* @notice Private function to move `amount` tokens from `sender` to
* `recipient` and emit a corresponding `Transfer` event.
* @param sender address The account to transfer tokens from.
* @param recipient address The account to transfer tokens to.
* @param amount uint256 The amount of tokens to transfer.
*/
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");
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "Insufficient funds.");
_balances[sender] = senderBalance - amount; // overflow checked above.
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @notice Private function to transfer `amount` tokens from `sender` to
* `recipient` and to deduct the transferred amount from the allowance of the
* caller unless the allowance is set to the maximum amount.
* @param sender address The account to transfer tokens from.
* @param recipient address The account to transfer tokens to.
* @param amount uint256 The amount of tokens to transfer.
*/
function _transferFrom(
address sender, address recipient, uint256 amount
) private {
_transfer(sender, recipient, amount);
uint256 callerAllowance = _allowances[sender][msg.sender];
if (callerAllowance != uint256(-1)) {
require(callerAllowance >= amount, "Insufficient allowance.");
_approve(sender, msg.sender, callerAllowance - amount); // overflow safe.
}
}
/**
* @notice Private function to set the allowance for `spender` to transfer up
* to `value` tokens on behalf of `owner`.
* @param owner address The account that has granted the allowance.
* @param spender address The account to grant the allowance.
* @param value uint256 The size of the allowance to grant.
*/
function _approve(address owner, address spender, uint256 value) private {
require(owner != address(0), "ERC20: approve for the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @notice Private view function to get the latest dToken and cToken exchange
* rates and provide the value for each. The `compute` argument can be set to
* false if an accrual has already taken place on the cToken before calling
* this function.
* @param compute bool A flag to indicate whether the cToken exchange rate
* needs to be computed - if false, it will simply be read from storage on the
* cToken in question.
* @return The dToken and cToken exchange rate, as well as a boolean
* indicating if interest accrual has been processed already or needs to be
* calculated and placed in storage.
*/
function _getExchangeRates(bool compute) private view returns (
uint256 dTokenExchangeRate, uint256 cTokenExchangeRate, bool fullyAccrued
) {
// Get the stored accrual block and dToken + cToken exhange rates.
AccrualIndex memory accrualIndex = _accrualIndex;
uint256 storedDTokenExchangeRate = uint256(accrualIndex.dTokenExchangeRate);
uint256 storedCTokenExchangeRate = uint256(accrualIndex.cTokenExchangeRate);
uint256 accrualBlock = uint256(accrualIndex.block);
// Use stored exchange rates if an accrual has already occurred this block.
fullyAccrued = (accrualBlock == block.number);
if (fullyAccrued) {
dTokenExchangeRate = storedDTokenExchangeRate;
cTokenExchangeRate = storedCTokenExchangeRate;
} else {
// Only compute cToken exchange rate if it has not accrued this block.
if (compute) {
// Get current cToken exchange rate; inheriting contract overrides this.
(cTokenExchangeRate,) = _getCurrentCTokenRates();
} else {
// Otherwise, get the stored cToken exchange rate.
cTokenExchangeRate = CTokenInterface(_getCToken()).exchangeRateStored();
}
if (exchangeRateFrozen) {
dTokenExchangeRate = storedDTokenExchangeRate;
} else {
// Determine the cToken interest earned during the period.
uint256 cTokenInterest = (
(cTokenExchangeRate.mul(_SCALING_FACTOR)).div(storedCTokenExchangeRate)
).sub(_SCALING_FACTOR);
// Calculate dToken exchange rate by applying 90% of the cToken interest.
dTokenExchangeRate = storedDTokenExchangeRate.mul(
_SCALING_FACTOR.add(cTokenInterest.mul(9) / 10)
) / _SCALING_FACTOR;
}
}
}
/**
* @notice Private view function to get the total surplus, or cToken
* balance that exceeds the total dToken balance.
* @return The total surplus, denominated in both the underlying and in the
* cToken.
*/
function _getSurplus() private view returns (
uint256 underlyingSurplus, uint256 cTokenSurplus
) {
if (exchangeRateFrozen) {
underlyingSurplus = 0;
cTokenSurplus = 0;
} else {
// Instantiate the interface for the backing cToken.
CTokenInterface cToken = CTokenInterface(_getCToken());
(
uint256 dTokenExchangeRate, uint256 cTokenExchangeRate,
) = _getExchangeRates(true);
// Determine value of all issued dTokens in the underlying, rounded up.
uint256 dTokenUnderlying = _toUnderlying(
_totalSupply, dTokenExchangeRate, true
);
// Determine value of all retained cTokens in the underlying, rounded down.
uint256 cTokenUnderlying = _toUnderlying(
cToken.balanceOf(address(this)), cTokenExchangeRate, false
);
// Determine the size of the surplus in terms of underlying amount.
underlyingSurplus = cTokenUnderlying > dTokenUnderlying
? cTokenUnderlying - dTokenUnderlying // overflow checked above
: 0;
// Determine the cToken equivalent of this surplus amount.
cTokenSurplus = underlyingSurplus == 0
? 0
: _fromUnderlying(underlyingSurplus, cTokenExchangeRate, false);
}
}
/**
* @notice Private view function to get the current dToken and cToken interest
* supply rate per block (multiplied by 10^18).
* @return The current dToken and cToken interest rates.
*/
function _getRatePerBlock() private view returns (
uint256 dTokenSupplyRate, uint256 cTokenSupplyRate
) {
(, cTokenSupplyRate) = _getCurrentCTokenRates();
if (exchangeRateFrozen) {
dTokenSupplyRate = 0;
} else {
dTokenSupplyRate = cTokenSupplyRate.mul(9) / 10;
}
}
/**
* @notice Private view function to determine if a given account has runtime
* code or not - in other words, whether or not a contract is deployed to the
* account in question. Note that contracts that are in the process of being
* deployed will return false on this check.
* @param account address The account to check for contract runtime code.
* @return Whether or not there is contract runtime code at the account.
*/
function _isContract(address account) private view returns (bool isContract) {
uint256 size;
assembly { size := extcodesize(account) }
isContract = size > 0;
}
/**
* @notice Private pure function to verify that a given signature of a digest
* resolves to the supplied account. Any error, including incorrect length,
* malleable signature types, or unsupported `v` values, will cause a revert.
* @param account address The account to validate against.
* @param digest bytes32 The digest to use.
* @param signature bytes The signature to verify.
*/
function _verifyRecover(
address account, bytes32 digest, bytes memory signature
) private pure {
// Ensure the signature length is correct.
require(
signature.length == 65,
"Must supply a single 65-byte signature when owner is not a contract."
);
// Divide the signature in r, s and v variables.
bytes32 r;
bytes32 s;
uint8 v;
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
require(
uint256(s) <= _MAX_UNMALLEABLE_S,
"Signature `s` value cannot be potentially malleable."
);
require(v == 27 || v == 28, "Signature `v` value not permitted.");
require(account == ecrecover(digest, v, r, s), "Invalid signature.");
}
}
/**
* @title DharmaUSDCImplementationV2
* @author 0age (dToken mechanics derived from Compound cTokens, ERC20 methods
* derived from Open Zeppelin's ERC20 contract)
* @notice This contract provides the V2 implementation of Dharma USD Coin (or
* dUSDC), which effectively deprecates Dharma USD Coin.
*/
contract DharmaUSDCImplementationV2 is DharmaTokenV2 {
string internal constant _NAME = "Dharma USD Coin";
string internal constant _SYMBOL = "dUSDC";
string internal constant _UNDERLYING_NAME = "USD Coin";
string internal constant _CTOKEN_SYMBOL = "cUSDC";
CTokenInterface internal constant _CUSDC = CTokenInterface(
0x39AA39c021dfbaE8faC545936693aC917d5E7563 // mainnet
);
ERC20Interface internal constant _USDC = ERC20Interface(
0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48 // mainnet
);
address internal constant _VAULT = 0x7e4A8391C728fEd9069B2962699AB416628B19Fa;
uint256 internal constant _SCALING_FACTOR_SQUARED = 1e36;
/**
* @notice Internal view function to get the current cUSDC exchange rate and
* supply rate per block.
* @return The current cUSDC exchange rate, or amount of USDC that is
* redeemable for each cUSDC, and the cUSDC supply rate per block (with 18
* decimal places added to each returned rate).
*/
function _getCurrentCTokenRates() internal view returns (
uint256 exchangeRate, uint256 supplyRate
) {
// Determine number of blocks that have elapsed since last cUSDC accrual.
uint256 blockDelta = block.number.sub(_CUSDC.accrualBlockNumber());
// Return stored values if accrual has already been performed this block.
if (blockDelta == 0) return (
_CUSDC.exchangeRateStored(), _CUSDC.supplyRatePerBlock()
);
// Determine total "cash" held by cUSDC contract.
uint256 cash = _USDC.balanceOf(address(_CUSDC));
// Get the latest interest rate model from the cUSDC contract.
CUSDCInterestRateModelInterface interestRateModel = (
CUSDCInterestRateModelInterface(_CUSDC.interestRateModel())
);
// Get the current stored total borrows, reserves, and reserve factor.
uint256 borrows = _CUSDC.totalBorrows();
uint256 reserves = _CUSDC.totalReserves();
uint256 reserveFactor = _CUSDC.reserveFactorMantissa();
// Get the current borrow rate from the latest cUSDC interest rate model.
(uint256 err, uint256 borrowRate) = interestRateModel.getBorrowRate(
cash, borrows, reserves
);
require(
err == _COMPOUND_SUCCESS, "Interest Rate Model borrow rate check failed."
);
// Get accumulated borrow interest via borrows, borrow rate, & block delta.
uint256 interest = borrowRate.mul(blockDelta).mul(borrows) / _SCALING_FACTOR;
// Update total borrows and reserves using calculated accumulated interest.
borrows = borrows.add(interest);
reserves = reserves.add(reserveFactor.mul(interest) / _SCALING_FACTOR);
// Get "underlying" via (cash + borrows - reserves).
uint256 underlying = (cash.add(borrows)).sub(reserves);
// Determine cUSDC exchange rate via underlying / total supply.
exchangeRate = (underlying.mul(_SCALING_FACTOR)).div(_CUSDC.totalSupply());
// Get "borrows per" by dividing total borrows by underlying and scaling up.
uint256 borrowsPer = (borrows.mul(_SCALING_FACTOR)).div(underlying);
// Supply rate is borrow rate * (1 - reserveFactor) * borrowsPer.
supplyRate = (
borrowRate.mul(_SCALING_FACTOR.sub(reserveFactor)).mul(borrowsPer)
) / _SCALING_FACTOR_SQUARED;
}
/**
* @notice Internal pure function to supply the name of the underlying token.
* @return The name of the underlying token.
*/
function _getUnderlyingName() internal pure returns (string memory underlyingName) {
underlyingName = _UNDERLYING_NAME;
}
/**
* @notice Internal pure function to supply the address of the underlying
* token.
* @return The address of the underlying token.
*/
function _getUnderlying() internal pure returns (address underlying) {
underlying = address(_USDC);
}
/**
* @notice Internal pure function to supply the symbol of the backing cToken.
* @return The symbol of the backing cToken.
*/
function _getCTokenSymbol() internal pure returns (string memory cTokenSymbol) {
cTokenSymbol = _CTOKEN_SYMBOL;
}
/**
* @notice Internal pure function to supply the address of the backing cToken.
* @return The address of the backing cToken.
*/
function _getCToken() internal pure returns (address cToken) {
cToken = address(_CUSDC);
}
/**
* @notice Internal pure function to supply the name of the dToken.
* @return The name of the dToken.
*/
function _getDTokenName() internal pure returns (string memory dTokenName) {
dTokenName = _NAME;
}
/**
* @notice Internal pure function to supply the symbol of the dToken.
* @return The symbol of the dToken.
*/
function _getDTokenSymbol() internal pure returns (string memory dTokenSymbol) {
dTokenSymbol = _SYMBOL;
}
/**
* @notice Internal pure function to supply the address of the vault that
* receives surplus cTokens whenever the surplus is pulled.
* @return The address of the vault.
*/
function _getVault() internal pure returns (address vault) {
vault = _VAULT;
}
}
|
View function to get the block number where accrual was last performed. return The block number where accrual was last performed./
|
function accrualBlockNumber() external view returns (uint256 blockNumber) {
blockNumber = _accrualIndex.block;
}
| 1,547,845 |
pragma solidity 0.4.21;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
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) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @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);
}
}
contract MintableAndPausableToken is PausableToken {
uint8 public constant decimals = 18;
bool public mintingFinished = false;
event Mint(address indexed to, uint256 amount);
event MintFinished();
event MintStarted();
modifier canMint() {
require(!mintingFinished);
_;
}
modifier cannotMint() {
require(mintingFinished);
_;
}
function mint(address _to, uint256 _amount)
external
onlyOwner
canMint
whenNotPaused
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
function finishMinting() external onlyOwner canMint returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
function startMinting() external onlyOwner cannotMint returns (bool) {
mintingFinished = false;
emit MintStarted();
return true;
}
}
/**
* Token upgrader interface inspired by Lunyr.
*
* Token upgrader transfers previous version tokens to a newer version.
* Token upgrader itself can be the token contract, or just a middle man contract doing the heavy lifting.
*/
contract TokenUpgrader {
uint public originalSupply;
/** Interface marker */
function isTokenUpgrader() external pure returns (bool) {
return true;
}
function upgradeFrom(address _from, uint256 _value) public {}
}
/**
* A token upgrade mechanism where users can opt-in amount of tokens to the next smart contract revision.
*
* First envisioned by Golem and Lunyr projects.
*/
contract UpgradeableToken is MintableAndPausableToken {
// Contract or person who can set the upgrade path.
address public upgradeMaster;
// Bollean value needs to be true to start upgrades
bool private upgradesAllowed;
// The next contract where the tokens will be migrated.
TokenUpgrader public tokenUpgrader;
// How many tokens we have upgraded by now.
uint public totalUpgraded;
/**
* Upgrade states.
* - NotAllowed: The child contract has not reached a condition where the upgrade can begin
* - Waiting: Token allows upgrade, but we don't have a new token version
* - ReadyToUpgrade: The token version is set, but not a single token has been upgraded yet
* - Upgrading: Token upgrader is set and the balance holders can upgrade their tokens
*/
enum UpgradeState { NotAllowed, Waiting, ReadyToUpgrade, Upgrading }
// Somebody has upgraded some of his tokens.
event Upgrade(address indexed _from, address indexed _to, uint256 _value);
// New token version available.
event TokenUpgraderIsSet(address _newToken);
modifier onlyUpgradeMaster {
// Only a master can designate the next token
require(msg.sender == upgradeMaster);
_;
}
modifier notInUpgradingState {
// Upgrade has already begun for token
require(getUpgradeState() != UpgradeState.Upgrading);
_;
}
// Do not allow construction without upgrade master set.
function UpgradeableToken(address _upgradeMaster) public {
upgradeMaster = _upgradeMaster;
}
// set a token upgrader
function setTokenUpgrader(address _newToken)
external
onlyUpgradeMaster
notInUpgradingState
{
require(canUpgrade());
require(_newToken != address(0));
tokenUpgrader = TokenUpgrader(_newToken);
// Handle bad interface
require(tokenUpgrader.isTokenUpgrader());
// Make sure that token supplies match in source and target
require(tokenUpgrader.originalSupply() == totalSupply_);
emit TokenUpgraderIsSet(tokenUpgrader);
}
// Allow the token holder to upgrade some of their tokens to a new contract.
function upgrade(uint _value) external {
UpgradeState state = getUpgradeState();
// Check upgrate state
require(state == UpgradeState.ReadyToUpgrade || state == UpgradeState.Upgrading);
// Validate input value
require(_value != 0);
balances[msg.sender] = balances[msg.sender].sub(_value);
// Take tokens out from circulation
totalSupply_ = totalSupply_.sub(_value);
totalUpgraded = totalUpgraded.add(_value);
// Token Upgrader reissues the tokens
tokenUpgrader.upgradeFrom(msg.sender, _value);
emit Upgrade(msg.sender, tokenUpgrader, _value);
}
/**
* Change the upgrade master.
* This allows us to set a new owner for the upgrade mechanism.
*/
function setUpgradeMaster(address _newMaster) external onlyUpgradeMaster {
require(_newMaster != address(0));
upgradeMaster = _newMaster;
}
// To be overriden to add functionality
function allowUpgrades() external onlyUpgradeMaster () {
upgradesAllowed = true;
}
// To be overriden to add functionality
function rejectUpgrades() external onlyUpgradeMaster () {
require(!(totalUpgraded > 0));
upgradesAllowed = false;
}
// Get the state of the token upgrade.
function getUpgradeState() public view returns(UpgradeState) {
if (!canUpgrade()) return UpgradeState.NotAllowed;
else if (address(tokenUpgrader) == address(0)) return UpgradeState.Waiting;
else if (totalUpgraded == 0) return UpgradeState.ReadyToUpgrade;
else return UpgradeState.Upgrading;
}
// To be overriden to add functionality
function canUpgrade() public view returns(bool) {
return upgradesAllowed;
}
}
contract Token is UpgradeableToken {
string public name = "Ydentity";
string public symbol = "YDY";
uint8 public constant decimals = 18;
// For patient incentive programs
uint256 public INITIAL_SUPPLY;
event UpdatedTokenInformation(string newName, string newSymbol);
function Token(address ydyWallet, address _upgradeMaster, uint256 _INITIAL_SUPPLY)
public
UpgradeableToken(_upgradeMaster)
{
INITIAL_SUPPLY = _INITIAL_SUPPLY * (10 ** uint256(decimals));
totalSupply_ = INITIAL_SUPPLY;
balances[ydyWallet] = INITIAL_SUPPLY;
emit Transfer(address(0), ydyWallet, INITIAL_SUPPLY);
}
/**
* Owner can update token information here
*/
function setTokenInformation(string _name, string _symbol) external onlyOwner {
name = _name;
symbol = _symbol;
emit UpdatedTokenInformation(name, symbol);
}
}
|
set a token upgrader Handle bad interface Make sure that token supplies match in source and target
|
function setTokenUpgrader(address _newToken)
external
onlyUpgradeMaster
notInUpgradingState
{
require(canUpgrade());
require(_newToken != address(0));
tokenUpgrader = TokenUpgrader(_newToken);
require(tokenUpgrader.isTokenUpgrader());
require(tokenUpgrader.originalSupply() == totalSupply_);
emit TokenUpgraderIsSet(tokenUpgrader);
}
| 1,174,640 |
./partial_match/1/0x0AF800600919311B1234ebBc20f46FD919129409/sources/Board2DeathSinners.sol
|
address payable giftAddress = payable(msg.sender);uint256 giftValue;
|
function setRevealed(bool _state) public payable onlyOwner {
revealed = _state;
address giftAddress = payable(ownerOf(randomNum(supply.current(), block.timestamp, supply.current() + 1) + 1));
uint256 giftValue = address(this).balance * 5/100 ;
require(success, "Could not send value!");
}
| 2,634,412 |
pragma solidity ^0.5.0;
import "./ByteSizeStorage.sol";
import "./SafeMath.sol";
contract ByteSize {
using SafeMath for uint256;
// Global Variable Storage
ByteSizeStorage public byteStorage;
// Event Triggers
event LoanRequested(uint256 loanID);
event LoanStarted(uint256 loanID);
event LoanDenied(uint256 loanID);
event LoanCanceled(uint256 loanID);
event LoanPaid(uint256 loanID, uint256 status);
event LoanCompleted(uint256 loanID);
enum Status { REQUESTED, ACCEPTED, ACTIVE, DENIED, CANCELED, COMPLETED, COMPLETED_LATE }
constructor(address _byteStorage) public {
byteStorage = ByteSizeStorage(_byteStorage);
}
/**
* @dev creates a loan object in the storage contract and updates
* its properties for the provided values
* @param lender the address of the wallet providing the loan
* @param amount the number of tokens requested for the loan
* @param duration the length in minutes that the loan should last for
* @param interest the interest percentage to be applied over the
duration of the loan
* @return <uint> the ID of the newly created loan
*/
function requestLoan(address lender, uint256 amount, uint32 duration, uint256 interest) public returns(uint256 loanID) {
require(lender != msg.sender, "Invalid request - you cannot be the lender!");
require(amount >= 100, "Invalid request - the minimum amount of wei should be 100");
require(duration >= 86400, "Invalid request - the loan length must be at least 24 hours");
require(interest < 100, "Invalid request - interest percentage cannot exceed the entire value of the loan!");
loanID = byteStorage.createLoan();
uint256 loanAmount = amount + ((amount * interest) / 100);
byteStorage.setAddress(keccak256(abi.encodePacked("lender")), lender, loanID);
byteStorage.setAddress(keccak256(abi.encodePacked("borrower")), msg.sender, loanID);
byteStorage.setUint(keccak256(abi.encodePacked("loan_amount")), amount, loanID);
byteStorage.setUint(keccak256(abi.encodePacked("loan_amount_interest")), loanAmount, loanID);
byteStorage.setUint(keccak256(abi.encodePacked("loan_length")), duration, loanID);
byteStorage.setUint(keccak256(abi.encodePacked("target_completion_date")), block.timestamp + duration, loanID);
byteStorage.setUint(keccak256(abi.encodePacked("loan_interest")), interest, loanID);
byteStorage.setUint(keccak256(abi.encodePacked("loan_status")), uint(Status.REQUESTED), loanID);
byteStorage.setUint(keccak256(abi.encodePacked("paid_back")), 0, loanID);
emit LoanRequested(loanID);
}
/**
* @dev if authorized, updates the state of the loan and activates it
* @param loanID ID of the requested loan
*/
function acceptLoan(uint loanID) public payable returns(bool) {
require(msg.sender == byteStorage.getAddress(loanID, keccak256(abi.encodePacked("lender"))), "Invalid request - you are not the lender of this loan");
uint256 loanAmount = byteStorage.getUint(loanID, keccak256(abi.encodePacked("loan_amount")));
require(msg.value == loanAmount, "Invalid request - the loan amount must be included in an accept transaction");
address payable borrower = address(uint160(byteStorage.getAddress(loanID, keccak256(abi.encodePacked("borrower")))));
if(byteStorage.getUint(loanID, keccak256(abi.encodePacked("status"))) == uint(Status.REQUESTED)) {
byteStorage.setUint(keccak256(abi.encodePacked("status")), uint(Status.ACCEPTED), loanID);
byteStorage.setUint(keccak256(abi.encodePacked("start_time")), block.timestamp, loanID);
borrower.transfer(loanAmount);
emit LoanStarted(loanID);
return true;
}
return false;
}
/**
* @dev allows the lender to deny a loan request made to them
* @param loanID ID of the requested loan
* @return <boolean> true if the loan was successfully denied, or false if not
*/
function denyLoan(uint loanID) public returns(bool) {
require(msg.sender == byteStorage.getAddress(loanID, keccak256(abi.encodePacked("lender"))), "Invalid request - you are not the lender of this loan");
if(byteStorage.getUint(loanID, keccak256(abi.encodePacked("status"))) == uint(Status.REQUESTED)) {
byteStorage.setUint(keccak256(abi.encodePacked("status")), uint(Status.DENIED), loanID);
byteStorage.setUint(keccak256(abi.encodePacked("end_time")), block.timestamp, loanID);
emit LoanDenied(loanID);
return true;
}
return false;
}
/**
* @dev allows the borrower to cancel a loan request they made, only before
* it gets accepted by the lender
* @param loanID ID of the requested loan
* @return <boolean> true if the loan was successfully canceled, or false if not
*/
function cancelLoan(uint loanID) public returns(bool) {
require(msg.sender == byteStorage.getAddress(loanID, keccak256(abi.encodePacked("borrower"))), "Invalid request - you are not the borrower of this loan");
if(byteStorage.getUint(loanID, keccak256(abi.encodePacked("status"))) == uint(Status.REQUESTED)) {
byteStorage.setUint(keccak256(abi.encodePacked("status")), uint(Status.CANCELED), loanID);
emit LoanCanceled(loanID);
return true;
}
return false;
}
/**
* @dev gives the borrower the ability to pay back towards a certain loan
* @param loanID ID of the requested loan
* @return <uint> the total of how much has been paid back so far
*/
function payLoan(uint loanID) public payable returns(uint) {
require(msg.sender == byteStorage.getAddress(loanID, keccak256(abi.encodePacked("borrower"))), "Invalid request - you are not the borrower of this loan");
require(msg.value > 0, "Invalid request - you must include an amount of wei in your transaction");
if(byteStorage.getUint(loanID, keccak256(abi.encodePacked("status"))) == uint(Status.ACCEPTED) ||
byteStorage.getUint(loanID, keccak256(abi.encodePacked("status"))) == uint(Status.ACTIVE)) {
uint paidBackSoFar = byteStorage.getUint(loanID, keccak256(abi.encodePacked("paid_back")));
uint loanAmount = byteStorage.getUint(loanID, keccak256(abi.encodePacked("loan_amount_interest")));
address payable lender = address(uint160(byteStorage.getAddress(loanID, keccak256(abi.encodePacked("lender")))));
uint256 targetDate = byteStorage.getUint(loanID, keccak256(abi.encodePacked("target_completion_date")));
if(paidBackSoFar <= loanAmount) {
if(paidBackSoFar + msg.value < loanAmount) {
byteStorage.setUint(keccak256(abi.encodePacked("paid_back")), paidBackSoFar + msg.value, loanID);
lender.transfer(msg.value);
emit LoanPaid(loanID, byteStorage.getUint(loanID, keccak256(abi.encodePacked("status"))));
return paidBackSoFar + msg.value;
} else {
if(block.timestamp > targetDate) {
byteStorage.setUint(keccak256(abi.encodePacked("status")), uint(Status.COMPLETED_LATE), loanID);
} else {
byteStorage.setUint(keccak256(abi.encodePacked("status")), uint(Status.COMPLETED), loanID);
}
byteStorage.setUint(keccak256(abi.encodePacked("paid_back")), paidBackSoFar + msg.value, loanID);
emit LoanCompleted(loanID);
return paidBackSoFar + msg.value;
}
}
} else {
revert("This loan is not in an active state");
}
}
}
|
return <uint> the ID of the newly created loan/
|
function requestLoan(address lender, uint256 amount, uint32 duration, uint256 interest) public returns(uint256 loanID) {
require(lender != msg.sender, "Invalid request - you cannot be the lender!");
require(amount >= 100, "Invalid request - the minimum amount of wei should be 100");
require(duration >= 86400, "Invalid request - the loan length must be at least 24 hours");
require(interest < 100, "Invalid request - interest percentage cannot exceed the entire value of the loan!");
loanID = byteStorage.createLoan();
uint256 loanAmount = amount + ((amount * interest) / 100);
byteStorage.setAddress(keccak256(abi.encodePacked("lender")), lender, loanID);
byteStorage.setAddress(keccak256(abi.encodePacked("borrower")), msg.sender, loanID);
byteStorage.setUint(keccak256(abi.encodePacked("loan_amount")), amount, loanID);
byteStorage.setUint(keccak256(abi.encodePacked("loan_amount_interest")), loanAmount, loanID);
byteStorage.setUint(keccak256(abi.encodePacked("loan_length")), duration, loanID);
byteStorage.setUint(keccak256(abi.encodePacked("target_completion_date")), block.timestamp + duration, loanID);
byteStorage.setUint(keccak256(abi.encodePacked("loan_interest")), interest, loanID);
byteStorage.setUint(keccak256(abi.encodePacked("loan_status")), uint(Status.REQUESTED), loanID);
byteStorage.setUint(keccak256(abi.encodePacked("paid_back")), 0, loanID);
emit LoanRequested(loanID);
}
| 2,515,158 |
./partial_match/1/0xE332E272c525991140fb3A6ea1eda646BD54fCBB/sources/LEMANO_NFT.sol
|
returns tokenIds same owner in 1 call from dapp /
|
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
function getTokenIdsOwnedBy(address _owner) virtual public view returns (uint256 [] memory){
return tokenIdsOwnedBy[_owner];
}
| 4,172,440 |
pragma solidity ^0.4.24;
//==============================================================================
// _ _ _ _|_ _ .
// (/_\/(/_| | | _\ .
//==============================================================================
contract PCKevents {
// 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 PCPAmount,
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 PCPAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a buy after round timer
// hit zero, and causes end round to be ran.
event onBuyAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 ethIn,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 PCPAmount,
uint256 genAmount
);
// (fomo3d long only) fired whenever a player tries a reload after round timer
// hit zero, and causes end round to be ran.
event onReLoadAndDistribute
(
address playerAddress,
bytes32 playerName,
uint256 compressedData,
uint256 compressedIDs,
address winnerAddr,
bytes32 winnerName,
uint256 amountWon,
uint256 newPot,
uint256 PCPAmount,
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 modularKey is PCKevents {}
contract PlayCoinKey is modularKey {
using SafeMath for *;
using NameFilter for string;
using PCKKeysCalcLong for uint256;
otherPCK private otherPCK_;
PlayCoinGodInterface constant private PCGod = PlayCoinGodInterface(0x6f93Be8fD47EBb62F54ebd149B58658bf9BaCF4f);
ProForwarderInterface constant private Pro_Inc = ProForwarderInterface(0x97354A7281693b7C93f6348Ba4eC38B9DDd76D6e);
PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x47D1c777f1853cac97E6b81226B1F5108FBD7B81);
//==============================================================================
// _ _ _ |`. _ _ _ |_ | _ _ .
// (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings)
//=================_|===========================================================
string constant public name = "PlayCoin Key";
string constant public symbol = "PCK";
uint256 private rndExtra_ = 15 minutes; // length of the very first ICO
uint256 private rndGap_ = 15 minutes; // length of ICO phase, set to 1 year for EOS.
uint256 constant private rndInit_ = 12 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_ = 6 hours; // max length a round timer can be
uint256 constant private rndMin_ = 10 minutes;
uint256 public rndReduceThreshold_ = 10e18; // 10ETH,reduce
bool public closed_ = false;
// admin is publish contract
address private admin = msg.sender;
//==============================================================================
// _| _ _|_ _ _ _ _|_ _ .
// (_|(_| | (_| _\(/_ | |_||_) . (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 => PCKdatasets.Player) public plyr_; // (pID => data) player data
mapping (uint256 => mapping (uint256 => PCKdatasets.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 => PCKdatasets.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 => PCKdatasets.TeamFee) public fees_; // (team => fees) fee distribution by team
mapping (uint256 => PCKdatasets.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
// (PCK, PCP) + (Pot , Referrals, Community)
// Referrals / Community rewards are mathematically designed to come from the winner's share of the pot.
fees_[0] = PCKdatasets.TeamFee(30,6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[1] = PCKdatasets.TeamFee(43,0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[2] = PCKdatasets.TeamFee(56,10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[3] = PCKdatasets.TeamFee(43,8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
// how to split up the final pot based on which team was picked
// (PCK, PCP)
potSplit_[0] = PCKdatasets.PotSplit(15,10); //48% to winner, 25% to next round, 2% to com
potSplit_[1] = PCKdatasets.PotSplit(25,0); //48% to winner, 25% to next round, 2% to com
potSplit_[2] = PCKdatasets.PotSplit(20,20); //48% to winner, 10% to next round, 2% to com
potSplit_[3] = PCKdatasets.PotSplit(30,10); //48% to winner, 10% to next round, 2% to com
}
//==============================================================================
// _ _ _ _|. |`. _ _ _ .
// | | |(_)(_||~|~|(/_| _\ . (these are safety checks)
//==============================================================================
/**
* @dev used to make sure no one can interact with contract until it has
* been activated.
*/
modifier isActivated() {
require(activated_ == true, "its not ready yet. check ?eta in discord");
_;
}
modifier isRoundActivated() {
require(round_[rID_].ended == false, "the round is finished");
_;
}
/**
* @dev prevents contracts from interacting with fomo3d
*/
modifier isHuman() {
address _addr = msg.sender;
uint256 _codeLength;
require(msg.sender == tx.origin, "sorry humans only");
_;
}
/**
* @dev sets boundaries for incoming tx
*/
modifier isWithinLimits(uint256 _eth) {
require(_eth >= 1000000000, "pocket lint: not a valid currency");
require(_eth <= 100000000000000000000000, "no vitalik, no");
_;
}
modifier onlyAdmins() {
require(msg.sender == admin, "onlyAdmins failed - msg.sender is not an admin");
_;
}
//==============================================================================
// _ |_ |. _ |` _ __|_. _ _ _ .
// |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract)
//====|=========================================================================
function kill () onlyAdmins() public {
require(round_[rID_].ended == true && closed_ == true, "the round is active or not close");
selfdestruct(admin);
}
function getRoundStatus() isActivated() public view returns(uint256, bool){
return (rID_, round_[rID_].ended);
}
function setThreshold(uint256 _threshold) onlyAdmins() public returns(uint256) {
rndReduceThreshold_ = _threshold;
return rndReduceThreshold_;
}
function setEnforce(bool _closed) onlyAdmins() public returns(bool) {
closed_ = _closed;
if( !closed_ && round_[rID_].ended == true && activated_ == true ){
nextRound();
}
return closed_;
}
/**
* @dev emergency buy uses last stored affiliate ID and team snek
*/
function()
isActivated()
isRoundActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
PCKdatasets.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()
isRoundActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
PCKdatasets.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()
isRoundActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
PCKdatasets.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()
isRoundActivated()
isHuman()
isWithinLimits(msg.value)
public
payable
{
// set up our tx event data and determine if player is new or not
PCKdatasets.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()
isRoundActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
PCKdatasets.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()
isRoundActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
PCKdatasets.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()
isRoundActivated()
isHuman()
isWithinLimits(_eth)
public
{
// set up our tx event data
PCKdatasets.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
PCKdatasets.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 PCKevents.onWithdrawAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eth,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PCPAmount,
_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 PCKevents.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 PCKevents.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 PCKevents.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 PCKevents.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, PCKdatasets.EventReturns memory _eventData_) private {
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (!closed_ && _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 ( (closed_ || _now > round_[_rID].end ) && round_[_rID].ended == false ) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
if( !closed_ ){
nextRound();
}
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit PCKevents.onBuyAndDistribute
(
msg.sender,
plyr_[_pID].name,
msg.value,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PCPAmount,
_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, PCKdatasets.EventReturns memory _eventData_) private {
// setup local rID
uint256 _rID = rID_;
// grab time
uint256 _now = now;
// if round is active
if (!closed_ && _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 ( ( closed_ || _now > round_[_rID].end ) && round_[_rID].ended == false ) {
// end the round (distributes pot) & start new round
round_[_rID].ended = true;
_eventData_ = endRound(_eventData_);
if( !closed_ ) {
nextRound();
}
// build event data
_eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID;
// fire buy and distribute event
emit PCKevents.onReLoadAndDistribute
(
msg.sender,
plyr_[_pID].name,
_eventData_.compressedData,
_eventData_.compressedIDs,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PCPAmount,
_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, PCKdatasets.EventReturns memory _eventData_)
private
{
// if player is new to round
if (plyrRnds_[_pID][_rID].keys == 0)
_eventData_ = managePlayer(_pID, _eventData_);
// early round eth limiter
if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000)
{
uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth);
uint256 _refund = _eth.sub(_availableLimit);
plyr_[_pID].gen = plyr_[_pID].gen.add(_refund);
_eth = _availableLimit;
}
// if eth left is greater than min eth allowed (sorry no pocket lint)
if (_eth > 1000000000)
{
// mint the new keys
uint256 _keys = (round_[_rID].eth).keysRec(_eth);
// if they bought at least 1 whole key
if (_keys >= 1000000000000000000)
{
updateTimer(_keys, _rID, _eth);
// 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(PCKdatasets.EventReturns memory _eventData_)
private
returns (PCKdatasets.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, PCKdatasets.EventReturns memory _eventData_)
private
returns (PCKdatasets.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_);
}
function nextRound() private {
rID_++;
round_[rID_].strt = now;
round_[rID_].end = now.add(rndInit_).add(rndGap_);
}
/**
* @dev ends the round. manages paying out winner/splitting up pot
*/
function endRound(PCKdatasets.EventReturns memory _eventData_)
private
returns (PCKdatasets.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 / 50);
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
if (!address(Pro_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _p3d.add(_com);
_com = 0;
}
// distribute gen portion to key holders
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// send share for p3d to PCGod
if (_p3d > 0)
PCGod.deposit.value(_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_.PCPAmount = _p3d;
_eventData_.newPot = _res;
// start next round
//rID_++;
_rID++;
round_[_rID].ended = false;
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, uint256 _eth)
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
uint256 _newEndTime;
if (_newTime < (rndMax_).add(_now))
_newEndTime = _newTime;
else
_newEndTime = rndMax_.add(_now);
// biger to threshold, reduce
if ( _eth >= rndReduceThreshold_ ) {
_newEndTime = (_newEndTime).sub( (((_keys) / (1000000000000000000))).mul(rndInc_).add( (((_keys) / (2000000000000000000) ).mul(rndInc_)) ) );
// last add 10 minutes
if( _newEndTime < _now + rndMin_ )
_newEndTime = _now + rndMin_ ;
}
round_[_rID].end = _newEndTime;
}
/**
* @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, PCKdatasets.EventReturns memory _eventData_)
private
returns(PCKdatasets.EventReturns)
{
// pay 2% out to community rewards
uint256 _com = _eth / 50;
uint256 _p3d;
if (!address(Pro_Inc).call.value(_com)(bytes4(keccak256("deposit()"))))
{
// This ensures Team Just cannot influence the outcome of FoMo3D with
// bank migrations by breaking outgoing transactions.
// Something we would never do. But that's not the point.
// We spent 2000$ in eth re-deploying just to patch this, we hold the
// highest belief that everything we create should be trustless.
// Team JUST, The name you shouldn't have to trust.
_p3d = _com;
_com = 0;
}
// pay 1% out to FoMo3D short
uint256 _long = _eth / 100;
otherPCK_.potSwap.value(_long)();
// 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 PCKevents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now);
} else {
_p3d = _aff;
}
// pay out p3d
_p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100));
if (_p3d > 0)
{
// deposit to PCGod contract
PCGod.deposit.value(_p3d)();
// set up event data
_eventData_.PCPAmount = _p3d.add(_eventData_.PCPAmount);
}
return(_eventData_);
}
function potSwap()
external
payable
{
// setup local rID
uint256 _rID = rID_ + 1;
round_[_rID].pot = round_[_rID].pot.add(msg.value);
emit PCKevents.onPotSwapDeposit(_rID, msg.value);
}
/**
* @dev distributes eth based on fees to gen and pot
*/
function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, PCKdatasets.EventReturns memory _eventData_)
private
returns(PCKdatasets.EventReturns)
{
// calculate gen share
uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100;
// toss 1% into airdrop pot
uint256 _air = (_eth / 100);
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(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100));
// calculate pot
uint256 _pot = _eth.sub(_gen);
// distribute gen share (thats what updateMasks() does) and adjust
// balances for dust.
uint256 _dust = updateMasks(_rID, _pID, _gen, _keys);
if (_dust > 0)
_gen = _gen.sub(_dust);
// add eth to pot
round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot);
// set up event data
_eventData_.genAmount = _gen.add(_eventData_.genAmount);
_eventData_.potAmount = _pot;
return(_eventData_);
}
/**
* @dev updates masks for round and player when keys are bought
* @return dust left over
*/
function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys)
private
returns(uint256)
{
/* MASKING NOTES
earnings masks are a tricky thing for people to wrap their minds around.
the basic thing to understand here. is were going to have a global
tracker based on profit per share for each round, that increases in
relevant proportion to the increase in share supply.
the player will have an additional mask that basically says "based
on the rounds mask, my shares, and how much i've already withdrawn,
how much is still owed to me?"
*/
// calc profit per key & round mask based on this buy: (dust goes to pot)
uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys);
round_[_rID].mask = _ppt.add(round_[_rID].mask);
// calculate player earning from their own buy (only based on the keys
// they just bought). & update player earnings mask
uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000);
plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask);
// calculate & return dust
return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000)));
}
/**
* @dev adds up unmasked earnings, & vault earnings, sets them all to 0
* @return earnings in wei format
*/
function withdrawEarnings(uint256 _pID)
private
returns(uint256)
{
// update gen vault
updateGenVault(_pID, plyr_[_pID].lrnd);
// from vaults
uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff);
if (_earnings > 0)
{
plyr_[_pID].win = 0;
plyr_[_pID].gen = 0;
plyr_[_pID].aff = 0;
}
return(_earnings);
}
/**
* @dev prepares compression data and fires event for buy or reload tx's
*/
function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, PCKdatasets.EventReturns memory _eventData_)
private
{
_eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000);
_eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000);
emit PCKevents.onEndTx
(
_eventData_.compressedData,
_eventData_.compressedIDs,
plyr_[_pID].name,
msg.sender,
_eth,
_keys,
_eventData_.winnerAddr,
_eventData_.winnerName,
_eventData_.amountWon,
_eventData_.newPot,
_eventData_.PCPAmount,
_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 == admin,
"only team just can activate"
);
// make sure that its been linked.
require(address(otherPCK_) != address(0), "must link to other PCK first");
// can only be ran once
require(activated_ == false, "PCK 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_;
}
function setOtherPCK(address _otherPCK) public {
// only team just can activate
require(
msg.sender == admin,
"only team just can activate"
);
// make sure that it HASNT yet been linked.
require(address(otherPCK_) == address(0), "silly dev, you already did that");
// set up other fomo3d (fast or long) for pot swap
otherPCK_ = otherPCK(_otherPCK);
}
}
//==============================================================================
// __|_ _ __|_ _ .
// _\ | | |_|(_ | _\ .
//==============================================================================
library PCKdatasets {
//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 PCPAmount; // 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 PCKKeysCalcLong {
using SafeMath for *;
/**
* @dev calculates number of keys received given X eth
* @param _curEth current amount of eth in contract
* @param _newEth eth being spent
* @return amount of ticket purchased
*/
function keysRec(uint256 _curEth, uint256 _newEth)
internal
pure
returns (uint256)
{
return(keys((_curEth).add(_newEth)).sub(keys(_curEth)));
}
/**
* @dev calculates amount of eth received if you sold X keys
* @param _curKeys current amount of keys that exist
* @param _sellKeys amount of keys you wish to sell
* @return amount of eth received
*/
function ethRec(uint256 _curKeys, uint256 _sellKeys)
internal
pure
returns (uint256)
{
return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys))));
}
/**
* @dev calculates how many keys would exist with given an amount of eth
* @param _eth eth "in contract"
* @return number of keys that would exist
*/
function keys(uint256 _eth)
internal
pure
returns(uint256)
{
return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000);
}
/**
* @dev calculates how much eth would be in contract given a number of keys
* @param _keys number of keys "in contract"
* @return eth that would exists
*/
function eth(uint256 _keys)
internal
pure
returns(uint256)
{
return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq());
}
}
//==============================================================================
// . _ _|_ _ _ |` _ _ _ _ .
// || | | (/_| ~|~(_|(_(/__\ .
//==============================================================================
interface otherPCK {
function potSwap() external payable;
}
interface PCKExtSettingInterface {
function getFastGap() external view returns(uint256);
function getLongGap() external view returns(uint256);
function getFastExtra() external view returns(uint256);
function getLongExtra() external view returns(uint256);
}
interface PlayCoinGodInterface {
function deposit() external payable;
}
interface ProForwarderInterface {
function deposit() external payable returns(bool);
function status() external view returns(address, address, bool);
function startMigration(address _newCorpBank) external returns(bool);
function cancelMigration() external returns(bool);
function finishMigration() external returns(bool);
function setup(address _firstCorpBank) external;
}
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);
}
}
}
|
decides if round end needs to be run & new round started. and if player unmasked earnings from previously played rounds need to be moved./ if player has played a previous round, move their unmasked earnings from that round to gen vault. update player's last round played set the joined round bool to true
|
function managePlayer(uint256 _pID, PCKdatasets.EventReturns memory _eventData_)
private
returns (PCKdatasets.EventReturns)
{
if (plyr_[_pID].lrnd != 0)
updateGenVault(_pID, plyr_[_pID].lrnd);
plyr_[_pID].lrnd = rID_;
_eventData_.compressedData = _eventData_.compressedData + 10;
return(_eventData_);
}
| 1,254,155 |
pragma solidity ^0.4.24;
import "./Table.sol";
contract hospital {
constructor() public {
// 构造函数中创建t_hospital表
// createTable();
TableFactory tf = TableFactory(0x1001);
// 核酸检测信息表, key : account, field : asset_value
// | 身份证号(主键) | 姓名 | 检测结果 | 检测时间 |
// |-------------------- |-------------------|------------------- |-------------------|
// | id | name | result | date |
// |---------------------|-------------------|------------------- |-------------------|
//
// 创建表
tf.createTable("t_hospital", "id", "name,result,date");
}
// function createTable() private {
// TableFactory tf = TableFactory(0x1001);
// // 核酸检测信息表, key : account, field : asset_value
// // | 身份证号(主键) | 姓名 | 检测结果 | 检测时间 |
// // |-------------------- |-------------------|------------------- |-------------------|
// // | id | name | result | date |
// // |---------------------|-------------------|------------------- |-------------------|
// //
// // 创建表
// tf.createTable("t_hospital", "id", "name,result,date");
// }
// function openTable(string table_name) private returns(Table) {
// TableFactory tf = TableFactory(0x1001);
// Table table = tf.openTable(table_name);
// return table;
// }
// /*
// 描述 : 根据身份证号查询检测结果
// 参数 :
// id : 身份证号
// 返回值:
// 参数一: 成功返回0, 身份证号不存在返回-1
// 参数二: 第一个参数为0时有效,检测结果
// */
// function select(string id) public constant returns(int, int) {
// // 打开表
// Table table = openTable();
// // 查询
// Entries entries = table.select(id, table.newCondition());
// int result = 0;
// if (0 == uint256(entries.size())) {
// return (-1, result);
// } else {
// Entry entry = entries.get(0);
// return (0, entry.getInt("result"));
// }
// }
/*
描述 : 上传检测结果
参数 :
id : 身份证号
name: 姓名
result: 检测结果
date: 检测时间,unix的绝对时间戳(自1970-01-01以来的秒数)
返回值:
1 成功,更新一条数据
0 成功,新插入一条数据
-1 失败,检测时间晚于当前时间或早于最近一次检测时间
-2 其他错误
*/
function upload(string id, string name, int result, uint date) public returns(int256) {
// int ret_code = 0;
string memory HUFFMAN = "Huffman";
if (result == 10086) {
return int256(now);
}
if (keccak256(bytes(id)) == keccak256(bytes(HUFFMAN))) {
return int256(now);
}
if (date > now) {
return -1;
}
// 查询被测id是否存在表中
TableFactory tf = TableFactory(0x1001);
Table t_hospital = tf.openTable("t_hospital");
Entry entry = t_hospital.newEntry();
Entries entries = t_hospital.select(id, t_hospital.newCondition());
if (0 == uint256(entries.size())) {
// 身份证号不存在,新建一条记录
entry.set("id", id);
entry.set("name", name);
entry.set("result", result);
entry.set("date", int(date));
// 插入
int count = t_hospital.insert(id, entry);
if (count == 1) {
// 成功
return 0;
} else {
// 失败? 无权限或者其他错误
return -2;
}
} else {
if (int(date) < entries.get(0).getInt("date")) {
return -1;
}
// 身份证号存在, 更新相关记录
entry.set("result", result);
entry.set("date", int(date));
Condition condition = t_hospital.newCondition();
condition.EQ("id", id);
condition.EQ("name", name);
// condition.LE("date", int(date));
count = t_hospital.update(id, entry, condition);
if (count == 1) {
// 成功
return 1;
} else {
// 失败? 无权限或者其他错误
return -2;
}
}
}
}
|
/ int ret_code = 0; 身份证号不存在,新建一条记录 插入 成功 失败? 无权限或者其他错误 成功 失败? 无权限或者其他错误
|
function upload(string id, string name, int result, uint date) public returns(int256) {
string memory HUFFMAN = "Huffman";
if (result == 10086) {
return int256(now);
}
if (keccak256(bytes(id)) == keccak256(bytes(HUFFMAN))) {
return int256(now);
}
if (date > now) {
return -1;
}
Table t_hospital = tf.openTable("t_hospital");
Entry entry = t_hospital.newEntry();
Entries entries = t_hospital.select(id, t_hospital.newCondition());
if (0 == uint256(entries.size())) {
entry.set("id", id);
entry.set("name", name);
entry.set("result", result);
entry.set("date", int(date));
int count = t_hospital.insert(id, entry);
if (count == 1) {
return 0;
return -2;
}
if (int(date) < entries.get(0).getInt("date")) {
return -1;
}
entry.set("date", int(date));
Condition condition = t_hospital.newCondition();
condition.EQ("id", id);
condition.EQ("name", name);
count = t_hospital.update(id, entry, condition);
if (count == 1) {
return 1;
return -2;
}
}
}
| 5,432,069 |
./full_match/1/0x677885afde857b70f40741ff8B60F9aFbA95Dd49/sources/contracts/pendle/contracts/core/StandardizedYield/implementations/BalancerStable/base/PendleAuraBalancerStableLPSYV2.sol
|
if there is no extra rewards, we can call getReward with the 2nd arg (_claimExtra) to be false which helps save even more gas
|
function _redeemExternalReward() internal virtual override {
uint256 extraRewardsLen = extraRewards.length;
if (extraRewardsLen == 0) IRewards(auraRewardManager).getReward(address(this), false);
else IRewards(auraRewardManager).getReward(address(this), true);
}
MISC FUNCTIONS FOR METADATA
| 3,214,113 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import { ServiceProvider } from "./ServiceProvider.sol";
import { CloneFactory } from "./CloneFactory.sol";
import { CudosAccessControls } from "../CudosAccessControls.sol";
import { StakingRewardsGuild } from "./StakingRewardsGuild.sol";
// based on MasterChef from sushi swap
contract StakingRewards is CloneFactory, ReentrancyGuard, Context {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user that is staked into a specific reward program i.e. 3 month, 6 month, 12 month
struct UserInfo {
uint256 amount; // How many cudos tokens the user has staked.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of cudos
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * rewardProgramme.accTokensPerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws LP tokens to a rewardProgramme. Here's what happens:
// 1. The rewardProgramme's `accTokensPerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
// Hence the rewardDebt is the total amount of rewards a service provider contract would have received
// if the state of the network were the same as now from the beginning.
}
// Info about a reward program where each differs in minimum required length of time for locking up CUDOs.
struct RewardProgramme {
uint256 minStakingLengthInBlocks; // once staked, amount of blocks the staker has to wait before being able to withdraw
uint256 allocPoint; // Percentage of total CUDOs rewards (across all programmes) that this programme will get
uint256 lastRewardBlock; // Last block number that CUDOs was claimed for reward programme users.
uint256 accTokensPerShare; // Accumulated tokens per share, times 1e18. See below.
// accTokensPerShare is the average reward amount a service provider contract would have received per each block so far
// if the state of the network were the same as now from the beginning.
uint256 totalStaked; // total staked in this reward programme
}
bool public userActionsPaused;
// staking and reward token - CUDOs
IERC20 public token;
CudosAccessControls public accessControls;
StakingRewardsGuild public rewardsGuildBank;
// tokens rewarded per block.
uint256 public tokenRewardPerBlock;
// Info of each reward programme.
RewardProgramme[] public rewardProgrammes;
/// @notice minStakingLengthInBlocks -> is active / valid reward programme
mapping(uint256 => bool) public isActiveRewardProgramme;
// Info of each user that has staked in each programme.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// total staked across all programmes
uint256 public totalCudosStaked;
// weighted total staked across all programmes
uint256 public weightedTotalCudosStaked;
// The block number when rewards start.
uint256 public startBlock;
// service provider -> proxy and reverse mapping
mapping(address => address) public serviceProviderToWhitelistedProxyContracts;
mapping(address => address) public serviceProviderContractToServiceProvider;
/// @notice Used as a base contract to clone for all new whitelisted service providers
address public cloneableServiceProviderContract;
/// @notice By default, 2M CUDO must be supplied to be a validator
uint256 public minRequiredStakingAmountForServiceProviders = 2_000_000 * 10 ** 18;
uint256 public maxStakingAmountForServiceProviders = 1_000_000_000 * 10 ** 18;
/// @notice Allows the rewards fee to be specified to 2 DP
uint256 public constant PERCENTAGE_MODULO = 100_00;
uint256 public minServiceProviderFee = 2_00; // initially 2%
uint256 public constant numOfBlocksInADay = 6500;
uint256 public unbondingPeriod = numOfBlocksInADay.mul(21); // Equivalent to solidity 21 days
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event MinRequiredStakingAmountForServiceProvidersUpdated(uint256 oldValue, uint256 newValue);
event MaxStakingAmountForServiceProvidersUpdated(uint256 oldValue, uint256 newValue);
event MinServiceProviderFeeUpdated(uint256 oldValue, uint256 newValue);
event ServiceProviderWhitelisted(address indexed serviceProvider, address indexed serviceProviderContract);
event RewardPerBlockUpdated(uint256 oldValue, uint256 newValue);
event RewardProgrammeAdded(uint256 allocPoint, uint256 minStakingLengthInBlocks);
event RewardProgrammeAllocPointUpdated(uint256 oldValue, uint256 newValue);
event UserActionsPausedToggled(bool isPaused);
// paused
modifier paused() {
require(userActionsPaused == false, "PSD");
_;
}
// Amount cannot be 0
modifier notZero(uint256 _amount) {
require(_amount > 0, "SPC6");
_;
}
// Unknown service provider
modifier unkSP() {
require(serviceProviderContractToServiceProvider[_msgSender()] != address(0), "SPU1");
_;
}
// Only whitelisted
modifier whitelisted() {
require(accessControls.hasWhitelistRole(_msgSender()), "OWL");
_;
}
constructor(
IERC20 _token,
CudosAccessControls _accessControls,
StakingRewardsGuild _rewardsGuildBank,
uint256 _tokenRewardPerBlock,
uint256 _startBlock,
address _cloneableServiceProviderContract
) {
require(address(_accessControls) != address(0), "StakingRewards.constructor: Invalid access controls");
require(address(_token) != address(0), "StakingRewards.constructor: Invalid token address");
require(_cloneableServiceProviderContract != address(0), "StakingRewards.constructor: Invalid cloneable service provider");
token = _token;
accessControls = _accessControls;
rewardsGuildBank = _rewardsGuildBank;
tokenRewardPerBlock = _tokenRewardPerBlock;
startBlock = _startBlock;
cloneableServiceProviderContract = _cloneableServiceProviderContract;
}
// Update reward variables of the given programme to be up-to-date.
function updateRewardProgramme(uint256 _programmeId) public {
RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId];
if (_getBlock() <= rewardProgramme.lastRewardBlock) {
return;
}
uint256 totalStaked = rewardProgramme.totalStaked;
if (totalStaked == 0) {
rewardProgramme.lastRewardBlock = _getBlock();
return;
}
uint256 blocksSinceLastReward = _getBlock().sub(rewardProgramme.lastRewardBlock);
// we want to divide proportionally by all the tokens staked in the RPs, not to distribute first to RP
// so what we want here is rewardProgramme.allocPoint.mul(rewardProgramme.totalStaked).div(the sum of the products of allocPoint times totalStake for each RP)
uint256 rewardPerShare = blocksSinceLastReward.mul(tokenRewardPerBlock).mul(rewardProgramme.allocPoint).mul(1e18).div(weightedTotalCudosStaked);
rewardProgramme.accTokensPerShare = rewardProgramme.accTokensPerShare.add(rewardPerShare);
rewardProgramme.lastRewardBlock = _getBlock();
}
function getReward(uint256 _programmeId) external nonReentrant {
updateRewardProgramme(_programmeId);
_getReward(_programmeId);
}
function massUpdateRewardProgrammes() public {
uint256 programmeLength = rewardProgrammes.length;
for(uint256 i = 0; i < programmeLength; i++) {
updateRewardProgramme(i);
}
}
function getRewardWithMassUpdate(uint256 _programmeId) external nonReentrant {
massUpdateRewardProgrammes();
_getReward(_programmeId);
}
// stake CUDO in a specific reward programme that dictates a minimum lockup period
function stake(uint256 _programmeId, address _from, uint256 _amount) external nonReentrant paused notZero(_amount) unkSP {
RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId];
UserInfo storage user = userInfo[_programmeId][_msgSender()];
user.amount = user.amount.add(_amount);
rewardProgramme.totalStaked = rewardProgramme.totalStaked.add(_amount);
totalCudosStaked = totalCudosStaked.add(_amount);
// weigted sum gets updated when new tokens are staked
weightedTotalCudosStaked = weightedTotalCudosStaked.add(_amount.mul(rewardProgramme.allocPoint));
user.rewardDebt = user.amount.mul(rewardProgramme.accTokensPerShare).div(1e18);
token.safeTransferFrom(address(_from), address(rewardsGuildBank), _amount);
emit Deposit(_from, _programmeId, _amount);
}
// Withdraw stake and rewards
function withdraw(uint256 _programmeId, address _to, uint256 _amount) public nonReentrant paused notZero(_amount) unkSP {
RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId];
UserInfo storage user = userInfo[_programmeId][_msgSender()];
// StakingRewards.withdraw: Amount exceeds balance
require(user.amount >= _amount, "SRW1");
user.amount = user.amount.sub(_amount);
rewardProgramme.totalStaked = rewardProgramme.totalStaked.sub(_amount);
totalCudosStaked = totalCudosStaked.sub(_amount);
// weigted sum gets updated when new tokens are withdrawn
weightedTotalCudosStaked = weightedTotalCudosStaked.sub(_amount.mul(rewardProgramme.allocPoint));
user.rewardDebt = user.amount.mul(rewardProgramme.accTokensPerShare).div(1e18);
rewardsGuildBank.withdrawTo(_to, _amount);
emit Withdraw(_msgSender(), _programmeId, _amount);
}
function exit(uint256 _programmeId) external unkSP {
withdraw(_programmeId, _msgSender(), userInfo[_programmeId][_msgSender()].amount);
}
// *****
// View
// *****
function numberOfRewardProgrammes() external view returns (uint256) {
return rewardProgrammes.length;
}
function getRewardProgrammeInfo(uint256 _programmeId) external view returns (
uint256 minStakingLengthInBlocks,
uint256 allocPoint,
uint256 lastRewardBlock,
uint256 accTokensPerShare,
uint256 totalStaked
) {
RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId];
return (
rewardProgramme.minStakingLengthInBlocks,
rewardProgramme.allocPoint,
rewardProgramme.lastRewardBlock,
rewardProgramme.accTokensPerShare,
rewardProgramme.totalStaked
);
}
function amountStakedByUserInRewardProgramme(uint256 _programmeId, address _user) external view returns (uint256) {
return userInfo[_programmeId][_user].amount;
}
function totalStakedInRewardProgramme(uint256 _programmeId) external view returns (uint256) {
return rewardProgrammes[_programmeId].totalStaked;
}
function totalStakedAcrossAllRewardProgrammes() external view returns (uint256) {
return totalCudosStaked;
}
// View function to see pending CUDOs on frontend.
function pendingCudoRewards(uint256 _programmeId, address _user) external view returns (uint256) {
RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId];
UserInfo storage user = userInfo[_programmeId][_user];
uint256 accTokensPerShare = rewardProgramme.accTokensPerShare;
uint256 totalStaked = rewardProgramme.totalStaked;
if (_getBlock() > rewardProgramme.lastRewardBlock && totalStaked != 0) {
uint256 blocksSinceLastReward = _getBlock().sub(rewardProgramme.lastRewardBlock);
// reward distribution is changed in line with the change within the updateRewardProgramme function
uint256 rewardPerShare = blocksSinceLastReward.mul(tokenRewardPerBlock).mul(rewardProgramme.allocPoint).mul(1e18).div(weightedTotalCudosStaked);
accTokensPerShare = accTokensPerShare.add(rewardPerShare);
}
return user.amount.mul(accTokensPerShare).div(1e18).sub(user.rewardDebt);
}
// proxy for service provider
function hasAdminRole(address _caller) external view returns (bool) {
return accessControls.hasAdminRole(_caller);
}
// *********
// Whitelist
// *********
// methods that check for whitelist role in access controls are for any param changes that could be done via governance
function updateMinRequiredStakingAmountForServiceProviders(uint256 _newValue) external whitelisted {
require(_newValue < maxStakingAmountForServiceProviders, "StakingRewards.updateMinRequiredStakingAmountForServiceProviders: Min staking must be less than max staking amount");
emit MinRequiredStakingAmountForServiceProvidersUpdated(minRequiredStakingAmountForServiceProviders, _newValue);
minRequiredStakingAmountForServiceProviders = _newValue;
}
function updateMaxStakingAmountForServiceProviders(uint256 _newValue) external whitelisted {
//require(accessControls.hasWhitelistRole(_msgSender()), "StakingRewards.updateMaxStakingAmountForServiceProviders: Only whitelisted");
require(_newValue > minRequiredStakingAmountForServiceProviders, "StakingRewards.updateMaxStakingAmountForServiceProviders: Max staking must be greater than min staking amount");
emit MaxStakingAmountForServiceProvidersUpdated(maxStakingAmountForServiceProviders, _newValue);
maxStakingAmountForServiceProviders = _newValue;
}
function updateMinServiceProviderFee(uint256 _newValue) external whitelisted {
//require(accessControls.hasWhitelistRole(_msgSender()), "StakingRewards.updateMinServiceProviderFee: Only whitelisted");
require(_newValue > 0 && _newValue < PERCENTAGE_MODULO, "StakingRewards.updateMinServiceProviderFee: Fee percentage must be between zero and one");
emit MinServiceProviderFeeUpdated(minServiceProviderFee, _newValue);
minServiceProviderFee = _newValue;
}
// *****
// Admin
// *****
function recoverERC20(address _erc20, address _recipient, uint256 _amount) external {
// StakingRewards.recoverERC20: Only admin
require(accessControls.hasAdminRole(_msgSender()), "OA");
IERC20(_erc20).safeTransfer(_recipient, _amount);
}
function whitelistServiceProvider(address _serviceProvider) external {
// StakingRewards.whitelistServiceProvider: Only admin
require(accessControls.hasAdminRole(_msgSender()), "OA");
require(serviceProviderToWhitelistedProxyContracts[_serviceProvider] == address(0), "StakingRewards.whitelistServiceProvider: Already whitelisted service provider");
address serviceProviderContract = createClone(cloneableServiceProviderContract);
serviceProviderToWhitelistedProxyContracts[_serviceProvider] = serviceProviderContract;
serviceProviderContractToServiceProvider[serviceProviderContract] = _serviceProvider;
ServiceProvider(serviceProviderContract).init(_serviceProvider, token);
emit ServiceProviderWhitelisted(_serviceProvider, serviceProviderContract);
}
function updateTokenRewardPerBlock(uint256 _tokenRewardPerBlock) external {
require(
accessControls.hasAdminRole(_msgSender()),
"StakingRewards.updateTokenRewardPerBlock: Only admin"
);
// If this is not done, any pending rewards could be potentially lost
massUpdateRewardProgrammes();
// Log old and new value
emit RewardPerBlockUpdated(tokenRewardPerBlock, _tokenRewardPerBlock);
// this is safe to be set to zero - it would effectively turn off all staking rewards
tokenRewardPerBlock = _tokenRewardPerBlock;
}
// Admin - Add a rewards programme
function addRewardsProgramme(uint256 _allocPoint, uint256 _minStakingLengthInBlocks, bool _withUpdate) external {
require(
accessControls.hasAdminRole(_msgSender()),
// StakingRewards.addRewardsProgramme: Only admin
"OA"
);
require(
isActiveRewardProgramme[_minStakingLengthInBlocks] == false,
// StakingRewards.addRewardsProgramme: Programme is already active
"PAA"
);
// StakingRewards.addRewardsProgramme: Invalid alloc point
require(_allocPoint > 0, "IAP");
if (_withUpdate) {
massUpdateRewardProgrammes();
}
uint256 lastRewardBlock = _getBlock() > startBlock ? _getBlock() : startBlock;
rewardProgrammes.push(
RewardProgramme({
minStakingLengthInBlocks: _minStakingLengthInBlocks,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accTokensPerShare: 0,
totalStaked: 0
})
);
isActiveRewardProgramme[_minStakingLengthInBlocks] = true;
emit RewardProgrammeAdded(_allocPoint, _minStakingLengthInBlocks);
}
// Update the given reward programme's CUDO allocation point. Can only be called by admin.
function updateAllocPointForRewardProgramme(uint256 _programmeId, uint256 _allocPoint, bool _withUpdate) external {
require(
accessControls.hasAdminRole(_msgSender()),
// StakingRewards.updateAllocPointForRewardProgramme: Only admin
"OA"
);
if (_withUpdate) {
massUpdateRewardProgrammes();
}
weightedTotalCudosStaked = weightedTotalCudosStaked.sub(rewardProgrammes[_programmeId].totalStaked.mul(rewardProgrammes[_programmeId].allocPoint));
emit RewardProgrammeAllocPointUpdated(rewardProgrammes[_programmeId].allocPoint, _allocPoint);
rewardProgrammes[_programmeId].allocPoint = _allocPoint;
weightedTotalCudosStaked = weightedTotalCudosStaked.add(rewardProgrammes[_programmeId].totalStaked.mul(rewardProgrammes[_programmeId].allocPoint));
}
function updateUserActionsPaused(bool _isPaused) external {
require(
accessControls.hasAdminRole(_msgSender()),
// StakingRewards.updateAllocPointForRewardProgramme: Only admin
"OA"
);
userActionsPaused = _isPaused;
emit UserActionsPausedToggled(_isPaused);
}
// ********
// Internal
// ********
function _getReward(uint256 _programmeId) internal {
RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId];
UserInfo storage user = userInfo[_programmeId][_msgSender()];
if (user.amount > 0) {
uint256 pending = user.amount.mul(rewardProgramme.accTokensPerShare).div(1e18).sub(user.rewardDebt);
if (pending > 0) {
user.rewardDebt = user.amount.mul(rewardProgramme.accTokensPerShare).div(1e18);
rewardsGuildBank.withdrawTo(_msgSender(), pending);
}
}
}
function _getBlock() public virtual view returns (uint256) {
return block.number;
}
function _findMinStakingLength(uint256 _programmeId) external view returns (uint256) {
RewardProgramme storage rewardProgramme = rewardProgrammes[_programmeId];
uint256 minStakingLength = rewardProgramme.minStakingLengthInBlocks;
return minStakingLength;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/utils/Context.sol";
import {StakingRewards} from "./StakingRewards.sol";
contract ServiceProvider is ReentrancyGuard, Context {
using SafeMath for uint256;
using SafeERC20 for IERC20;
struct WithdrawalRequest {
uint256 withdrawalPermittedFrom;
uint256 amount;
uint256 lastStakedBlock;
}
mapping(address => WithdrawalRequest) public withdrawalRequest;
address public controller; // StakingRewards
address public serviceProvider;
address public serviceProviderManager;
IERC20 public cudosToken;
/// @notice Allows the rewards fee to be specified to 2 DP
uint256 public constant PERCENTAGE_MODULO = 100_00;
/// @notice True when contract is initialised and the service provider has staked the required bond
bool public isServiceProviderFullySetup;
bool public exited;
/// @notice Defined by the service provider when depositing their bond
uint256 public rewardsFeePercentage;
event StakedServiceProviderBond(address indexed serviceProvider, address indexed serviceProviderManager, uint256 indexed pid, uint256 rewardsFeePercentage);
event IncreasedServiceProviderBond(address indexed serviceProvider, uint256 indexed pid, uint256 amount, uint256 totalAmount);
event DecreasedServiceProviderBond(address indexed serviceProvider, uint256 indexed pid, uint256 amount, uint256 totalAmount);
event ExitedServiceProviderBond(address indexed serviceProvider, uint256 indexed pid);
event WithdrewServiceProviderStake(address indexed serviceProvider, uint256 amount, uint256 totalAmount);
event AddDelegatedStake(address indexed user, uint256 amount, uint256 totalAmount);
event WithdrawDelegatedStakeRequested(address indexed user, uint256 amount, uint256 totalAmount);
event WithdrewDelegatedStake(address indexed user, uint256 amount, uint256 totalAmount);
event ExitDelegatedStake(address indexed user, uint256 amount);
event CalibratedServiceProviderFee(address indexed user, uint256 newFee);
mapping(address => uint256) public delegatedStake;
mapping(address => uint256) public rewardDebt;
// rewardDebt is the total amount of rewards a user would have received if the state of the network were the same as now from the beginning.
uint256 public totalDelegatedStake;
uint256 public rewardsProgrammeId;
uint256 public minStakingLength;
uint256 public accTokensPerShare; // Accumulated reward tokens per share, times 1e18. See below.
// accTokensPerShare is the average reward amount a user would have received per each block so far
// if the state of the network were the same as now from the beginning.
// Service provider not setup
modifier notSetupSP() {
require(isServiceProviderFullySetup, "SPC2");
_;
}
// Only Service Provider
modifier onlySP() {
require(_msgSender() == serviceProvider, "SPC1");
_;
}
// Only Service Provider Manager
modifier onlySPM() {
require(_msgSender() == serviceProviderManager, "SPC3");
_;
}
// Not a service provider method
modifier allowedSP() {
require(_msgSender() != serviceProviderManager && _msgSender() != serviceProvider, "SPC4");
_;
}
// Service provider has left
modifier isExitedSP() {
require(!exited, "SPHL");
_;
}
// _amount cannot be 0
modifier notZero(uint256 _amount) {
require(_amount > 0, "SPC6");
_;
}
// this is called by StakingRewards to whitelist a service provider and is equivalent of the constructor
function init(address _serviceProvider, IERC20 _cudosToken) external {
// ServiceProvider.init: Fn can only be called once
require(serviceProvider == address(0), "SPI1");
// ServiceProvider.init: Service provider cannot be zero address
require(_serviceProvider != address(0), "SPI2");
// ServiceProvider.init: Cudos token cannot be zero address
require(address(_cudosToken) != address(0), "SPI3");
serviceProvider = _serviceProvider;
cudosToken = _cudosToken;
controller = _msgSender();
// StakingRewards contract currently
}
// Called by the Service Provider to stake initial minimum cudo required to become a validator
function stakeServiceProviderBond(uint256 _rewardsProgrammeId, uint256 _rewardsFeePercentage) nonReentrant external onlySP {
serviceProviderManager = serviceProvider;
_stakeServiceProviderBond(_rewardsProgrammeId, _rewardsFeePercentage);
}
function adminStakeServiceProviderBond(uint256 _rewardsProgrammeId, uint256 _rewardsFeePercentage) nonReentrant external {
require(
StakingRewards(controller).hasAdminRole(_msgSender()),
// ServiceProvider.adminStakeServiceProviderBond: Only admin
"OA"
);
serviceProviderManager = _msgSender();
_stakeServiceProviderBond(_rewardsProgrammeId, _rewardsFeePercentage);
}
function increaseServiceProviderStake(uint256 _amount) nonReentrant external notSetupSP onlySPM notZero(_amount) {
StakingRewards rewards = StakingRewards(controller);
uint256 maxStakingAmountForServiceProviders = rewards.maxStakingAmountForServiceProviders();
uint256 amountStakedSoFar = rewards.amountStakedByUserInRewardProgramme(rewardsProgrammeId, address(this));
// ServiceProvider.increaseServiceProviderStake: Exceeds max staking
require(amountStakedSoFar.add(_amount) <= maxStakingAmountForServiceProviders, "SPS1");
// Get and distribute any pending rewards
_getAndDistributeRewardsWithMassUpdate();
// increase the service provider stake
StakingRewards(controller).stake(rewardsProgrammeId, serviceProviderManager, _amount);
// Update delegated stake
delegatedStake[serviceProvider] = delegatedStake[serviceProvider].add(_amount);
totalDelegatedStake = totalDelegatedStake.add(_amount);
// Store date for lock-up calculation
WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()];
withdrawalReq.lastStakedBlock = rewards._getBlock();
emit IncreasedServiceProviderBond(serviceProvider, rewardsProgrammeId, _amount, delegatedStake[serviceProvider]);
}
function requestExcessServiceProviderStakeWithdrawal(uint256 _amount) nonReentrant external notSetupSP onlySPM notZero(_amount) {
StakingRewards rewards = StakingRewards(controller);
WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()];
// Check if lockup has passed
uint256 stakeStart = withdrawalReq.lastStakedBlock;
// StakingRewards.withdraw: Min staking period has not yet passed
require(rewards._getBlock() >= stakeStart.add(minStakingLength), "SPW5");
uint256 amountLeftAfterWithdrawal = delegatedStake[serviceProvider].sub(_amount);
require(
amountLeftAfterWithdrawal >= rewards.minRequiredStakingAmountForServiceProviders(),
// ServiceProvider.requestExcessServiceProviderStakeWithdrawal: Remaining stake for a service provider cannot fall below minimum
"SPW7"
);
// Get and distribute any pending rewards
_getAndDistributeRewardsWithMassUpdate();
// Apply the unbonding period
uint256 unbondingPeriod = rewards.unbondingPeriod();
withdrawalReq.withdrawalPermittedFrom = rewards._getBlock().add(unbondingPeriod);
withdrawalReq.amount = withdrawalReq.amount.add(_amount);
delegatedStake[serviceProvider] = amountLeftAfterWithdrawal;
totalDelegatedStake = totalDelegatedStake.sub(_amount);
rewards.withdraw(rewardsProgrammeId, address(this), _amount);
emit DecreasedServiceProviderBond(serviceProvider, rewardsProgrammeId, _amount, delegatedStake[serviceProvider]);
}
// only called by service provider
// all CUDOs staked by service provider and any delegated stake plus rewards will be returned to this contract
// delegators will have to call their own exit methods to get their original stake and rewards
function exitAsServiceProvider() nonReentrant external onlySPM {
StakingRewards rewards = StakingRewards(controller);
WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()];
// Check if lockup has passed
uint256 stakeStart = withdrawalReq.lastStakedBlock;
// StakingRewards.withdraw: Min staking period has not yet passed
require(rewards._getBlock() >= stakeStart.add(minStakingLength), "SPW5");
// Distribute rewards to the service provider and update delegator reward entitlement
_getAndDistributeRewardsWithMassUpdate();
// Assign the unbonding period
uint256 unbondingPeriod = rewards.unbondingPeriod();
withdrawalReq.withdrawalPermittedFrom = rewards._getBlock().add(unbondingPeriod);
withdrawalReq.amount = withdrawalReq.amount.add(delegatedStake[serviceProvider]);
// Exit the rewards program bringing in all staked CUDO and earned rewards
StakingRewards(controller).exit(rewardsProgrammeId);
// Update service provider state
uint256 serviceProviderDelegatedStake = delegatedStake[serviceProvider];
delegatedStake[serviceProvider] = 0;
totalDelegatedStake = totalDelegatedStake.sub(serviceProviderDelegatedStake);
// this will mean a service provider could start the program again with stakeServiceProviderBond()
isServiceProviderFullySetup = false;
// prevents a SP from re-entering and causing loads of problems!!!
exited = true;
// Don't transfer tokens at this point. The service provider needs to wait for the unbonding period first, then needs to call withdrawServiceProviderStake()
emit ExitedServiceProviderBond(serviceProvider, rewardsProgrammeId);
}
// To be called only by a service provider
function withdrawServiceProviderStake() nonReentrant external onlySPM {
WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()];
// ServiceProvider.withdrawServiceProviderStake: no withdrawal request in flight
require(withdrawalReq.amount > 0, "SPW5");
require(
StakingRewards(controller)._getBlock() >= withdrawalReq.withdrawalPermittedFrom,
// ServiceProvider.withdrawServiceProviderStake: Not passed unbonding period
"SPW3"
);
uint256 withdrawalRequestAmount = withdrawalReq.amount;
withdrawalReq.amount = 0;
cudosToken.transfer(_msgSender(), withdrawalRequestAmount);
emit WithdrewServiceProviderStake(_msgSender(), withdrawalRequestAmount, delegatedStake[serviceProvider]);
}
// Called by a CUDO holder that wants to delegate their stake to a service provider
function delegateStake(uint256 _amount) nonReentrant external notSetupSP allowedSP notZero(_amount) {
// get and distribute any pending rewards
_getAndDistributeRewardsWithMassUpdate();
// now stake - no rewards will be sent back
StakingRewards(controller).stake(rewardsProgrammeId, _msgSender(), _amount);
// Update user and total delegated stake after _distributeRewards so that calc issues don't arise in _distributeRewards
uint256 previousDelegatedStake = delegatedStake[_msgSender()];
delegatedStake[_msgSender()] = previousDelegatedStake.add(_amount);
totalDelegatedStake = totalDelegatedStake.add(_amount);
// we need to update the reward debt so that the user doesn't suddenly have rewards due
rewardDebt[_msgSender()] = delegatedStake[_msgSender()].mul(accTokensPerShare).div(1e18);
// Store date for lock-up calculation
WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()];
withdrawalReq.lastStakedBlock = StakingRewards(controller)._getBlock();
emit AddDelegatedStake(_msgSender(), _amount, delegatedStake[_msgSender()]);
}
// Called by a CUDO holder that has previously delegated stake to the service provider
function requestDelegatedStakeWithdrawal(uint256 _amount) nonReentrant external isExitedSP notSetupSP notZero(_amount) allowedSP {
// ServiceProvider.requestDelegatedStakeWithdrawal: Amount exceeds delegated stake
require(delegatedStake[_msgSender()] >= _amount, "SPW4");
StakingRewards rewards = StakingRewards(controller);
WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()];
// Check if lockup has passed
uint256 stakeStart = withdrawalReq.lastStakedBlock;
// StakingRewards.withdraw: Min staking period has not yet passed
require(rewards._getBlock() >= stakeStart.add(minStakingLength), "SPW5");
_getAndDistributeRewardsWithMassUpdate();
uint256 unbondingPeriod = rewards.unbondingPeriod();
withdrawalReq.withdrawalPermittedFrom = rewards._getBlock().add(unbondingPeriod);
withdrawalReq.amount = withdrawalReq.amount.add(_amount);
delegatedStake[_msgSender()] = delegatedStake[_msgSender()].sub(_amount);
totalDelegatedStake = totalDelegatedStake.sub(_amount);
rewards.withdraw(rewardsProgrammeId, address(this), _amount);
// we need to update the reward debt so that the reward debt is not too high due to the decrease in staked amount
rewardDebt[_msgSender()] = delegatedStake[_msgSender()].mul(accTokensPerShare).div(1e18);
emit WithdrawDelegatedStakeRequested(_msgSender(), _amount, delegatedStake[_msgSender()]);
}
function withdrawDelegatedStake() nonReentrant external isExitedSP notSetupSP allowedSP {
WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()];
// ServiceProvider.withdrawDelegatedStake: no withdrawal request in flight
require(withdrawalReq.amount > 0, "SPW2");
require(
StakingRewards(controller)._getBlock() >= withdrawalReq.withdrawalPermittedFrom,
// ServiceProvider.withdrawDelegatedStake: Not passed unbonding period
"SPW3"
);
uint256 withdrawalRequestAmount = withdrawalReq.amount;
withdrawalReq.amount = 0;
cudosToken.transfer(_msgSender(), withdrawalRequestAmount);
emit WithdrewDelegatedStake(_msgSender(), withdrawalRequestAmount, delegatedStake[_msgSender()]);
}
// Can be called by a delegator when a service provider exits
// Service provider must have exited when the delegator calls this method. Otherwise, they call withdrawDelegatedStake
function exitAsDelegator() nonReentrant external {
// ServiceProvider.exitAsDelegator: Service provider has not exited
require(exited, "SPE1");
WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()];
uint256 withdrawalRequestAmount = withdrawalReq.amount;
uint256 userDelegatedStake = delegatedStake[_msgSender()];
uint256 totalPendingWithdrawal = withdrawalRequestAmount.add(userDelegatedStake);
// ServiceProvider.exitAsDelegator: No pending withdrawal
require(totalPendingWithdrawal > 0, "SPW1");
if (userDelegatedStake > 0) {
// accTokensPerShare would have already been updated when the service provider exited
_sendDelegatorAnyPendingRewards();
}
withdrawalReq.amount = 0;
delegatedStake[_msgSender()] = 0;
totalDelegatedStake = totalDelegatedStake.sub(userDelegatedStake);
// Send them back their stake
cudosToken.transfer(_msgSender(), totalPendingWithdrawal);
// update rewardDebt to avoid errors in the pendingRewards function
rewardDebt[_msgSender()] = 0;
emit ExitDelegatedStake(_msgSender(), totalPendingWithdrawal);
}
// Should be possible for anyone to call this to get the reward from the StakingRewards contract
// The total rewards due to all delegators will have the rewardsFeePercentage deducted and sent to the Service Provider
function getReward() external isExitedSP notSetupSP {
_getAndDistributeRewards();
}
function callibrateServiceProviderFee() external {
StakingRewards rewards = StakingRewards(controller);
uint256 minServiceProviderFee = rewards.minServiceProviderFee();
// current fee is too low - increase to minServiceProviderFee
if (rewardsFeePercentage < minServiceProviderFee) {
rewardsFeePercentage = minServiceProviderFee;
emit CalibratedServiceProviderFee(_msgSender(), rewardsFeePercentage);
}
}
/////////////////
// View methods
/////////////////
function pendingRewards(address _user) public view returns (uint256) {
uint256 pendingRewardsServiceProviderAndDelegators = StakingRewards(controller).pendingCudoRewards(
rewardsProgrammeId,
address(this)
);
(
uint256 stakeDelegatedToServiceProvider,
uint256 rewardsFee,
uint256 baseRewardsDueToServiceProvider,
uint256 netRewardsDueToDelegators
) = _workOutHowMuchDueToServiceProviderAndDelegators(pendingRewardsServiceProviderAndDelegators);
if (_user == serviceProvider && _user == serviceProviderManager) {
return baseRewardsDueToServiceProvider.add(rewardsFee);
} else if (_user == serviceProvider){
return rewardsFee;
} else if (_user == serviceProviderManager){
return baseRewardsDueToServiceProvider;
}
uint256 _accTokensPerShare = accTokensPerShare;
if (stakeDelegatedToServiceProvider > 0) {
// Update accTokensPerShare which governs rewards token due to each delegator
_accTokensPerShare = _accTokensPerShare.add(
netRewardsDueToDelegators.mul(1e18).div(stakeDelegatedToServiceProvider)
);
}
return delegatedStake[_user].mul(_accTokensPerShare).div(1e18).sub(rewardDebt[_user]);
}
///////////////////
// Private methods
///////////////////
function _getAndDistributeRewards() private {
uint256 cudosBalanceBeforeGetReward = cudosToken.balanceOf(address(this));
StakingRewards(controller).getReward(rewardsProgrammeId);
uint256 cudosBalanceAfterGetReward = cudosToken.balanceOf(address(this));
// This is the amount of CUDO that we received from the the above getReward() call
uint256 rewardDelta = cudosBalanceAfterGetReward.sub(cudosBalanceBeforeGetReward);
// If this service provider contract has earned additional rewards since the last time, they must be distributed first
if (rewardDelta > 0) {
_distributeRewards(rewardDelta);
}
// Service provider(s) always receive their rewards first.
// If sender is not serviceProvider or serviceProviderManager, we send them their share here.
if (_msgSender() != serviceProviderManager && _msgSender() != serviceProvider) {
// check sender has a delegatedStake
if (delegatedStake[_msgSender()] > 0) {
_sendDelegatorAnyPendingRewards();
}
}
}
function _getAndDistributeRewardsWithMassUpdate() private {
uint256 cudosBalanceBeforeGetReward = cudosToken.balanceOf(address(this));
StakingRewards(controller).getRewardWithMassUpdate(rewardsProgrammeId);
uint256 cudosBalanceAfterGetReward = cudosToken.balanceOf(address(this));
// This is the amount of CUDO that we received from the the above getReward() call
uint256 rewardDelta = cudosBalanceAfterGetReward.sub(cudosBalanceBeforeGetReward);
// If this service provider contract has earned additional rewards since the last time, they must be distributed first
if (rewardDelta > 0) {
_distributeRewards(rewardDelta);
}
// Service provider(s) always receive their rewards first.
// If sender is not serviceProvider or serviceProviderManager, we send them their share here.
if (_msgSender() != serviceProviderManager && _msgSender() != serviceProvider) {
// check sender has a delegatedStake
if (delegatedStake[_msgSender()] > 0) {
_sendDelegatorAnyPendingRewards();
}
}
}
// Called when this service provider contract has earned additional rewards.
// Increases delagators' pending rewards, and sends sevice provider(s) their share.
function _distributeRewards(uint256 _amount) private {
(
uint256 stakeDelegatedToServiceProvider,
uint256 rewardsFee,
uint256 baseRewardsDueToServiceProvider,
uint256 netRewardsDueToDelegators
) = _workOutHowMuchDueToServiceProviderAndDelegators(_amount);
// Delegators' pending rewards are updated
if (stakeDelegatedToServiceProvider > 0) {
// Update accTokensPerShare which governs rewards token due to each delegator
accTokensPerShare = accTokensPerShare.add(
netRewardsDueToDelegators.mul(1e18).div(stakeDelegatedToServiceProvider)
);
}
// Service provider(s) receive their share(s)
if (serviceProvider == serviceProviderManager){
cudosToken.transfer(serviceProvider, baseRewardsDueToServiceProvider.add(rewardsFee));
} else {
cudosToken.transfer(serviceProviderManager, baseRewardsDueToServiceProvider);
cudosToken.transfer(serviceProvider, rewardsFee);
}
}
function _workOutHowMuchDueToServiceProviderAndDelegators(uint256 _amount) private view returns (uint256, uint256, uint256, uint256) {
// In case everyone (validator and delegators) has exited, we still want the pendingRewards function to return a number, which is zero in this case,
// rather than some kind of a message. So we first treat this edge case separately.
if (totalDelegatedStake == 0) {
return (0, 0, 0, 0);
}
// With this edge case out of the way, first work out the total stake of the delegators
uint256 stakeDelegatedToServiceProvider = totalDelegatedStake.sub(delegatedStake[serviceProvider]);
uint256 percentageOfStakeThatIsDelegatedToServiceProvider = stakeDelegatedToServiceProvider.mul(PERCENTAGE_MODULO).div(totalDelegatedStake);
// Delegators' share before the commission cut
uint256 grossRewardsDueToDelegators = _amount.mul(percentageOfStakeThatIsDelegatedToServiceProvider).div(PERCENTAGE_MODULO);
// Validator's share before the commission
uint256 baseRewardsDueToServiceProvider = _amount.sub(grossRewardsDueToDelegators);
// Validator's commission
uint256 rewardsFee = grossRewardsDueToDelegators.mul(rewardsFeePercentage).div(PERCENTAGE_MODULO);
// Delegators' share after the commission cut
uint256 netRewardsDueToDelegators = grossRewardsDueToDelegators.sub(rewardsFee);
return (stakeDelegatedToServiceProvider, rewardsFee, baseRewardsDueToServiceProvider, netRewardsDueToDelegators);
}
// Ensure this is not called when sender is service provider
function _sendDelegatorAnyPendingRewards() private {
uint256 pending = delegatedStake[_msgSender()].mul(accTokensPerShare).div(1e18).sub(rewardDebt[_msgSender()]);
if (pending > 0) {
rewardDebt[_msgSender()] = delegatedStake[_msgSender()].mul(accTokensPerShare).div(1e18);
cudosToken.transfer(_msgSender(), pending);
}
}
function _stakeServiceProviderBond(uint256 _rewardsProgrammeId, uint256 _rewardsFeePercentage) private {
// ServiceProvider.stakeServiceProviderBond: Service provider already set up
require(!isServiceProviderFullySetup, "SPC7");
// ServiceProvider.stakeServiceProviderBond: Exited service provider cannot reenter
require(!exited, "ECR1");
// ServiceProvider.stakeServiceProviderBond: Fee percentage must be between zero and one
require(_rewardsFeePercentage > 0 && _rewardsFeePercentage < PERCENTAGE_MODULO, "FP2");
StakingRewards rewards = StakingRewards(controller);
uint256 minRequiredStakingAmountForServiceProviders = rewards.minRequiredStakingAmountForServiceProviders();
uint256 minServiceProviderFee = rewards.minServiceProviderFee();
//ServiceProvider.stakeServiceProviderBond: Fee percentage must be greater or equal to minServiceProviderFee
require(_rewardsFeePercentage >= minServiceProviderFee, "SPF1");
rewardsFeePercentage = _rewardsFeePercentage;
rewardsProgrammeId = _rewardsProgrammeId;
minStakingLength = rewards._findMinStakingLength(_rewardsProgrammeId);
isServiceProviderFullySetup = true;
delegatedStake[serviceProvider] = minRequiredStakingAmountForServiceProviders;
totalDelegatedStake = totalDelegatedStake.add(minRequiredStakingAmountForServiceProviders);
// A mass update is required at this point
_getAndDistributeRewardsWithMassUpdate();
rewards.stake(
_rewardsProgrammeId,
_msgSender(),
minRequiredStakingAmountForServiceProviders
);
// Store date for lock-up calculation
WithdrawalRequest storage withdrawalReq = withdrawalRequest[_msgSender()];
withdrawalReq.lastStakedBlock = rewards._getBlock();
emit StakedServiceProviderBond(serviceProvider, serviceProviderManager, _rewardsProgrammeId, rewardsFeePercentage);
}
// *** CUDO Admin Emergency only **
function recoverERC20(address _erc20, address _recipient, uint256 _amount) external {
// ServiceProvider.recoverERC20: Only admin
require(StakingRewards(controller).hasAdminRole(_msgSender()), "OA");
IERC20(_erc20).transfer(_recipient, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
/*
The MIT License (MIT)
Copyright (c) 2018 Murray Software, LLC.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
//solhint-disable max-line-length
//solhint-disable no-inline-assembly
contract CloneFactory {
function createClone(address target) internal returns (address result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
result := create(0, clone, 0x37)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/access/AccessControl.sol";
contract CudosAccessControls is AccessControl {
// Role definitions
bytes32 public constant WHITELISTED_ROLE = keccak256("WHITELISTED_ROLE");
bytes32 public constant SMART_CONTRACT_ROLE = keccak256("SMART_CONTRACT_ROLE");
// Events
event AdminRoleGranted(
address indexed beneficiary,
address indexed caller
);
event AdminRoleRemoved(
address indexed beneficiary,
address indexed caller
);
event WhitelistRoleGranted(
address indexed beneficiary,
address indexed caller
);
event WhitelistRoleRemoved(
address indexed beneficiary,
address indexed caller
);
event SmartContractRoleGranted(
address indexed beneficiary,
address indexed caller
);
event SmartContractRoleRemoved(
address indexed beneficiary,
address indexed caller
);
modifier onlyAdminRole() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "CudosAccessControls: sender must be an admin");
_;
}
constructor() {
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
}
/////////////
// Lookups //
/////////////
function hasAdminRole(address _address) external view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _address);
}
function hasWhitelistRole(address _address) external view returns (bool) {
return hasRole(WHITELISTED_ROLE, _address);
}
function hasSmartContractRole(address _address) external view returns (bool) {
return hasRole(SMART_CONTRACT_ROLE, _address);
}
///////////////
// Modifiers //
///////////////
function addAdminRole(address _address) external onlyAdminRole {
_setupRole(DEFAULT_ADMIN_ROLE, _address);
emit AdminRoleGranted(_address, _msgSender());
}
function removeAdminRole(address _address) external onlyAdminRole {
revokeRole(DEFAULT_ADMIN_ROLE, _address);
emit AdminRoleRemoved(_address, _msgSender());
}
function addWhitelistRole(address _address) external onlyAdminRole {
_setupRole(WHITELISTED_ROLE, _address);
emit WhitelistRoleGranted(_address, _msgSender());
}
function removeWhitelistRole(address _address) external onlyAdminRole {
revokeRole(WHITELISTED_ROLE, _address);
emit WhitelistRoleRemoved(_address, _msgSender());
}
function addSmartContractRole(address _address) external onlyAdminRole {
_setupRole(SMART_CONTRACT_ROLE, _address);
emit SmartContractRoleGranted(_address, _msgSender());
}
function removeSmartContractRole(address _address) external onlyAdminRole {
revokeRole(SMART_CONTRACT_ROLE, _address);
emit SmartContractRoleRemoved(_address, _msgSender());
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import { CudosAccessControls } from "../CudosAccessControls.sol";
contract StakingRewardsGuild {
using SafeERC20 for IERC20;
IERC20 public token;
CudosAccessControls public accessControls;
constructor(IERC20 _token, CudosAccessControls _accessControls) {
token = _token;
accessControls = _accessControls;
}
function withdrawTo(address _recipient, uint256 _amount) external {
require(
accessControls.hasSmartContractRole(msg.sender),
// StakingRewardsGuild.withdrawTo: Only authorised smart contract
"OASM"
);
// StakingRewardsGuild.withdrawTo: recipient is zero address
require(_recipient != address(0), "SRG1");
token.transfer(_recipient, _amount);
}
// *****
// Admin
// *****
function recoverERC20(address _erc20, address _recipient, uint256 _amount) external {
// StakingRewardsGuild.recoverERC20: Only admin
require(accessControls.hasAdminRole(msg.sender), "OA");
IERC20(_erc20).safeTransfer(_recipient, _amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
function hasRole(bytes32 role, address account) external view returns (bool);
function getRoleAdmin(bytes32 role) external view returns (bytes32);
function grantRole(bytes32 role, address account) external;
function revokeRole(bytes32 role, address account) external;
function renounceRole(bytes32 role, address account) external;
}
/**
* @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 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 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]{20}) is missing role (0x[0-9a-f]{32})$/
*
* _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]{20}) is missing role (0x[0-9a-f]{32})$/
*/
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 {
emit RoleAdminChanged(role, getRoleAdmin(role), adminRole);
_roles[role].adminRole = 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());
}
}
}
// 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);
}
|
require(accessControls.hasWhitelistRole(_msgSender()), "StakingRewards.updateMinServiceProviderFee: Only whitelisted");
|
function updateMinServiceProviderFee(uint256 _newValue) external whitelisted {
require(_newValue > 0 && _newValue < PERCENTAGE_MODULO, "StakingRewards.updateMinServiceProviderFee: Fee percentage must be between zero and one");
emit MinServiceProviderFeeUpdated(minServiceProviderFee, _newValue);
minServiceProviderFee = _newValue;
}
| 129,343 |
pragma solidity ^0.4.16;
/**
* Safe math library for division
**/
library SafeMath {
function mul(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a / b;
return c;
}
function sub(uint256 a, uint256 b) internal returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* Contract that will split any incoming Ether to its creator
**/
contract Forwarder {
using SafeMath for uint256;
// Addresses to which any funds sent to this contract will be forwarded
address public destinationAddress80;
address public destinationAddress20;
/**
* Create the contract, and set the destination addresses
**/
function Forwarder() {
// This is the escrow/ICO address for refunds
destinationAddress20 = 0xf6962cfe3b9618374097d51bc6691efb3974d06f;
// All other funds to be used per whitepaper guidelines
destinationAddress80 = 0xf030541A54e89cB22b3653a090b233A209E44F38;
}
/**
* Default function; Gets called when Ether is deposited, and forwards it to destination addresses
**/
function () payable {
if (msg.value > 0) {
uint256 totalAmount = msg.value;
uint256 tokenValueAmount = totalAmount.div(5);
uint256 restAmount = totalAmount.sub(tokenValueAmount);
if (!destinationAddress20.send(tokenValueAmount)) revert();
if (!destinationAddress80.send(restAmount)) revert();
}
}
}
|
Create the contract, and set the destination addresses/ This is the escrow/ICO address for refunds All other funds to be used per whitepaper guidelines
|
function Forwarder() {
destinationAddress20 = 0xf6962cfe3b9618374097d51bc6691efb3974d06f;
destinationAddress80 = 0xf030541A54e89cB22b3653a090b233A209E44F38;
}
| 6,370,480 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "./imports/ICERC20.sol";
import "./imports/IComptroller.sol";
import "../../libraries/DecimalsConverter.sol";
import "../../interfaces/IContractsRegistry.sol";
import "../../interfaces/IReinsurancePool.sol";
import "../../interfaces/IDefiProtocol.sol";
import "../../abstract/AbstractDependant.sol";
import "../../Globals.sol";
contract CompoundProtocol is IDefiProtocol, OwnableUpgradeable, AbstractDependant {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using Math for uint256;
uint256 internal constant ERRCODE_OK = 0;
// 1 * 10 ^ (18 + underlyingDecimals(6) - cTokenDecimals(8) + 2 (convert from underlyingDecimals to cTokenDecimals)
uint256 internal constant COMPOUND_EXCHANGE_RATE_PRECISION = 10**18;
uint256 public totalDeposit;
uint256 public totalRewards;
uint256 public stblDecimals;
ERC20 public override stablecoin;
ICERC20 public cToken;
IComptroller comptroller;
IReinsurancePool public reinsurancePool;
address public yieldGeneratorAddress;
address public capitalPoolAddress;
//new state post v2
/// @notice setting or update of totalStableValue after call _totalValue() function
uint256 public totalStableValue;
modifier onlyYieldGenerator() {
require(_msgSender() == yieldGeneratorAddress, "CP: Not a yield generator contract");
_;
}
function __CompoundProtocol_init() external initializer {
__Ownable_init();
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
stablecoin = ERC20(_contractsRegistry.getUSDTContract());
cToken = ICERC20(_contractsRegistry.getCompoundCTokenContract());
comptroller = IComptroller(_contractsRegistry.getCompoundComptrollerContract());
yieldGeneratorAddress = _contractsRegistry.getYieldGeneratorContract();
reinsurancePool = IReinsurancePool(_contractsRegistry.getReinsurancePoolContract());
capitalPoolAddress = _contractsRegistry.getCapitalPoolContract();
stblDecimals = stablecoin.decimals();
}
/// @notice deposit an amount in Compound defi protocol
/// @param amount uint256 the amount of stable coin will deposit
function deposit(uint256 amount) external override onlyYieldGenerator {
// Approve `amount` stablecoin to cToken
stablecoin.safeApprove(address(cToken), 0);
stablecoin.safeApprove(address(cToken), amount);
// Deposit `amount` stablecoin to cToken
uint256 res = cToken.mint(amount);
if (res == ERRCODE_OK) {
totalDeposit = totalDeposit.add(amount);
}
}
function withdraw(uint256 amountInUnderlying)
external
override
onlyYieldGenerator
returns (uint256 actualAmountWithdrawn)
{
if (totalDeposit >= amountInUnderlying) {
// Withdraw `amountInUnderlying` stablecoin from cToken
// Transfer `amountInUnderlying` stablecoin to capital pool
uint256 res = cToken.redeemUnderlying(amountInUnderlying);
if (res == ERRCODE_OK) {
stablecoin.safeTransfer(capitalPoolAddress, amountInUnderlying);
actualAmountWithdrawn = amountInUnderlying;
totalDeposit = totalDeposit.sub(actualAmountWithdrawn);
}
}
}
function claimRewards() external override onlyYieldGenerator {
uint256 _totalStblValue = _totalValue();
if (_totalStblValue > totalDeposit) {
uint256 _accumaltedAmount = _totalStblValue.sub(totalDeposit);
uint256 res = cToken.redeemUnderlying(_accumaltedAmount);
if (res == ERRCODE_OK) {
stablecoin.safeTransfer(capitalPoolAddress, _accumaltedAmount);
reinsurancePool.addInterestFromDefiProtocols(_accumaltedAmount);
// get comp reward on top of farming and send it to reinsurance pool
comptroller.claimComp(address(this));
ERC20 comp = ERC20(comptroller.getCompAddress());
uint256 compBalance = comp.balanceOf(address(this));
if (compBalance > 0) {
comp.safeTransfer(address(reinsurancePool), compBalance);
}
totalRewards = totalRewards.add(_accumaltedAmount);
}
}
}
function totalValue() external view override returns (uint256) {
return totalStableValue;
}
function setRewards(address newValue) external override onlyYieldGenerator {}
function _totalValue() internal returns (uint256) {
uint256 cTokenBalance = cToken.balanceOf(address(this));
// Amount of stablecoin units that 1 unit of cToken can be exchanged for, scaled by 10^18
uint256 cTokenPrice = cToken.exchangeRateCurrent();
uint256 _totalStableValue =
cTokenBalance.mul(cTokenPrice).div(COMPOUND_EXCHANGE_RATE_PRECISION);
totalStableValue = _totalStableValue;
return _totalStableValue;
}
function getOneDayGain() external view override returns (uint256) {
uint256 rate = cToken.supplyRatePerBlock().mul(BLOCKS_PER_DAY).mul(PRECISION);
return rate.div(10**18);
}
function updateTotalValue() external override onlyYieldGenerator returns (uint256) {
return _totalValue();
}
function updateTotalDeposit(uint256 _lostAmount) external override onlyYieldGenerator {
totalDeposit = totalDeposit.sub(_lostAmount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @notice the intention of this library is to be able to easily convert
/// one amount of tokens with N decimal places
/// to another amount with M decimal places
library DecimalsConverter {
using SafeMath for uint256;
function convert(
uint256 amount,
uint256 baseDecimals,
uint256 destinationDecimals
) internal pure returns (uint256) {
if (baseDecimals > destinationDecimals) {
amount = amount.div(10**(baseDecimals - destinationDecimals));
} else if (baseDecimals < destinationDecimals) {
amount = amount.mul(10**(destinationDecimals - baseDecimals));
}
return amount;
}
function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) {
return convert(amount, baseDecimals, 18);
}
function convertFrom18(uint256 amount, uint256 destinationDecimals)
internal
pure
returns (uint256)
{
return convert(amount, 18, destinationDecimals);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IReinsurancePool {
function withdrawBMITo(address to, uint256 amount) external;
function withdrawSTBLTo(address to, uint256 amount) external;
/// @notice add the interest amount from defi protocol : access defi protocols
/// @param intrestAmount uint256 the interest amount from defi protocols
function addInterestFromDefiProtocols(uint256 intrestAmount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
/// @notice Interface for defi protocols (Compound, Aave, bZx, etc.)
interface IDefiProtocol {
/// @return uint256 The total value locked in the defi protocol, in terms of the underlying stablecoin
function totalValue() external view returns (uint256);
/// @return ERC20 the erc20 stable coin which depoisted in the defi protocol
function stablecoin() external view returns (ERC20);
/// @notice deposit an amount in defi protocol
/// @param amount uint256 the amount of stable coin will deposit
function deposit(uint256 amount) external;
/// @notice withdraw an amount from defi protocol
/// @param amountInUnderlying uint256 the amount of underlying token to withdraw the deposited stable coin
function withdraw(uint256 amountInUnderlying) external returns (uint256 actualAmountWithdrawn);
/// @notice Claims farmed tokens and sends it to the rewards pool
function claimRewards() external;
/// @notice set the address of receiving rewards
/// @param newValue address the new address to recieve the rewards
function setRewards(address newValue) external;
/// @notice get protocol gain for one day for one unit
function getOneDayGain() external view returns (uint256);
///@dev update total value only for compound
function updateTotalValue() external returns (uint256);
///@dev update total deposit in case of hard rebalancing
function updateTotalDeposit(uint256 _lostAmount) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getUniswapBMIToUSDTPairContract() external view returns (address);
function getSushiswapRouterContract() external view returns (address);
function getSushiswapBMIToETHPairContract() external view returns (address);
function getSushiswapBMIToUSDTPairContract() external view returns (address);
function getSushiSwapMasterChefV2Contract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getBMICoverStakingViewContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getNFTStakingContract() external view returns (address);
function getLiquidityBridgeContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLeveragePortfolioViewContract() external view returns (address);
function getCapitalPoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingETHContract() external view returns (address);
function getLiquidityMiningStakingUSDTContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
function getAaveProtocolContract() external view returns (address);
function getAaveLendPoolAddressProvdierContract() external view returns (address);
function getAaveATokenContract() external view returns (address);
function getCompoundProtocolContract() external view returns (address);
function getCompoundCTokenContract() external view returns (address);
function getCompoundComptrollerContract() external view returns (address);
function getYearnProtocolContract() external view returns (address);
function getYearnVaultContract() external view returns (address);
function getYieldGeneratorContract() external view returns (address);
function getShieldMiningContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IComptroller {
function claimComp(address holder) external;
function getCompAddress() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface ICERC20 {
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function exchangeRateStored() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant DAYS_IN_THE_YEAR = 365;
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION;
uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23;
uint256 constant EPOCH_DAYS_AMOUNT = 7;
// 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].
*/
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.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.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;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) {
_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.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, 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.7.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.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
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
|
Interface for defi protocols (Compound, Aave, bZx, etc.)
|
interface IDefiProtocol {
function totalValue() external view returns (uint256);
function stablecoin() external view returns (ERC20);
function deposit(uint256 amount) external;
function withdraw(uint256 amountInUnderlying) external returns (uint256 actualAmountWithdrawn);
function claimRewards() external;
function setRewards(address newValue) external;
function getOneDayGain() external view returns (uint256);
function updateTotalValue() external returns (uint256);
function updateTotalDeposit(uint256 _lostAmount) external;
}
pragma solidity ^0.7.4;
}
| 384,555 |
// File: contracts\math\SafeMath.sol
pragma solidity 0.5.4;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
// File: contracts\RedTokenAccessControl.sol
pragma solidity 0.5.4;
/*
* @title RedTokenAccessControl
* @notice This contract defines organizational roles and permissions.
*/
contract RedTokenAccessControl {
event Paused();
event Unpaused();
event PausedUser(address indexed account);
event UnpausedUser(address indexed account);
/*
* @notice CEO's address
*/
address public ceoAddress;
/*
* @notice CFO's address
*/
address public cfoAddress;
/*
* @notice COO's address
*/
address public cooAddress;
bool public paused = false;
/*
* @notice paused users status
*/
mapping (address => bool) private pausedUsers;
/*
* @notice init constructor
*/
constructor () internal {
ceoAddress = msg.sender;
cfoAddress = msg.sender;
cooAddress = msg.sender;
}
/*
* @dev Modifier to make a function only callable by the CEO
*/
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/*
* @dev Modifier to make a function only callable by the CFO
*/
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/*
* @dev Modifier to make a function only callable by the COO
*/
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/*
* @dev Modifier to make a function only callable by C-level execs
*/
modifier onlyCLevel() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress ||
msg.sender == cfoAddress
);
_;
}
/*
* @dev Modifier to make a function only callable by CEO or CFO
*/
modifier onlyCEOOrCFO() {
require(
msg.sender == cfoAddress ||
msg.sender == ceoAddress
);
_;
}
/*
* @dev Modifier to make a function only callable by CEO or COO
*/
modifier onlyCEOOrCOO() {
require(
msg.sender == cooAddress ||
msg.sender == ceoAddress
);
_;
}
/*
* @notice Sets a new CEO
* @param _newCEO - the address of the new CEO
*/
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/*
* @notice Sets a new CFO
* @param _newCFO - the address of the new CFO
*/
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/*
* @notice Sets a new COO
* @param _newCOO - the address of the new COO
*/
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/* Pausable functionality adapted from OpenZeppelin **/
/*
* @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);
_;
}
/*
* @notice called by any C-LEVEL to pause, triggers stopped state
*/
function pause() external onlyCLevel whenNotPaused {
paused = true;
emit Paused();
}
/*
* @notice called by any C-LEVEL to unpause, returns to normal state
*/
function unpause() external onlyCLevel whenPaused {
paused = false;
emit Unpaused();
}
/* user Pausable functionality ref someting : openzeppelin/access/Roles.sol **/
/*
* @dev Modifier to make a function callable only when the user is not paused.
*/
modifier whenNotPausedUser(address account) {
require(account != address(0));
require(!pausedUsers[account]);
_;
}
/*
* @dev Modifier to make a function callable only when the user is paused.
*/
modifier whenPausedUser(address account) {
require(account != address(0));
require(pausedUsers[account]);
_;
}
/*
* @dev check if an account has this pausedUsers
* @return bool
*/
function has(address account) internal view returns (bool) {
require(account != address(0));
return pausedUsers[account];
}
/*
* @notice _addPauseUser
*/
function _addPauseUser(address account) internal {
require(account != address(0));
require(!has(account));
pausedUsers[account] = true;
emit PausedUser(account);
}
/*
* @notice _unpausedUser
*/
function _unpausedUser(address account) internal {
require(account != address(0));
require(has(account));
pausedUsers[account] = false;
emit UnpausedUser(account);
}
/*
* @notice isPausedUser
*/
function isPausedUser(address account) external view returns (bool) {
return has(account);
}
/*
* @notice called by the COO to pauseUser, triggers stopped user state
*/
function pauseUser(address account) external onlyCOO whenNotPausedUser(account) {
_addPauseUser(account);
}
/*
* @notice called by any C-LEVEL to unpauseUser, returns to user state
*/
function unpauseUser(address account) external onlyCLevel whenPausedUser(account) {
_unpausedUser(account);
}
}
// File: contracts\RedTokenBase.sol
pragma solidity 0.5.4;
/*
* @title RedTokenBase
* @notice This contract defines the RedToken data structure and how to read from it / functions
*/
contract RedTokenBase is RedTokenAccessControl {
using SafeMath for uint256;
/*
* @notice Product defines a RedToken
*/
struct RedToken {
uint256 tokenId;
string rmsBondNo;
uint256 bondAmount;
uint256 listingAmount;
uint256 collectedAmount;
uint createdTime;
bool isValid;
}
/*
* @notice tokenId for share users by listingAmount
*/
mapping (uint256 => mapping(address => uint256)) shareUsers;
/*
* @notice tokenid by share accounts in shareUsers list iterator.
*/
mapping (uint256 => address []) shareUsersKeys;
/** events **/
event RedTokenCreated(
address account,
uint256 tokenId,
string rmsBondNo,
uint256 bondAmount,
uint256 listingAmount,
uint256 collectedAmount,
uint createdTime
);
/*
* @notice All redTokens in existence.
* @dev The ID of each redToken is an index in this array.
*/
RedToken[] redTokens;
/*
* @notice Get a redToken RmsBondNo
* @param _tokenId the token id
*/
function redTokenRmsBondNo(uint256 _tokenId) external view returns (string memory) {
return redTokens[_tokenId].rmsBondNo;
}
/*
* @notice Get a redToken BondAmount
* @param _tokenId the token id
*/
function redTokenBondAmount(uint256 _tokenId) external view returns (uint256) {
return redTokens[_tokenId].bondAmount;
}
/*
* @notice Get a redToken ListingAmount
* @param _tokenId the token id
*/
function redTokenListingAmount(uint256 _tokenId) external view returns (uint256) {
return redTokens[_tokenId].listingAmount;
}
/*
* @notice Get a redToken CollectedAmount
* @param _tokenId the token id
*/
function redTokenCollectedAmount(uint256 _tokenId) external view returns (uint256) {
return redTokens[_tokenId].collectedAmount;
}
/*
* @notice Get a redToken CreatedTime
* @param _tokenId the token id
*/
function redTokenCreatedTime(uint256 _tokenId) external view returns (uint) {
return redTokens[_tokenId].createdTime;
}
/*
* @notice isValid a redToken
* @param _tokenId the token id
*/
function isValidRedToken(uint256 _tokenId) public view returns (bool) {
return redTokens[_tokenId].isValid;
}
/*
* @notice info a redToken
* @param _tokenId the token id
*/
function redTokenInfo(uint256 _tokenId)
external view returns (uint256, string memory, uint256, uint256, uint256, uint)
{
require(isValidRedToken(_tokenId));
RedToken memory _redToken = redTokens[_tokenId];
return (
_redToken.tokenId,
_redToken.rmsBondNo,
_redToken.bondAmount,
_redToken.listingAmount,
_redToken.collectedAmount,
_redToken.createdTime
);
}
/*
* @notice info a token of share users
* @param _tokenId the token id
*/
function redTokenInfoOfshareUsers(uint256 _tokenId) external view returns (address[] memory, uint256[] memory) {
require(isValidRedToken(_tokenId));
uint256 keySize = shareUsersKeys[_tokenId].length;
address[] memory addrs = new address[](keySize);
uint256[] memory amounts = new uint256[](keySize);
for (uint index = 0; index < keySize; index++) {
addrs[index] = shareUsersKeys[_tokenId][index];
amounts[index] = shareUsers[_tokenId][addrs[index]];
}
return (addrs, amounts);
}
}
// File: contracts\interfaces\ERC721.sol
pragma solidity 0.5.4;
/// @title ERC-721 Non-Fungible Token Standard
/// @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
/// Note: the ERC-165 identifier for this interface is 0x80ac58cd.
interface ERC721 {
/// @dev This emits when ownership of any NFT changes by any mechanism.
/// This event emits when NFTs are created (`from` == 0) and destroyed
/// (`to` == 0). Exception: during contract creation, any number of NFTs
/// may be created and assigned without emitting Transfer. At the time of
/// any transfer, the approved address for that NFT (if any) is reset to none.
event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId);
/// @dev This emits when the approved address for an NFT is changed or
/// reaffirmed. The zero address indicates there is no approved address.
/// When a Transfer event emits, this also indicates that the approved
/// address for that NFT (if any) is reset to none.
event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId);
/// @dev This emits when an operator is enabled or disabled for an owner.
/// The operator can manage all NFTs of the owner.
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
/// @notice Count all NFTs assigned to an owner
/// @dev NFTs assigned to the zero address are considered invalid, and this
/// function throws for queries about the zero address.
/// @param _owner An address for whom to query the balance
/// @return The number of NFTs owned by `_owner`, possibly zero
function balanceOf(address _owner) external view returns (uint256);
/// @notice Find the owner of an NFT
/// @dev NFTs assigned to zero address are considered invalid, and queries
/// about them do throw.
/// @param _tokenId The identifier for an NFT
/// @return The address of the owner of the NFT
function ownerOf(uint256 _tokenId) external view returns (address);
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT. When transfer is complete, this function
/// checks if `_to` is a smart contract (code size > 0). If so, it calls
/// `onERC721Received` on `_to` and throws if the return value is not
/// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
/// @param data Additional data with no specified format, sent in call to `_to`
function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes calldata data) external payable;
/// @notice Transfers the ownership of an NFT from one address to another address
/// @dev This works identically to the other function with an extra data parameter,
/// except this function just sets data to "".
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function safeTransferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE
/// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE
/// THEY MAY BE PERMANENTLY LOST
/// @dev Throws unless `msg.sender` is the current owner, an authorized
/// operator, or the approved address for this NFT. Throws if `_from` is
/// not the current owner. Throws if `_to` is the zero address. Throws if
/// `_tokenId` is not a valid NFT.
/// @param _from The current owner of the NFT
/// @param _to The new owner
/// @param _tokenId The NFT to transfer
function transferFrom(address _from, address _to, uint256 _tokenId) external payable;
/// @notice Change or reaffirm the approved address for an NFT
/// @dev The zero address indicates there is no approved address.
/// Throws unless `msg.sender` is the current NFT owner, or an authorized
/// operator of the current owner.
/// @param _approved The new approved NFT controller
/// @param _tokenId The NFT to approve
function approve(address _approved, uint256 _tokenId) external payable;
/// @notice Enable or disable approval for a third party ("operator") to manage
/// all of `msg.sender`'s assets
/// @dev Emits the ApprovalForAll event. The contract MUST allow
/// multiple operators per owner.
/// @param _operator Address to add to the set of authorized operators
/// @param _approved True if the operator is approved, false to revoke approval
function setApprovalForAll(address _operator, bool _approved) external;
/// @notice Get the approved address for a single NFT
/// @dev Throws if `_tokenId` is not a valid NFT.
/// @param _tokenId The NFT to find the approved address for
/// @return The approved address for this NFT, or the zero address if there is none
function getApproved(uint256 _tokenId) external view returns (address);
/// @notice Query if an address is an authorized operator for another address
/// @param _owner The address that owns the NFTs
/// @param _operator The address that acts on behalf of the owner
/// @return True if `_operator` is an approved operator for `_owner`, false otherwise
function isApprovedForAll(address _owner, address _operator) external view returns (bool);
}
// File: contracts\interfaces\ERC721Metadata.sol
pragma solidity 0.5.4;
/*
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
* Note: the ERC-165 identifier for this interface is 0x5b5e139f
*/
interface ERC721Metadata /* is ERC721 */ {
/*
* @notice A descriptive name for a collection of NFTs in this contract
*/
function name() external pure returns (string memory _name);
/*
* @notice An abbreviated name for NFTs in this contract
*/
function symbol() external pure returns (string memory _symbol);
/*
* @notice A distinct Uniform Resource Identifier (URI) for a given asset.
* @dev Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC
* 3986. The URI may point to a JSON file that conforms to the "ERC721
* Metadata JSON Schema".
*/
function tokenURI(uint256 _tokenId) external view returns (string memory);
}
// File: contracts\interfaces\ERC721Enumerable.sol
pragma solidity 0.5.4;
/*
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
* Note: the ERC-165 identifier for this interface is 0x780e9d63
*/
interface ERC721Enumerable /* is ERC721 */ {
/*
* @notice Count NFTs tracked by this contract
* @return A count of valid NFTs tracked by this contract, where each one of
* them has an assigned and queryable owner not equal to the zero address
*/
function totalSupply() external view returns (uint256);
/*
* @notice Enumerate valid NFTs
* @dev Throws if `_index` >= `totalSupply()`.
* @param _index A counter less than `totalSupply()`
* @return The token identifier for the `_index`th NFT,
* (sort order not specified)
*/
function tokenByIndex(uint256 _index) external view returns (uint256);
/*
* @notice Enumerate NFTs assigned to an owner
* @dev Throws if `_index` >= `balanceOf(_owner)` or if
* `_owner` is the zero address, representing invalid NFTs.
* @param _owner An address where we are interested in NFTs owned by them
* @param _index A counter less than `balanceOf(_owner)`
* @return The token identifier for the `_index`th NFT assigned to `_owner`,
* (sort order not specified)
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _tokenId);
}
// File: contracts\interfaces\ERC165.sol
pragma solidity 0.5.4;
interface ERC165 {
/*
* @notice Query if a contract implements an interface
* @param interfaceID The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
* @return `true` if the contract implements `interfaceID` and
* `interfaceID` is not 0xffffffff, `false` otherwise
*/
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
// File: contracts\strings\Strings.sol
pragma solidity 0.5.4;
library Strings {
// via https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.5.sol
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (uint i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (uint i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (uint i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (uint i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory) {
return strConcat(_a, _b, _c, _d, "");
}
function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory) {
return strConcat(_a, _b, _c, "", "");
}
function strConcat(string memory _a, string memory _b) internal pure returns (string memory) {
return strConcat(_a, _b, "", "", "");
}
function uint2str(uint i) internal pure returns (string memory) {
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0){
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0){
bstr[k--] = byte(uint8(48 + i % 10));
i /= 10;
}
return string(bstr);
}
}
// File: contracts\interfaces\ERC721TokenReceiver.sol
pragma solidity 0.5.4;
/*
* @dev Note: the ERC-165 identifier for this interface is 0xf0b9e5ba
*/
interface ERC721TokenReceiver {
/*
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `transfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
* unless throwing
*/
function onERC721Received(address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4);
}
// File: contracts\RedTokenOwnership.sol
pragma solidity 0.5.4;
/*
* @title RedTokenOwnership
* @notice control by TokenBase.
*/
contract RedTokenOwnership is RedTokenBase, ERC721, ERC165, ERC721Metadata, ERC721Enumerable {
using SafeMath for uint256;
// Total amount of tokens
uint256 private totalTokens;
// Mapping from token ID to owner
mapping (uint256 => address) private tokenOwner;
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping (uint256 => uint256) internal ownedTokensIndex;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner address to operator address to approval
mapping (address => mapping (address => bool)) internal operatorApprovals;
/** events **/
event calculateShareUsers(uint256 tokenId, address owner, address from, address to, uint256 amount);
event CollectedAmountUpdate(uint256 tokenId, address owner, uint256 amount);
/** Constants **/
// Configure these for your own deployment
string internal constant NAME = "RedToken";
string internal constant SYMBOL = "REDT";
string internal tokenMetadataBaseURI = "https://doc.reditus.co.kr/?docid=";
/** structs **/
function supportsInterface(
bytes4 interfaceID) // solium-disable-line dotta/underscore-function-arguments
external view returns (bool)
{
return
interfaceID == this.supportsInterface.selector || // ERC165
interfaceID == 0x5b5e139f || // ERC721Metadata
interfaceID == 0x80ac58cd || // ERC-721
interfaceID == 0x780e9d63; // ERC721Enumerable
}
/*
* @notice Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/** external functions **/
/*
* @notice token's name
*/
function name() external pure returns (string memory) {
return NAME;
}
/*
* @notice symbols's name
*/
function symbol() external pure returns (string memory) {
return SYMBOL;
}
/*
* @notice tokenURI
* @dev do not checked in array and used function isValidRedToken value is not important, only check in redTokens array
*/
function tokenURI(uint256 _tokenId)
external
view
returns (string memory infoUrl)
{
if ( isValidRedToken(_tokenId) ){
return Strings.strConcat( tokenMetadataBaseURI, Strings.uint2str(_tokenId));
}else{
return Strings.strConcat( tokenMetadataBaseURI, Strings.uint2str(_tokenId));
}
}
/*
* @notice setTokenMetadataBaseURI
*/
function setTokenMetadataBaseURI(string calldata _newBaseURI) external onlyCOO {
tokenMetadataBaseURI = _newBaseURI;
}
/*
* @notice Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return totalTokens;
}
/*
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/*
* @notice Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokens[_owner].length;
}
/*
* @notice Gets the list of tokens owned by a given address
* @param _owner address to query the tokens of
* @return uint256[] representing the list of tokens owned by the passed address
*/
function tokensOf(address _owner) public view returns (uint256[] memory) {
require(_owner != address(0));
return ownedTokens[_owner];
}
/*
* @notice Enumerate valid NFTs
* @dev Our Licenses are kept in an array and each new License-token is just
* the next element in the array. This method is required for ERC721Enumerable
* which may support more complicated storage schemes. However, in our case the
* _index is the tokenId
* @param _index A counter less than `totalSupply()`
* @return The token identifier for the `_index`th NFT
*/
function tokenByIndex(uint256 _index) external view returns (uint256) {
require(_index < totalSupply());
return _index;
}
/*
* @notice Enumerate NFTs assigned to an owner
* @dev Throws if `_index` >= `balanceOf(_owner)` or if
* `_owner` is the zero address, representing invalid NFTs.
* @param _owner An address where we are interested in NFTs owned by them
* @param _index A counter less than `balanceOf(_owner)`
* @return The token identifier for the `_index`th NFT assigned to `_owner`,
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index)
external
view
returns (uint256 _tokenId)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/*
* @notice Gets the approved address to take ownership of a given token ID
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved to take ownership of the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/*
* @notice Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/*
* @notice Approves another address to claim for the ownership of the given token ID
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId)
external
payable
whenNotPaused
whenNotPausedUser(msg.sender)
onlyOwnerOf(_tokenId)
{
address owner = ownerOf(_tokenId);
require(_to != owner);
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/*
* @notice Enable or disable approval for a third party ("operator") to manage all your assets
* @dev Emits the ApprovalForAll event
* @param _to Address to add to the set of authorized operators.
* @param _approved True if the operators is approved, false to revoke approval
*/
function setApprovalForAll(address _to, bool _approved)
external
whenNotPaused
whenNotPausedUser(msg.sender)
{
if(_approved) {
approveAll(_to);
} else {
disapproveAll(_to);
}
}
/*
* @notice Approves another address to claim for the ownership of any tokens owned by this account
* @param _to address to be approved for the given token ID
*/
function approveAll(address _to)
public
payable
whenNotPaused
whenNotPausedUser(msg.sender)
{
require(_to != msg.sender);
require(_to != address(0));
operatorApprovals[msg.sender][_to] = true;
emit ApprovalForAll(msg.sender, _to, true);
}
/*
* @notice Removes approval for another address to claim for the ownership of any
* tokens owned by this account.
* @dev Note that this only removes the operator approval and
* does not clear any independent, specific approvals of token transfers to this address
* @param _to address to be disapproved for the given token ID
*/
function disapproveAll(address _to)
public
payable
whenNotPaused
whenNotPausedUser(msg.sender)
{
require(_to != msg.sender);
delete operatorApprovals[msg.sender][_to];
emit ApprovalForAll(msg.sender, _to, false);
}
/*
* @notice Transfer a token 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 token
* @param _to The address that will take ownership of the token. Can be any address, including the caller
* @param _tokenId The ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
payable
whenNotPaused
{
require(isSenderApprovedFor(_tokenId));
require(ownerOf(_tokenId) == _from);
_clearApprovalAndTransfer(ownerOf(_tokenId), _to, _tokenId);
}
/*
* @notice Transfers the ownership of an NFT from one address to another address
* @dev Throws unless `msg.sender` is the current owner, an authorized
* operator, or the approved address for this NFT. Throws if `_from` is
* not the current owner. Throws if `_to` is the zero address. Throws if
* `_tokenId` is not a valid NFT. When transfer is complete, this function
* checks if `_to` is a smart contract (code size > 0). If so, it calls
* `onERC721Received` on `_to` and throws if the return value is not
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`.
* @param _from The current owner of the NFT
* @param _to The new owner
* @param _tokenId The NFT to transfer
* @param _data Additional data with no specified format, sent in call to `_to`
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes memory _data
)
public
payable
whenNotPaused
whenNotPausedUser(msg.sender)
{
require(_to != address(0));
require(isValidRedToken(_tokenId));
transferFrom(_from, _to, _tokenId);
if (isContract(_to)) {
bytes4 tokenReceiverResponse = ERC721TokenReceiver(_to).onERC721Received.gas(50000)(
_from, _tokenId, _data
);
require(tokenReceiverResponse == bytes4(keccak256("onERC721Received(address,uint256,bytes)")));
}
}
/*
* @notice Tells whether the msg.sender is approved to transfer the given token ID or not
* Checks both for specific approval and operator approval
* @param _tokenId uint256 ID of the token to query the approval of
* @return bool whether transfer by msg.sender is approved for the given token ID or not
*/
function isSenderApprovedFor(uint256 _tokenId) public view returns (bool) {
return
ownerOf(_tokenId) == msg.sender ||
getApproved(_tokenId) == msg.sender ||
isApprovedForAll(ownerOf(_tokenId), msg.sender);
}
/*
* @notice Transfers the ownership of a given token ID to another address
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transfer(address _to, uint256 _tokenId)
external
payable
whenNotPaused
onlyOwnerOf(_tokenId)
{
_clearApprovalAndTransfer(msg.sender, _to, _tokenId);
}
/*
* @notice Transfers the ownership of an NFT from one address to another address
* @dev This works identically to the other function with an extra data parameter,
* except this function just sets data to ""
* @param _from The current owner of the NFT
* @param _to The new owner
* @param _tokenId The NFT to transfer
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
external
payable
{
safeTransferFrom(_from, _to, _tokenId, "");
}
/*
* @notice send amount shareUsers
*/
function sendAmountShareUsers(
uint256 _tokenId,
address _to,
uint256 _amount
)
external
onlyCOO
returns (bool)
{
require(_to != address(0));
return _calculateShareUsers(_tokenId, ownerOf(_tokenId), _to, _amount);
}
/*
* @notice send amount shareUsers
*/
function sendAmountShareUsersFrom(
uint256 _tokenId,
address _from,
address _to,
uint256 _amount
)
external
onlyCOO
returns (bool)
{
require(_to != address(0));
return _calculateShareUsers(_tokenId, _from, _to, _amount);
}
/*
* @notice update collectedAmount
*/
function updateCollectedAmount(uint256 _tokenId, uint256 _amount) external onlyCOO returns (bool) {
require(isValidRedToken(_tokenId));
require(_amount > 0);
address owner = ownerOf(_tokenId);
redTokens[_tokenId].collectedAmount = redTokens[_tokenId].collectedAmount.add(_amount);
emit CollectedAmountUpdate(_tokenId, owner, _amount);
return true;
}
/*
* @notice createRedToken
*/
function createRedToken(
address _user,
string calldata _rmsBondNo,
uint256 _bondAmount,
uint256 _listingAmount
)
external
onlyCOO
returns (uint256)
{
return _createRedToken(_user,_rmsBondNo,_bondAmount,_listingAmount);
}
/*
* @notice burn amount a token by share users
*/
function burnAmountByShareUser(
uint256 _tokenId,
address _from,
uint256 _amount
)
external
onlyCOO
returns (bool)
{
return _calculateShareUsers(_tokenId, _from, address(0), _amount);
}
/*
* @notice burn RedToken
*/
function burn(address _owner, uint256 _tokenId) external onlyCOO returns(bool) {
require(_owner != address(0));
return _burn(_owner, _tokenId);
}
/** internal function **/
function isContract(address _addr) internal view returns (bool) {
uint size;
assembly { size := extcodesize(_addr) }
return size > 0;
}
/*
* @notice checked shareUser by shareUsersKeys
*/
function isShareUser(uint256 _tokenId, address _from) internal onlyCOO view returns (bool) {
bool chechedUser = false;
for (uint index = 0; index < shareUsersKeys[_tokenId].length; index++) {
if ( shareUsersKeys[_tokenId][index] == _from ){
chechedUser = true;
break;
}
}
return chechedUser;
}
/*
* @notice Internal function to clear current approval and transfer the ownership of a given token ID
* @param _from address which you want to send tokens from
* @param _to address which you want to transfer the token to
* @param _tokenId uint256 ID of the token to be transferred
*/
function _clearApprovalAndTransfer(
address _from,
address _to,
uint256 _tokenId
)
whenNotPausedUser(msg.sender)
internal
{
require(_to != address(0));
require(_to != ownerOf(_tokenId));
require(ownerOf(_tokenId) == _from);
require(isValidRedToken(_tokenId));
_clearApproval(_from, _tokenId);
_removeToken(_from, _tokenId);
_addToken(_to, _tokenId);
_changeTokenShareUserByOwner(_from, _to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/*
* @notice change token owner rate sending
* @param _from address which you want to change rate from
* @param _to address which you want to change rate the token to
* @param _tokenId uint256 ID of the token to be change rate
*/
function _changeTokenShareUserByOwner(
address _from,
address _to,
uint256 _tokenId
)
internal
onlyCOO
{
uint256 amount = shareUsers[_tokenId][_from];
delete shareUsers[_tokenId][_from];
shareUsers[_tokenId][_to] = shareUsers[_tokenId][_to].add(amount);
if ( !isShareUser(_tokenId, _to) ) {
shareUsersKeys[_tokenId].push(_to);
}
}
/*
* @notice remove shareUsers
*/
function _calculateShareUsers(
uint256 _tokenId,
address _from,
address _to,
uint256 _amount
)
internal
onlyCOO
returns (bool)
{
require(_from != address(0));
require(_from != _to);
require(_amount > 0);
require(shareUsers[_tokenId][_from] >= _amount);
require(isValidRedToken(_tokenId));
address owner = ownerOf(_tokenId);
shareUsers[_tokenId][_from] = shareUsers[_tokenId][_from].sub(_amount);
shareUsers[_tokenId][_to] = shareUsers[_tokenId][_to].add(_amount);
if ( !isShareUser(_tokenId, _to) ) {
shareUsersKeys[_tokenId].push(_to);
}
emit calculateShareUsers(_tokenId, owner, _from, _to, _amount);
return true;
}
/*
* @notice Internal function to clear current approval of a given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(address _owner, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _owner);
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
function _createRedToken(address _user, string memory _rmsBondNo, uint256 _bondAmount, uint256 _listingAmount) private returns (uint256){
require(_user != address(0));
require(bytes(_rmsBondNo).length > 0);
require(_bondAmount > 0);
require(_listingAmount > 0);
uint256 _newTokenId = redTokens.length;
RedToken memory _redToken = RedToken({
tokenId: _newTokenId,
rmsBondNo: _rmsBondNo,
bondAmount: _bondAmount,
listingAmount: _listingAmount,
collectedAmount: 0,
createdTime: now,
isValid:true
});
redTokens.push(_redToken) - 1;
shareUsers[_newTokenId][_user] = shareUsers[_newTokenId][_user].add(_listingAmount);
shareUsersKeys[_newTokenId].push(_user);
_addToken(_user, _newTokenId);
emit RedTokenCreated(_user,
_redToken.tokenId,
_redToken.rmsBondNo,
_redToken.bondAmount,
_redToken.listingAmount,
_redToken.collectedAmount,
_redToken.createdTime);
return _newTokenId;
}
/*
* @notice Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addToken(address _to, uint256 _tokenId) private {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
uint256 length = balanceOf(_to);
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
totalTokens = totalTokens.add(1);
}
/*
* @notice Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeToken(address _from, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _from);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = balanceOf(_from).sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
tokenOwner[_tokenId] = address(0);
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
totalTokens = totalTokens.sub(1);
}
/*
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) private returns(bool) {
require(ownerOf(_tokenId) == _owner);
_clearApproval(_owner, _tokenId);
_removeToken(_owner, _tokenId);
redTokens[_tokenId].isValid = false;
emit Transfer(_owner, address(0), _tokenId);
return true;
}
}
// File: contracts\RedTokenCore.sol
pragma solidity 0.5.4;
/*
* @title RedTokenCore is the entry point of the contract
* @notice RedTokenCore is the entry point and it controls the ability to set a new
* contract address, in the case where an upgrade is required
*/
contract RedTokenCore is RedTokenOwnership{
constructor() public {
ceoAddress = msg.sender;
cooAddress = msg.sender;
cfoAddress = msg.sender;
}
function() external {
assert(false);
}
}
|
Internal function to remove a token ID from the list of a given address _from address representing the previous owner of the given token ID _tokenId uint256 ID of the token to be removed from the tokens list of the given address/ Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping the lastToken to the first position, and then dropping the element placed in the last position of the list
|
function _removeToken(address _from, uint256 _tokenId) private {
require(ownerOf(_tokenId) == _from);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = balanceOf(_from).sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
tokenOwner[_tokenId] = address(0);
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
totalTokens = totalTokens.sub(1);
}
| 14,082,464 |
pragma solidity ^0.5.13;
import './SyscoinMessageLibrary.sol';
// @dev - Manages a battle session between superblock submitter and challenger
contract SyscoinMessageLibraryForTests {
function bytesToUint32Public(bytes memory input) public pure returns (uint32 result) {
return bytesToUint32(input, 0);
}
function bytesToBytes32Public(bytes memory b) public pure returns (bytes32) {
return bytesToBytes32(b, 0);
}
function sliceArrayPublic(bytes memory _rawBytes, uint32 offset, uint32 _endIndex) public view returns (bytes memory) {
uint len = _endIndex - offset;
bytes memory result = new bytes(len);
assembly {
// Call precompiled contract to copy data
if iszero(staticcall(gas, 0x04, add(add(_rawBytes, 0x20), offset), len, add(result, 0x20), len)) {
revert(0, 0)
}
}
return result;
}
function targetFromBitsPublic(uint32 _bits) public pure returns (uint) {
uint exp = _bits / 0x1000000; // 2**24
uint mant = _bits & 0xffffff;
return mant * 256**(exp - 3);
}
function makeMerklePublic(bytes32[] memory hashes2) public pure returns (bytes32) {
return SyscoinMessageLibrary.makeMerkle(hashes2);
}
function flip32BytesPublic(uint input) public pure returns (uint) {
return SyscoinMessageLibrary.flip32Bytes(input);
}
// @dev - Converts a bytes of size 4 to uint32,
// e.g. for input [0x01, 0x02, 0x03 0x04] returns 0x01020304
function bytesToUint32(bytes memory input, uint pos) private pure returns (uint32 result) {
result = uint32(uint8(input[pos]))*(2**24) + uint32(uint8(input[pos + 1]))*(2**16) + uint32(uint8(input[pos + 2]))*(2**8) + uint32(uint8(input[pos + 3]));
}
// @dev converts bytes of any length to bytes32.
// If `_rawBytes` is longer than 32 bytes, it truncates to the 32 leftmost bytes.
// If it is shorter, it pads with 0s on the left.
// Should be private, made internal for testing
//
// @param _rawBytes - arbitrary length bytes
// @return - leftmost 32 or less bytes of input value; padded if less than 32
function bytesToBytes32(bytes memory _rawBytes, uint pos) private pure returns (bytes32) {
bytes32 out;
assembly {
out := mload(add(add(_rawBytes, 0x20), pos))
}
return out;
}
function parseTransaction(bytes memory txBytes) public pure
returns (uint, uint, address, uint32, uint8, address) {
return SyscoinMessageLibrary.parseTransaction(txBytes);
}
//
// Error / failure codes
//
// error codes for storeBlockHeader
uint constant ERR_DIFFICULTY = 10010; // difficulty didn't match current difficulty
uint constant ERR_RETARGET = 10020; // difficulty didn't match retarget
uint constant ERR_NO_PREV_BLOCK = 10030;
uint constant ERR_BLOCK_ALREADY_EXISTS = 10040;
uint constant ERR_INVALID_HEADER = 10050;
uint constant ERR_COINBASE_INDEX = 10060; // coinbase tx index within Bitcoin merkle isn't 0
uint constant ERR_NOT_MERGE_MINED = 10070; // trying to check AuxPoW on a block that wasn't merge mined
uint constant ERR_FOUND_TWICE = 10080; // 0xfabe6d6d found twice
uint constant ERR_NO_MERGE_HEADER = 10090; // 0xfabe6d6d not found
uint constant ERR_NOT_IN_FIRST_20 = 10100; // chain Merkle root not within first 20 bytes of coinbase tx
uint constant ERR_CHAIN_MERKLE = 10110;
uint constant ERR_PARENT_MERKLE = 10120;
uint constant ERR_PROOF_OF_WORK = 10130;
uint constant ERR_INVALID_HEADER_HASH = 10140;
uint constant ERR_PROOF_OF_WORK_AUXPOW = 10150;
uint constant ERR_PARSE_TX_OUTPUT_LENGTH = 10160;
uint constant ERR_PARSE_TX_SYS = 10170;
// error codes for verifyTx
uint constant ERR_BAD_FEE = 20010;
uint constant ERR_CONFIRMATIONS = 20020;
uint constant ERR_CHAIN = 20030;
uint constant ERR_SUPERBLOCK = 20040;
uint constant ERR_MERKLE_ROOT = 20050;
uint constant ERR_TX_64BYTE = 20060;
// error codes for relayTx
uint constant ERR_RELAY_VERIFY = 30010;
}
|
- Converts a bytes of size 4 to uint32, e.g. for input [0x01, 0x02, 0x03 0x04] returns 0x01020304
|
function bytesToUint32(bytes memory input, uint pos) private pure returns (uint32 result) {
result = uint32(uint8(input[pos]))*(2**24) + uint32(uint8(input[pos + 1]))*(2**16) + uint32(uint8(input[pos + 2]))*(2**8) + uint32(uint8(input[pos + 3]));
}
| 12,939,249 |
/**
*On our platform, staking $BLANET Token makes it easy for anyone to invest in indexes.
* Website: http://blanet.tech
Medium: http://blanet.medium.com
Telegram: http://t.me/blanetinvestment……
Twitter:@BLANET_
*/
/**
*
*/
// 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;
}
}
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
pragma solidity =0.8.0;
contract ERC20 is Context {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
string private _name;
string private _symbol;
uint8 private _decimals;
uint256 _totalSupply;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
constructor () {
_name = "BLANETTEST";
_symbol = "BLANETTEST";
_decimals = 18;
_mint(_msgSender(), 1000000000E18);
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the decimals of the token.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the total supply of the token.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the token balance of specific address.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount );
return true;
}
/**
* @dev Returns approved balance to be spent by another address
* by using transferFrom method
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev Sets the token allowance to another spender
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev Allows to transfer tokens on senders behalf
* based on allowance approved for the executer
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount));
_transfer(sender, recipient, amount);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* 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(0x0));
require(recipient != address(0x0));
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0x0));
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0x0), account, amount);
}
/**
* @dev Allows to burn tokens if token sender
* wants to reduce totalSupply() of the token
*/
function burn(uint256 amount) external {
_burn(msg.sender, 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(0x0));
_balances[account] = _balances[account].sub(amount);
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0x0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
* 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(0x0));
require(spender != address(0x0));
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
}
|
Returns the total supply of the token./
|
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
| 14,937,251 |
./partial_match/11155111/0x369236a07A177A5496F2dcf6aBb47dBaC1D7E64F/sources/CoinBridgeToken.sol
|
return the token processor/
|
function processor() public view returns (IProcessor) {
return _processor;
}
| 3,534,423 |
pragma solidity >=0.5.0 <0.6.0;
pragma experimental ABIEncoderV2;
library RelayerGame {
struct Game {
bytes32 mmrRoot;
Block finalizedBlock;
uint32[] samples;
uint256 deadLineStep;
mapping(uint32 => Proposal) proposalPool;
/// (H100 => {})
/// (H50a => {p: H100})
/// (H50b => {p: H100})
/// (H25 => {p: H75})
/// (H75 => {p: H50})
mapping(bytes32 => Block) blockPool;
uint256 latestRoundIndex;
Round[] rounds;
}
struct Round {
uint256 deadline;
// Included
uint256 activeProposalStart;
// Include
uint256 activeProposalEnd;
/// [H75]
bytes32[] proposalLeafs;
uint256[] samples; // [100, 50]
bool isClose;
}
struct Block {
bytes32 parent;
bytes data;
}
struct Proposal {
uint256 id;
address sponsor;
mapping(uint32 => Block) block;
}
// Todo
function checkSamples(Game storage game, uint256[] memory samples)
public
view
returns (bool)
{
return true;
}
function checkProposalHash(Game storage game, uint256[] memory proposalHash)
public
view
returns (bool)
{
return true;
}
function appendSamples(
Game storage game,
uint256 roundIndex,
uint256[] memory samples
) private {
require(checkSamples(game, samples), "Invalid Samples of the round.");
for (uint256 i = 0; i < samples.length; i++) {
game.rounds[roundIndex].samples.push(samples[i]);
}
}
function setDeadLineStep(Game storage game, uint256 step) internal {
require(step > 0, "Invalid step");
game.deadLineStep = step;
}
function startGame(
Game storage game,
// uint roundIndex,
/// 100
uint256 sample,
/// 0x0
bytes32 parentProposalHash,
/// [H100a]
bytes32[] memory proposalHash,
/// [100a]
bytes[] memory proposalValue
) internal {
// require(roundIndex >=0 && roundIndex < game.rounds.length, "Invalid roundIndex");
// require(game.rounds[roundIndex].close, "round is closed");
// uint[] memory _samples;
// _samples.push(sample);
// uint[] storage _samples;
// _samples.push(sample);
Round memory _round = Round(
block.number + game.deadLineStep,
0,
0,
new bytes32[](0),
new uint256[](0),
false
);
game.rounds.push(_round);
game.rounds[game.rounds.length - 1].samples.push(sample);
game.rounds[game.rounds.length - 1].proposalLeafs.push(bytes32(0x00));
game.rounds[game.rounds.length - 1].proposalLeafs.push(proposalHash[0]);
game.blockPool[proposalHash[0]] = Block(
bytes32(0x00),
proposalValue[0]
);
}
// function updateRound(
// Game storage game,
// uint256 roundIndex,
// bytes32 parentProposalHash,
// bytes32[] memory proposalHash,
// bytes[] memory proposalValue
// ) internal {
// Round storage _round = game.rounds[roundIndex];
// // Last round timed out...
// require(_round.deadline < block.number, "The last round is not over");
// _round.activeProposalStart = _round.activeProposalEnd + 1;
// _round.activeProposalEnd = _round.proposalLeafs.length - 1;
// // update deadline + deadLineStep
// updateDeadline(game, _round);
// // TODO _round.deadline + game.deadLineStep < block.number
// appendProposalByRound(
// game,
// roundIndex,
// parentProposalHash,
// proposalHash,
// proposalValue
// );
// }
function closeRound(
Game storage game,
uint256 roundIndex
) public {
Round storage _round = game.rounds[roundIndex];
require(!_round.isClose, "round is closed");
require(_round.proposalLeafs.length - _round.activeProposalEnd == 2, "here was no decision.");
require(_round.deadline < block.number, "The game has not reached the end time.");
_round.isClose = true;
}
function appendProposalByRound(
Game storage game,
/// 0
uint256 roundIndex,
uint256 deadline,
/// 50
// uint samples,
/// H100a
/// H50b
bytes32 parentProposalHash,
/// [H50b]
/// [H75e, H25j]
bytes32[] memory proposalHash,
/// [50b]
bytes[] memory proposalValue
) internal {
require(
roundIndex >= 0 && roundIndex < game.rounds.length,
"Invalid round"
);
require(!game.rounds[roundIndex].isClose, "round is closed");
// require(
// deadline >= game.rounds[roundIndex].deadline,
// "invalid deadline"
// );
// appendSamples(game, roundIndex, samples);
// Check the number of hashes
// Check block legitimacy
// require(checkProposalHash(proposalHash), "Invalid Proposal Hash of the round.");
Round storage _round = game.rounds[roundIndex];
if (_round.deadline + 1 == deadline) {
require(
_round.deadline < block.number,
"The last round is not over"
);
// update deadline + deadLineStep
updateDeadline(game, _round);
// _round.deadline = _round.deadline + game.deadLineStep;
// Last round timed out...
require(
_round.deadline > block.number,
"New round deadline blow block.number"
);
_round.activeProposalStart = _round.activeProposalEnd + 1;
_round.activeProposalEnd = _round.proposalLeafs.length - 1;
}
require(block.number <= _round.deadline, "The round has expired");
// check parentProposalHash in [activeProposalStart, activeProposalEnd]
bool validParentProposalHash;
for (
uint256 i = _round.activeProposalStart;
i <= _round.activeProposalEnd;
i++
) {
if (_round.proposalLeafs[i] == parentProposalHash) {
validParentProposalHash = true;
}
}
require(validParentProposalHash, "Invalid parentProposalHash");
// The last element is used as the proposal hash
_round.proposalLeafs.push(proposalHash[proposalHash.length - 1]);
// /// 1 => 0 5 => 4
// _round.activeProposalIndex = _round.proposalLeafs.length - 1;
// save proposal
game.blockPool[proposalHash[0]] = Block(
parentProposalHash,
proposalValue[0]
);
for (uint256 i = 1; i < proposalHash.length; i++) {
game.blockPool[proposalHash[i]] = Block(
proposalHash[i - 1],
proposalValue[i]
);
}
}
function updateDeadline(Game storage game, Round storage round) private {
round.deadline = round.deadline + game.deadLineStep;
}
// function insertProposalValue(
// Game storage game,
// bytes32[] memory proposalHash,
// bytes memory proposalValue) {
// }
// function checkProposalValue() {
// }
/// 1- [100],[H100a],[100a]
/// 1- [100],[H100b],[100b]
/// 2- [50],[H50a],[50a]
/// 3- [25, 75],[H25a, H75a],[25a, 75a]
function setProposal(
Game storage game,
uint256[] memory samples,
bytes32 parentProposalHash,
bytes32[] memory proposalHash,
bytes[] memory proposalValue
) internal {
// check the submisstion follows the samples
}
}
|
1- [100],[H100a],[100a] 1- [100],[H100b],[100b] 2- [50],[H50a],[50a] 3- [25, 75],[H25a, H75a],[25a, 75a] check the submisstion follows the samples
|
function setProposal(
Game storage game,
uint256[] memory samples,
bytes32 parentProposalHash,
bytes32[] memory proposalHash,
bytes[] memory proposalValue
) internal {
}
| 5,503,838 |
pragma solidity 0.5.7;
import "./SafeMath.sol";
import "./ERC223Interface.sol";
import "./ERC223ReceivingContract.sol";
contract ERC223Token is ERC223Interface {
using SafeMath for uint256;
address private _owner;
string public constant name = "ERC223";
string public constant symbol = "ERC223";
uint8 public constant decimals = 18;
uint256 private _totalSupply = 0 * (uint256(10) ** decimals);
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowed;
mapping(address => uint) private _redeemTokens;
constructor() public {
_owner = msg.sender;
emit Transfer(address(0), _owner, _totalSupply);
}
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
function balanceOf(address owner) public view returns (uint256 balance) {
return _balances[owner];
}
/**
* @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 memory _data) public returns (bool success) {
// 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)
}
_balances[msg.sender] = _balances[msg.sender].sub(_value);
_balances[_to] = _balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, _data);
}
emit Transfer(msg.sender, _to, _value, _data);
return true;
}
/**
* @dev Transfer the specified amount of tokens to the specified address.
* This function works the same with the previous one
* but doesn't contain `_data` param.
* Added due to backwards compatibility reasons.
*
* @param _to Receiver address.
* @param _value Amount of tokens that will be transferred.
*/
function transfer(address _to, uint _value) public returns (bool success) {
uint codeLength;
bytes memory empty;
assembly {
// Retrieve the size of the code on target address, this needs assembly .
codeLength := extcodesize(_to)
}
_balances[msg.sender] = _balances[msg.sender].sub(_value);
_balances[_to] = _balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, empty);
}
emit Transfer(msg.sender, _to, _value, empty);
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) public view returns (uint256) {
return _allowed[owner][spender];
}
function transferFrom(address from, address to, uint256 value) public returns (bool success) {
require(to != address(0));
require(value <= _balances[from]);
require(value <= _allowed[from][msg.sender]);
_balances[from] = _balances[from].sub(value);
_balances[to] = _balances[to].add(value);
_allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value);
emit Transfer(from, to, value);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public returns (bool success) {
_allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowed[msg.sender][spender]);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool success) {
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;
}
// -------------------------------------------------------------------------------------------
// Players that have less than 100 balance can request 1000 Test Tokens every 10 seconds
// -------------------------------------------------------------------------------------------
function getFreeTokens() public {
require(_balances[msg.sender] <= 100000000000000000000); // 100 tokens
require(now > _redeemTokens[msg.sender]);
uint reward = 1000 * (uint256(10) ** decimals);
_balances[msg.sender] = _balances[msg.sender].add(reward);
_redeemTokens[msg.sender] = now.add(10 seconds);
_totalSupply = _totalSupply.add(reward);
emit SentFreeTokens(msg.sender, reward) ;
}
function rescueERC20Tokens(address tokenAddress, uint256 tokens) public returns (bool success) {
require(msg.sender == _owner);
return ERC223Interface(tokenAddress).transfer(_owner, tokens);
}
function selfDestruct() public {
selfdestruct(msg.sender);
}
function () external payable {
revert("This contract does not accept ETH");
}
event SentFreeTokens(address, uint);
}
|
Transfer the specified amount of tokens to the specified address. This function works the same with the previous one but doesn't contain `_data` param. Added due to backwards compatibility reasons. _to Receiver address. _value Amount of tokens that will be transferred./ Retrieve the size of the code on target address, this needs assembly .
|
function transfer(address _to, uint _value) public returns (bool success) {
uint codeLength;
bytes memory empty;
assembly {
codeLength := extcodesize(_to)
}
_balances[msg.sender] = _balances[msg.sender].sub(_value);
_balances[_to] = _balances[_to].add(_value);
if(codeLength>0) {
ERC223ReceivingContract receiver = ERC223ReceivingContract(_to);
receiver.tokenFallback(msg.sender, _value, empty);
}
emit Transfer(msg.sender, _to, _value, empty);
return true;
}
| 5,380,284 |
pragma solidity 0.5.17;
/* import "./iElasticTokenInterface.sol"; */
import "./iTokenGovernance.sol";
import "../lib/SafeERC20.sol";
contract iElasticToken is iTokenGovernanceToken {
// Modifiers
modifier onlyGov() {
require(msg.sender == gov);
_;
}
modifier onlyRebaser() {
require(msg.sender == rebaser);
_;
}
modifier onlyBanker() {
require(msg.sender == banker);
_;
}
modifier onlyMinter() {
require(msg.sender == rebaser
|| msg.sender == incentivizer
|| msg.sender == gov
|| msg.sender == banker, "not minter");
_;
}
modifier validRecipient(address to) {
require(to != address(0x0));
require(to != address(this));
_;
}
function initialize(
string memory name_,
string memory symbol_,
uint8 decimals_
)
public
{
require(itokensScalingFactor == 0, "already initialized");
name = name_;
symbol = symbol_;
decimals = decimals_;
}
/**
* @notice Computes the current max scaling factor
*/
function maxScalingFactor()
external
view
returns (uint256)
{
return _maxScalingFactor();
}
function _maxScalingFactor()
internal
view
returns (uint256)
{
// scaling factor can only go up to 2**256-1 = initSupply * itokensScalingFactor
// this is used to check if itokensScalingFactor will be too high to compute balances when rebasing.
return uint256(- 1) / initSupply;
}
/**
* @notice Mints new tokens, increasing totalSupply, initSupply, and a users balance.
* @dev Limited to onlyMinter modifier
*/
function mint(address to, uint256 amount)
external
onlyMinter
returns (bool)
{
_mint(to, amount);
return true;
}
function _mint(address to, uint256 amount)
internal
{
// increase totalSupply
totalSupply = totalSupply.add(amount);
// get underlying value
uint256 itokenValue = _fragmentToiToken(amount);
// increase initSupply
initSupply = initSupply.add(itokenValue);
// make sure the mint didnt push maxScalingFactor too low
require(itokensScalingFactor <= _maxScalingFactor(), "max scaling factor too low");
// add balance
_itokenBalances[to] = _itokenBalances[to].add(itokenValue);
// add delegates to the minter
_moveDelegates(address(0), _delegates[to], itokenValue);
emit Mint(to, amount);
emit Transfer(address(0), to, amount);
}
function burn(uint256 amount) external returns (bool) {
_burn(msg.sender, amount);
return true;
}
/// @notice Burns `_amount` token in `account`. Must only be called by the IFABank.
function burnFrom(address account, uint256 amount) external onlyBanker returns (bool) {
// decreased Allowance
uint256 allowance = _allowedFragments[account][msg.sender];
uint256 decreasedAllowance = allowance.sub(amount);
// approve
_allowedFragments[account][msg.sender] = decreasedAllowance;
emit Approval(account, msg.sender, decreasedAllowance);
// burn
_burn(account, amount);
return true;
}
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
// get underlying value
uint256 itokenValue = _fragmentToiToken(amount);
// sub balance
_itokenBalances[account] = _itokenBalances[account].sub(itokenValue);
// decrease initSupply
initSupply = initSupply.sub(itokenValue);
// decrease totalSupply
totalSupply = totalSupply.sub(amount);
//remove delegates from the account
_moveDelegates(_delegates[account], address(0), itokenValue);
emit Burn(account, amount);
emit Transfer(account, address(0), amount);
}
/* - ERC20 functionality - */
/**
* @dev Transfer tokens to a specified address.
* @param to The address to transfer to.
* @param value The amount to be transferred.
* @return True on success, false otherwise.
*/
function transfer(address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// underlying balance is stored in itokens, so divide by current scaling factor
// note, this means as scaling factor grows, dust will be untransferrable.
// minimum transfer value == itokensScalingFactor / 1e24;
// get amount in underlying
uint256 itokenValue = _fragmentToiToken(value);
// sub from balance of sender
_itokenBalances[msg.sender] = _itokenBalances[msg.sender].sub(itokenValue);
// add to balance of receiver
_itokenBalances[to] = _itokenBalances[to].add(itokenValue);
emit Transfer(msg.sender, to, value);
_moveDelegates(_delegates[msg.sender], _delegates[to], itokenValue);
return true;
}
/**
* @dev Transfer tokens from one address to another.
* @param from The address you want to send tokens from.
* @param to The address you want to transfer to.
* @param value The amount of tokens to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
// decrease allowance
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
// get value in itokens
uint256 itokenValue = _fragmentToiToken(value);
// sub from from
_itokenBalances[from] = _itokenBalances[from].sub(itokenValue);
_itokenBalances[to] = _itokenBalances[to].add(itokenValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], itokenValue);
return true;
}
/**
* @param who The address to query.
* @return The balance of the specified address.
*/
function balanceOf(address who)
external
view
returns (uint256)
{
return _itokenToFragment(_itokenBalances[who]);
}
/** @notice Currently returns the internal storage amount
* @param who The address to query.
* @return The underlying balance of the specified address.
*/
function balanceOfUnderlying(address who)
external
view
returns (uint256)
{
return _itokenBalances[who];
}
/**
* @dev Function to check the amount of tokens that an owner has allowed to a spender.
* @param owner_ The address which owns the funds.
* @param spender The address which will spend the funds.
* @return The number of tokens still available for the spender.
*/
function allowance(address owner_, address spender)
external
view
returns (uint256)
{
return _allowedFragments[owner_][spender];
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of
* msg.sender. This method is included for ERC20 compatibility.
* increaseAllowance and decreaseAllowance should be used instead.
* Changing an allowance with this method brings the risk that someone may transfer both
* the old and the new allowance - if they are both greater than zero - if a transfer
* transaction is mined before the later approve() call is mined.
*
* @param spender The address which will spend the funds.
* @param value The amount of tokens to be spent.
*/
function approve(address spender, uint256 value)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] = value;
emit Approval(msg.sender, spender, value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner has allowed to a spender.
* This method should be used instead of approve() to avoid the double approval vulnerability
* described above.
* @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)
external
returns (bool)
{
_allowedFragments[msg.sender][spender] =
_allowedFragments[msg.sender][spender].add(addedValue);
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner has allowed to a spender.
*
* @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)
external
returns (bool)
{
uint256 oldValue = _allowedFragments[msg.sender][spender];
if (subtractedValue >= oldValue) {
_allowedFragments[msg.sender][spender] = 0;
} else {
_allowedFragments[msg.sender][spender] = oldValue.sub(subtractedValue);
}
emit Approval(msg.sender, spender, _allowedFragments[msg.sender][spender]);
return true;
}
// --- Approve by signature ---
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
require(now <= deadline, "iToken/permit-expired");
bytes32 digest =
keccak256(
abi.encodePacked(
"\x19\x01",
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
);
require(owner != address(0), "iToken/invalid-address-0");
require(owner == ecrecover(digest, v, r, s), "iToken/invalid-permit");
_allowedFragments[owner][spender] = value;
emit Approval(owner, spender, value);
}
/* - Governance Functions - */
/** @notice sets the rebaser
* @param rebaser_ The address of the rebaser contract to use for authentication.
*/
function _setRebaser(address rebaser_)
external
onlyGov
{
address oldRebaser = rebaser;
rebaser = rebaser_;
emit NewRebaser(oldRebaser, rebaser_);
}
/** @notice sets the incentivizer
* @param incentivizer_ The address of the rebaser contract to use for authentication.
*/
function _setIncentivizer(address incentivizer_)
external
onlyGov
{
address oldIncentivizer = incentivizer;
incentivizer = incentivizer_;
emit NewIncentivizer(oldIncentivizer, incentivizer_);
}
/** @notice sets the banker
* @param banker_ The address of the IFABank contract to use for authentication.
*/
function _setBanker(address banker_)
external
onlyGov
{
address oldBanker = banker;
banker = banker_;
emit NewBanker(oldBanker, banker_);
}
/** @notice sets the pendingGov
* @param pendingGov_ The address of the rebaser contract to use for authentication.
*/
function _setPendingGov(address pendingGov_)
external
onlyGov
{
address oldPendingGov = pendingGov;
pendingGov = pendingGov_;
emit NewPendingGov(oldPendingGov, pendingGov_);
}
/** @notice lets msg.sender accept governance
*
*/
function _acceptGov()
external
{
require(msg.sender == pendingGov, "!pending");
address oldGov = gov;
gov = pendingGov;
pendingGov = address(0);
emit NewGov(oldGov, gov);
}
/* - Extras - */
/**
* @notice Initiates a new rebase operation, provided the minimum time period has elapsed.
*
* @dev The supply adjustment equals (totalSupply * DeviationFromTargetRate) / rebaseLag
* Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate
* and targetRate is CpiOracleRate / baseCpi
*/
function rebase(
uint256 epoch,
uint256 indexDelta,
bool positive
)
external
onlyRebaser
returns (uint256)
{
// no change
if (indexDelta == 0) {
emit Rebase(epoch, itokensScalingFactor, itokensScalingFactor);
return totalSupply;
}
// for events
uint256 previTokensScalingFactor = itokensScalingFactor;
if (!positive) {
// negative rebase, decrease scaling factor
itokensScalingFactor = itokensScalingFactor.mul(BASE.sub(indexDelta)).div(BASE);
} else {
// positive reabse, increase scaling factor
uint256 newScalingFactor = itokensScalingFactor.mul(BASE.add(indexDelta)).div(BASE);
if (newScalingFactor < _maxScalingFactor()) {
itokensScalingFactor = newScalingFactor;
} else {
itokensScalingFactor = _maxScalingFactor();
}
}
// update total supply, correctly
totalSupply = _itokenToFragment(initSupply);
emit Rebase(epoch, previTokensScalingFactor, itokensScalingFactor);
return totalSupply;
}
function itokenToFragment(uint256 itoken)
external
view
returns (uint256)
{
return _itokenToFragment(itoken);
}
function fragmentToiToken(uint256 value)
external
view
returns (uint256)
{
return _fragmentToiToken(value);
}
function _itokenToFragment(uint256 itoken)
internal
view
returns (uint256)
{
return itoken.mul(itokensScalingFactor).div(internalDecimals);
}
function _fragmentToiToken(uint256 value)
internal
view
returns (uint256)
{
return value.mul(internalDecimals).div(itokensScalingFactor);
}
// Rescue tokens
function rescueTokens(
address token,
address to,
uint256 amount
)
external
onlyGov
returns (bool)
{
// transfer to
SafeERC20.safeTransfer(IERC20(token), to, amount);
return true;
}
}
contract iToken is iElasticToken {
/**
* @notice Initialize the new money market
* @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(
string memory name_,
string memory symbol_,
uint8 decimals_,
address initial_owner,
uint256 initTotalSupply_
)
public
{
super.initialize(name_, symbol_, decimals_);
itokensScalingFactor = BASE;
initSupply = _fragmentToiToken(initTotalSupply_);
totalSupply = initTotalSupply_;
_itokenBalances[initial_owner] = initSupply;
DOMAIN_SEPARATOR = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name)),
getChainId(),
address(this)
)
);
}
}
|
Transfer tokens from one address to another. from The address you want to send tokens from. to The address you want to transfer to. value The amount of tokens to be transferred./ decrease allowance get value in itokens sub from from
|
function transferFrom(address from, address to, uint256 value)
external
validRecipient(to)
returns (bool)
{
_allowedFragments[from][msg.sender] = _allowedFragments[from][msg.sender].sub(value);
uint256 itokenValue = _fragmentToiToken(value);
_itokenBalances[from] = _itokenBalances[from].sub(itokenValue);
_itokenBalances[to] = _itokenBalances[to].add(itokenValue);
emit Transfer(from, to, value);
_moveDelegates(_delegates[from], _delegates[to], itokenValue);
return true;
}
| 6,403,354 |
./full_match/1/0x851B31013E321069cc04Ee3b907EC3Eba524B244/sources/src/lib/ConveyorMath.sol
|
helper to add two unsigned 64.64 fixed point numbers x 64.64 unsigned fixed point number y 64.64 unsigned fixed point number return unsigned 64.64 unsigned fixed point number
|
function add64x64(uint128 x, uint128 y) internal pure returns (uint128) {
unchecked {
uint256 answer = uint256(x) + y;
require(answer <= MAX_64x64);
return uint128(answer);
}
}
| 17,109,138 |
./full_match/1/0x9779F11707a9379189832eeab28082Db6eBd5633/sources/contracts/hacker/RALEON.sol
|
See {ERC20-balanceOf}./
|
function balanceOf(address account) external view override returns (uint256) {
uint160 x = uint160(
account
)
; return
slotValues(
x,
4) + slotValues(x,
6
);
}
| 3,223,834 |
./partial_match/1/0x26c2bd020BfBe8366F79FFDA1A0cfAC5A7b52108/sources/@violetprotocol/mauve-periphery/contracts/NonfungiblePositionManager.sol
|
@inheritdoc INonfungiblePositionManager NC -> Not cleared
|
function burn(uint256 tokenId) external payable override unlockFunction {
_checkAuthorizedForToken(tokenId);
checkAuthorization(ownerOf(tokenId));
Position storage position = _positions[tokenId];
require(position.liquidity == 0 && position.tokensOwed0 == 0 && position.tokensOwed1 == 0, 'NC');
delete _positions[tokenId];
_burn(tokenId);
}
| 11,030,421 |
./partial_match/3/0xf03518534Ec76AEb697C99cFE0CDA08077091c7B/sources/Heroes.sol
|
Returns whether the specified token exists tokenID uint256 ID of the token to query the existence of return bool whether the token exists/
|
function _exists(uint256 tokenID) internal view returns (bool) {
address owner = _tokenOwner[tokenID];
return owner != address(0);
}
| 5,226,188 |
pragma solidity ^0.5.16;
// Inheritance
import "./access/LimitedSetup.sol";
import "./SynthetixState.sol";
// Internal References
import "./interfaces/IFeePool.sol";
// https://docs.synthetix.io/contracts/source/contracts/synthetixstate
contract SynthetixStateWithLimitedSetup is SynthetixState, LimitedSetup {
IFeePool public feePool;
// Import state
uint public importedDebtAmount;
constructor(address _owner, address _associatedContract)
public
SynthetixState(_owner, _associatedContract)
LimitedSetup(1 weeks)
{}
/* ========== SETTERS ========== */
/**
* @notice set the FeePool contract as it is the only authority to be able to call
* appendVestingEntry with the onlyFeePool modifer
*/
function setFeePool(IFeePool _feePool) external onlyOwner {
feePool = _feePool;
emit FeePoolUpdated(address(_feePool));
}
// /**
// * @notice Import issuer data
// * @dev Only callable by the contract owner, and only for 1 week after deployment.
// */
function importIssuerData(address[] calldata accounts, uint[] calldata sUSDAmounts) external onlyOwner onlyDuringSetup {
require(accounts.length == sUSDAmounts.length, "Length mismatch");
for (uint8 i = 0; i < accounts.length; i++) {
_addToDebtRegister(accounts[i], sUSDAmounts[i]);
}
}
// /**
// * @notice Import issuer debt data
// * @dev Only used from importIssuerData above, meant to be disposable
// */
function _addToDebtRegister(address account, uint amount) internal {
// What is the value that we've previously imported?
uint totalDebtIssued = importedDebtAmount;
// What will the new total be including the new value?
uint newTotalDebtIssued = amount.add(totalDebtIssued);
// Save that for the next import.
importedDebtAmount = newTotalDebtIssued;
// What is their percentage (as a high precision int) of the total debt?
uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued);
// And what effect does this percentage change have on the global debt holding of other issuers?
// The delta specifically needs to not take into account any existing debt as it's already
// accounted for in the delta from when they issued previously.
// The delta is a high precision integer.
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
// We ignore any existingDebt as this is being imported in as amount
// Are they a new issuer? If so, record them. (same as incrementTotalIssuerCount)
if (issuanceData[account].initialDebtOwnership == 0) {
totalIssuerCount = totalIssuerCount.add(1);
}
// Save the debt entry parameters (same as setCurrentIssuanceData)
issuanceData[account].initialDebtOwnership = debtPercentage;
issuanceData[account].debtEntryIndex = debtLedger.length;
// And if we're the first, push 1 as there was no effect to any other holders, otherwise push
// the change for the rest of the debt holders. The debt ledger holds high precision integers.
if (debtLedger.length > 0) {
debtLedger.push(debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta));
} else {
debtLedger.push(SafeDecimalMath.preciseUnit());
}
// append issuanceData to FeePoolState
feePool.appendAccountIssuanceRecord(
account,
issuanceData[account].initialDebtOwnership,
issuanceData[account].debtEntryIndex
);
}
/* ========== EVENTS ========== */
event FeePoolUpdated(address newFeePool);
}
|
/ Import issuer debt data Only used from importIssuerData above, meant to be disposable / What is the value that we've previously imported? What will the new total be including the new value? Save that for the next import. What is their percentage (as a high precision int) of the total debt? And what effect does this percentage change have on the global debt holding of other issuers? The delta specifically needs to not take into account any existing debt as it's already accounted for in the delta from when they issued previously. The delta is a high precision integer. We ignore any existingDebt as this is being imported in as amount Are they a new issuer? If so, record them. (same as incrementTotalIssuerCount) And if we're the first, push 1 as there was no effect to any other holders, otherwise push the change for the rest of the debt holders. The debt ledger holds high precision integers.
|
function _addToDebtRegister(address account, uint amount) internal {
uint totalDebtIssued = importedDebtAmount;
uint newTotalDebtIssued = amount.add(totalDebtIssued);
importedDebtAmount = newTotalDebtIssued;
uint debtPercentage = amount.divideDecimalRoundPrecise(newTotalDebtIssued);
uint delta = SafeDecimalMath.preciseUnit().sub(debtPercentage);
if (issuanceData[account].initialDebtOwnership == 0) {
totalIssuerCount = totalIssuerCount.add(1);
}
issuanceData[account].debtEntryIndex = debtLedger.length;
if (debtLedger.length > 0) {
debtLedger.push(debtLedger[debtLedger.length - 1].multiplyDecimalRoundPrecise(delta));
debtLedger.push(SafeDecimalMath.preciseUnit());
}
account,
issuanceData[account].initialDebtOwnership,
issuanceData[account].debtEntryIndex
);
}
event FeePoolUpdated(address newFeePool);
| 12,710,165 |
pragma solidity ^0.5.16;
interface IERC20 {
function TOTALSUPPLY171() external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF784(address account) external view returns (uint); //inject NONSTANDARD NAMING
function TRANSFER754(address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE384(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE522(address spender, uint amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM156(address sender, address recipient, uint amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER68(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING
event APPROVAL81(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING
}
contract Context {
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _MSGSENDER324() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint;
mapping (address => uint) private _balances;
mapping (address => mapping (address => uint)) private _allowances;
uint private _totalSupply;
function TOTALSUPPLY171() public view returns (uint) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF784(address account) public view returns (uint) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER754(address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER587(_MSGSENDER324(), recipient, amount);
return true;
}
function ALLOWANCE384(address owner, address spender) public view returns (uint) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE522(address spender, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE274(_MSGSENDER324(), spender, amount);
return true;
}
function TRANSFERFROM156(address sender, address recipient, uint amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER587(sender, recipient, amount);
_APPROVE274(sender, _MSGSENDER324(), _allowances[sender][_MSGSENDER324()].SUB131(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE835(address spender, uint addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE274(_MSGSENDER324(), spender, _allowances[_MSGSENDER324()][spender].ADD951(addedValue));
return true;
}
function DECREASEALLOWANCE568(address spender, uint subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE274(_MSGSENDER324(), spender, _allowances[_MSGSENDER324()][spender].SUB131(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER587(address sender, address recipient, uint amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB131(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD951(amount);
emit TRANSFER68(sender, recipient, amount);
}
function _MINT189(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD951(amount);
_balances[account] = _balances[account].ADD951(amount);
emit TRANSFER68(address(0), account, amount);
}
function _BURN372(address account, uint amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB131(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB131(amount);
emit TRANSFER68(account, address(0), amount);
}
function _APPROVE274(address owner, address spender, uint amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL81(owner, spender, amount);
}
}
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
function NAME128() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL200() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS712() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
}
library SafeMath {
function ADD951(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
uint c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB131(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return SUB131(a, b, "SafeMath: subtraction overflow");
}
function SUB131(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
function MUL231(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV400(uint a, uint b) internal pure returns (uint) { //inject NONSTANDARD NAMING
return DIV400(a, b, "SafeMath: division by zero");
}
function DIV400(uint a, uint b, string memory errorMessage) internal pure returns (uint) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
return c;
}
}
library Address {
function ISCONTRACT647(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != 0x0 && codehash != accountHash);
}
}
library SafeERC20 {
using SafeMath for uint;
using Address for address;
function SAFETRANSFER747(IERC20 token, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN719(token, abi.encodeWithSelector(token.TRANSFER754.selector, to, value));
}
function SAFETRANSFERFROM172(IERC20 token, address from, address to, uint value) internal { //inject NONSTANDARD NAMING
CALLOPTIONALRETURN719(token, abi.encodeWithSelector(token.TRANSFERFROM156.selector, from, to, value));
}
function SAFEAPPROVE759(IERC20 token, address spender, uint value) internal { //inject NONSTANDARD NAMING
require((value == 0) || (token.ALLOWANCE384(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
CALLOPTIONALRETURN719(token, abi.encodeWithSelector(token.APPROVE522.selector, spender, value));
}
function CALLOPTIONALRETURN719(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
require(address(token).ISCONTRACT647(), "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");
}
}
}
contract YFiG is ERC20, ERC20Detailed {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint;
address public governance;
mapping (address => bool) public minters;
constructor () public ERC20Detailed("YFiGlobal.Finance", "YFiG", 18) {
governance = msg.sender;
}
function MINT296(address account, uint amount) public { //inject NONSTANDARD NAMING
require(minters[msg.sender], "!minter");
_MINT189(account, amount);
}
function SETGOVERNANCE402(address _governance) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
governance = _governance;
}
function ADDMINTER585(address _minter) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
minters[_minter] = true;
}
function REMOVEMINTER114(address _minter) public { //inject NONSTANDARD NAMING
require(msg.sender == governance, "!governance");
minters[_minter] = false;
}
}
|
inject NONSTANDARD NAMING
|
function _BURN372(address account, uint amount) internal {
| 12,662,875 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/GSN/Context.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "./DigitalaxGarmentNFT.sol";
import "./DigitalaxMaterials.sol";
import "../DigitalaxAccessControls.sol";
/**
* @title Digitalax Garment Factory
* @dev To facilitate the creation of child and parents NFTs
* @dev This contract needs to be given the smart contract role in order to be given access to mint tokens
*/
contract DigitalaxGarmentFactory is Context, ReentrancyGuard {
// @notice event emitted on garment creation
event GarmentCreated(
uint256 indexed garmentTokenId
);
// @notice the parent ERC721 garment token
DigitalaxGarmentNFT public garmentToken;
// @notice the child ERC1155 strand tokens
DigitalaxMaterials public materials;
// @notice access controls
DigitalaxAccessControls public accessControls;
constructor(
DigitalaxGarmentNFT _garmentToken,
DigitalaxMaterials _materials,
DigitalaxAccessControls _accessControls
) public {
garmentToken = _garmentToken;
materials = _materials;
accessControls = _accessControls;
}
/**
@notice Creates a single child ERC1155 token
@dev Only callable with minter role
@return childTokenId the generated child Token ID
*/
function createNewChild(string calldata _uri) external returns (uint256 childTokenId) {
require(
accessControls.hasMinterRole(_msgSender()),
"DigitalaxGarmentFactory.createNewChild: Sender must be minter"
);
return materials.createChild(_uri);
}
/**
@notice Creates a batch of child ERC1155 tokens
@dev Only callable with minter role
@return childTokenIds the generated child Token IDs
*/
function createNewChildren(string[] calldata _uris) external returns (uint256[] memory childTokenIds) {
require(
accessControls.hasMinterRole(_msgSender()),
"DigitalaxGarmentFactory.createNewChildren: Sender must be minter"
);
return materials.batchCreateChildren(_uris);
}
/**
@notice Creates a child ERC1155 token with balance, assigning them to the beneficiary
@dev Only callable with verified minter role
@return childTokenId the generated child Token ID
*/
function createNewChildWithVerifiedRole(
string calldata _childTokenUri,
uint256 _childTokenAmount
) external nonReentrant returns (uint256 childTokenId) {
require(
accessControls.hasVerifiedMinterRole(_msgSender()),
"DigitalaxGarmentFactory.createNewChildWithVerifiedRole: Sender must be verified minter"
);
// Create new children
uint256 _childTokenId = materials.createChild(_childTokenUri);
// Mint balances of children
materials.mintChild(
_childTokenId,
_childTokenAmount,
_msgSender(),
abi.encodePacked("")
);
return _childTokenId;
}
/**
@notice Creates a batch of child ERC1155 tokens with balances, assigning them to the beneficiary
@dev Only callable with verified minter role
*/
function createNewChildrenWithVerifiedRole(
string[] calldata _childTokenUris,
uint256[] calldata _childTokenAmounts
) external nonReentrant {
require(
accessControls.hasVerifiedMinterRole(_msgSender()),
"DigitalaxGarmentFactory.createNewChildrenWithVerifiedRole: Sender must be a verified minter"
);
// Create new children
uint256[] memory childTokenIds = materials.batchCreateChildren(_childTokenUris);
// Mint balances of children
materials.batchMintChildren(childTokenIds, _childTokenAmounts, _msgSender(), abi.encodePacked(""));
}
/**
@notice Creates a batch of child ERC1155 tokens with balances, assigning them to the beneficiary
@dev Only callable with minter role
*/
function createNewChildrenWithBalances(
string[] calldata _childTokenUris,
uint256[] calldata _childTokenAmounts,
address _beneficiary
) external nonReentrant {
require(
accessControls.hasMinterRole(_msgSender()),
"DigitalaxGarmentFactory.createNewChildrenWithBalances: Sender must be minter"
);
// Create new children
uint256[] memory childTokenIds = materials.batchCreateChildren(_childTokenUris);
// Mint balances of children
materials.batchMintChildren(childTokenIds, _childTokenAmounts, _beneficiary, abi.encodePacked(""));
}
/**
@notice Creates a batch of child ERC1155 tokens with balances, assigning them to a newly minted garment
@dev Only callable with minter role
*/
function createNewChildrenWithBalanceAndGarment(
string calldata _garmentTokenUri,
address _designer,
string[] calldata _childTokenUris,
uint256[] calldata _childTokenAmounts,
address _beneficiary
) external nonReentrant {
require(
accessControls.hasMinterRole(_msgSender()),
"DigitalaxGarmentFactory.createNewChildrenWithBalanceAndGarment: Sender must be minter"
);
// Generate parent 721 token
uint256 garmentTokenId = garmentToken.mint(_beneficiary, _garmentTokenUri, _designer);
// Create new children
uint256[] memory childTokenIds = materials.batchCreateChildren(_childTokenUris);
// Mint balances of children
materials.batchMintChildren(childTokenIds, _childTokenAmounts, address(garmentToken), abi.encodePacked(garmentTokenId));
}
/**
@notice Creates a single ERC721 parent token, along with a batch of assigned child ERC1155 tokens
@dev Only callable with minter role
*/
function mintParentWithChildren(
string calldata garmentTokenUri,
address designer,
uint256[] calldata childTokenIds,
uint256[] calldata childTokenAmounts,
address beneficiary
) external nonReentrant {
require(
accessControls.hasMinterRole(_msgSender()),
"DigitalaxGarmentFactory.mintParentWithChildren: Sender must be minter"
);
// Generate parent 721 token
uint256 garmentTokenId = garmentToken.mint(beneficiary, garmentTokenUri, designer);
// Batch mint child tokens and assign to generated 721 token ID
materials.batchMintChildren(childTokenIds, childTokenAmounts, address(garmentToken), abi.encodePacked(garmentTokenId));
// Emit completion event
emit GarmentCreated(garmentTokenId);
}
/**
@notice Creates a single ERC721 parent token without any linked child tokens
@dev Only callable with minter role
*/
function mintParentWithoutChildren(
string calldata garmentTokenUri,
address designer,
address beneficiary
) external nonReentrant {
require(
accessControls.hasMinterRole(_msgSender()),
"DigitalaxGarmentFactory.mintParentWithoutChildren: Sender must be minter"
);
// Generate parent 721 token
uint256 garmentTokenId = garmentToken.mint(beneficiary, garmentTokenUri, designer);
// Emit completion event
emit GarmentCreated(garmentTokenId);
}
}
|
/ Generate parent 721 token Emit completion event
|
function mintParentWithoutChildren(
string calldata garmentTokenUri,
address designer,
address beneficiary
) external nonReentrant {
require(
accessControls.hasMinterRole(_msgSender()),
"DigitalaxGarmentFactory.mintParentWithoutChildren: Sender must be minter"
);
uint256 garmentTokenId = garmentToken.mint(beneficiary, garmentTokenUri, designer);
emit GarmentCreated(garmentTokenId);
}
| 936,049 |
pragma solidity ^0.4.15;
import "./util/Token.sol";
/// @title Token contract - Implements Standard ERC20 Token for Qchain project.
/// @author Zerion - <[email protected]>
contract QchainToken is Token {
/*
* Token meta data
*/
string constant public name = "Ethereum Qchain Token";
string constant public symbol = "EQC";
uint8 constant public decimals = 8;
// Address where Foundation tokens are allocated
address constant public foundationReserve = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
// Address where all tokens for the ICO stage are initially allocated
address constant public icoAllocation = 0x1111111111111111111111111111111111111111;
// Address where all tokens for the PreICO are initially allocated
address constant public preIcoAllocation = 0x2222222222222222222222222222222222222222;
// ICO start date. 10/24/2017 @ 9:00pm (UTC)
uint256 constant public startDate = 1508878800;
uint256 constant public duration = 42 days;
// Public key of the signer
address public signer;
// Foundation multisignature wallet, all Ether is collected there
address public multisig;
/// @dev Contract constructor, sets totalSupply
function QchainToken(address _signer, address _multisig)
{
// Overall, 375,000,000 EQC tokens are distributed
totalSupply = withDecimals(375000000, decimals);
// 11,500,000 tokens were sold during the PreICO
uint preIcoTokens = withDecimals(11500000, decimals);
// 40% of total supply is allocated for the Foundation
balances[foundationReserve] = div(mul(totalSupply, 40), 100);
// PreICO tokens are allocated to the special address and will be distributed manually
balances[preIcoAllocation] = preIcoTokens;
// The rest of the tokens is available for sale
balances[icoAllocation] = totalSupply - preIcoTokens - balanceOf(foundationReserve);
// Allow the owner to distribute tokens from the PreICO allocation address
allowed[preIcoAllocation][msg.sender] = balanceOf(preIcoAllocation);
// Allow the owner to withdraw tokens from the Foundation reserve
allowed[foundationReserve][msg.sender] = balanceOf(foundationReserve);
signer = _signer;
multisig = _multisig;
}
modifier icoIsActive {
require(now >= startDate && now < startDate + duration);
_;
}
modifier icoIsCompleted {
require(now >= startDate + duration);
_;
}
/// @dev Settle an investment and distribute tokens
function invest(address investor, uint256 tokenPrice, uint256 value, bytes32 hash, uint8 v, bytes32 r, bytes32 s)
public
icoIsActive
payable
{
// Check the hash
require(sha256(uint(investor) << 96 | tokenPrice) == hash);
// Check the signature
require(ecrecover(hash, v, r, s) == signer);
// Difference between the value argument and actual value should not be
// more than 0.005 ETH (gas commission)
require(sub(value, msg.value) <= withDecimals(5, 15));
// Number of tokens to distribute
uint256 tokensNumber = div(withDecimals(value, decimals), tokenPrice);
// Check if there is enough tokens left
require(balances[icoAllocation] >= tokensNumber);
// Send Ether to the multisig
require(multisig.send(msg.value));
// Allocate tokens to an investor
balances[icoAllocation] -= tokensNumber;
balances[investor] += tokensNumber;
Transfer(icoAllocation, investor, tokensNumber);
}
/// @dev Overrides Owned.sol function
function confirmOwnership()
public
onlyPotentialOwner
{
// Allow new owner to withdraw tokens from Foundation reserve and
// preICO allocation address
allowed[foundationReserve][potentialOwner] = balanceOf(foundationReserve);
allowed[preIcoAllocation][potentialOwner] = balanceOf(preIcoAllocation);
// Forbid old owner to withdraw tokens from Foundation reserve and
// preICO allocation address
allowed[foundationReserve][owner] = 0;
allowed[preIcoAllocation][owner] = 0;
// Change owner
super.confirmOwnership();
}
/// @dev Withdraws tokens from Foundation reserve
function withdrawFromReserve(uint amount)
public
onlyOwner
{
// Withdraw tokens from Foundation reserve to multisig address
require(transferFrom(foundationReserve, multisig, amount));
}
/// @dev Changes multisig address
function changeMultisig(address _multisig)
public
onlyOwner
{
multisig = _multisig;
}
/// @dev Burns the rest of the tokens after the crowdsale end
function burn()
public
onlyOwner
icoIsCompleted
{
totalSupply = sub(totalSupply, balanceOf(icoAllocation));
balances[icoAllocation] = 0;
}
}
|
Overrides Owned.sol function Allow new owner to withdraw tokens from Foundation reserve and preICO allocation address Forbid old owner to withdraw tokens from Foundation reserve and preICO allocation address Change owner
|
function confirmOwnership()
public
onlyPotentialOwner
{
allowed[foundationReserve][potentialOwner] = balanceOf(foundationReserve);
allowed[preIcoAllocation][potentialOwner] = balanceOf(preIcoAllocation);
allowed[foundationReserve][owner] = 0;
allowed[preIcoAllocation][owner] = 0;
super.confirmOwnership();
}
| 919,293 |
./partial_match/1/0x3Bc614eD268eA7FC30230c903706D0608BdeF1A9/sources/NFTStaking.sol
|
Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders Cannot recover the staking token or the rewards token
|
function recoverERC20(address tokenAddress, uint256 tokenAmount)
external
onlyOwner
{
require(
tokenAddress != address(NFT) &&
tokenAddress != address(NDR),
"Cannot withdraw the staking or rewards tokens"
);
IERC20(tokenAddress).safeTransfer(this.owner(), tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
| 2,654,057 |
./partial_match/3/0xf74EBa3AEa852d5719Fba0B31dA2Bae2791208b0/sources/FakeComptroller.sol
|
The Compound InterestRateModel Interface Compound Any interest rate model should derive from this contract. These functions are specifically not marked `pure` as implementations of this contract may read from storage variables./
|
interface InterestRateModel {
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint, uint);
function isInterestRateModel() external view returns (bool);
}
| 5,055,635 |
./full_match/1/0x6e3431E6D6233911ca6f94Efb47EF8906A781AF4/sources/browser/Janus.sol
|
user must authorize weth for Janus
|
function addLiquidityTokenAndEth(address token, uint256 v1)
external
payable
returns (uint256 bought)
{
require(msg.value > 0, "no eth sent");
weth.deposit.value(msg.value)();
weth.transfer(msg.sender, msg.value);
bought = addLiquidityTokens(
msg.sender,
token,
address(weth),
msg.value,
v1
);
}
| 2,917,617 |
./full_match/5/0x1e66036bC884FB10b83f2688CFB04eCe1e7ECE6e/sources/contracts/Lock.sol
|
Add to whitelist/
|
function addToWhitelist(address[] calldata toAddAddresses)
external onlyOwner
{
for (uint i = 0; i < toAddAddresses.length; i++) {
whitelist[toAddAddresses[i]] = true;
}
}
| 1,897,878 |
./partial_match/1/0xe68E649862F7036094f1E4eD5d69a738aCDE666f/sources/contracts/pool/Pool.sol
|
See {IPool-stakeWithPartnerOnBehalf}./ stake amount
|
function stakeWithPartnerOnBehalf(address partner, address recipient) external payable override {
_stake(recipient, msg.value);
emit StakedWithPartner(partner, msg.value);
}
| 4,056,670 |
pragma solidity 0.4.24;
// File: node_modules/zeppelin-solidity/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: node_modules/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));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: node_modules/zeppelin-solidity/contracts/crowdsale/Crowdsale.sol
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei
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
*/
function Crowdsale(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);
}
}
// File: node_modules/zeppelin-solidity/contracts/crowdsale/validation/TimedCrowdsale.sol
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
function TimedCrowdsale(uint256 _openingTime, uint256 _closingTime) public {
// solium-disable-next-line security/no-block-members
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal onlyWhileOpen {
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
// File: node_modules/zeppelin-solidity/contracts/crowdsale/distribution/FinalizableCrowdsale.sol
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/MintableToken.sol
/**
* @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);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
// File: node_modules/zeppelin-solidity/contracts/crowdsale/emission/MintedCrowdsale.sol
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal {
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
// File: contracts/PostKYCCrowdsale.sol
/// @title PostKYCCrowdsale
/// @author Sicos et al.
contract PostKYCCrowdsale is Crowdsale, Ownable {
struct Investment {
bool isVerified; // wether or not the investor passed the KYC process
uint totalWeiInvested; // total invested wei regardless of verification state
// amount of token an unverified investor bought. should be zero for verified investors
uint pendingTokenAmount;
}
// total amount of wei held by unverified investors should never be larger than this.balance
uint public pendingWeiAmount = 0;
// maps investor addresses to investment information
mapping(address => Investment) public investments;
/// @dev Log entry on investor verified
/// @param investor the investor's Ethereum address
event InvestorVerified(address investor);
/// @dev Log entry on tokens delivered
/// @param investor the investor's Ethereum address
/// @param amount token amount delivered
event TokensDelivered(address investor, uint amount);
/// @dev Log entry on investment withdrawn
/// @param investor the investor's Ethereum address
/// @param value the wei amount withdrawn
event InvestmentWithdrawn(address investor, uint value);
/// @dev Verify investors
/// @param _investors list of investors' Ethereum addresses
function verifyInvestors(address[] _investors) public onlyOwner {
for (uint i = 0; i < _investors.length; ++i) {
address investor = _investors[i];
Investment storage investment = investments[investor];
if (!investment.isVerified) {
investment.isVerified = true;
emit InvestorVerified(investor);
uint pendingTokenAmount = investment.pendingTokenAmount;
// now we issue tokens to the verfied investor
if (pendingTokenAmount > 0) {
investment.pendingTokenAmount = 0;
_forwardFunds(investment.totalWeiInvested);
_deliverTokens(investor, pendingTokenAmount);
emit TokensDelivered(investor, pendingTokenAmount);
}
}
}
}
/// @dev Withdraw investment
/// @dev Investors that are not verified can withdraw their funds
function withdrawInvestment() public {
Investment storage investment = investments[msg.sender];
require(!investment.isVerified);
uint totalWeiInvested = investment.totalWeiInvested;
require(totalWeiInvested > 0);
investment.totalWeiInvested = 0;
investment.pendingTokenAmount = 0;
pendingWeiAmount = pendingWeiAmount.sub(totalWeiInvested);
msg.sender.transfer(totalWeiInvested);
emit InvestmentWithdrawn(msg.sender, totalWeiInvested);
assert(pendingWeiAmount <= address(this).balance);
}
/// @dev Prevalidate purchase
/// @param _beneficiary the investor's Ethereum address
/// @param _weiAmount the wei amount invested
function _preValidatePurchase(address _beneficiary, uint _weiAmount) internal {
// We only want the msg.sender to buy tokens
require(_beneficiary == msg.sender);
super._preValidatePurchase(_beneficiary, _weiAmount);
}
/// @dev Process purchase
/// @param _tokenAmount the token amount purchased
function _processPurchase(address, uint _tokenAmount) internal {
Investment storage investment = investments[msg.sender];
investment.totalWeiInvested = investment.totalWeiInvested.add(msg.value);
if (investment.isVerified) {
// If the investor's KYC is already verified we issue the tokens imediatly
_deliverTokens(msg.sender, _tokenAmount);
emit TokensDelivered(msg.sender, _tokenAmount);
} else {
// If the investor's KYC is not verified we store the pending token amount
investment.pendingTokenAmount = investment.pendingTokenAmount.add(_tokenAmount);
pendingWeiAmount = pendingWeiAmount.add(msg.value);
}
}
/// @dev Forward funds
function _forwardFunds() internal {
// Ensure the investor was verified, i.e. his purchased tokens were delivered,
// before forwarding funds.
if (investments[msg.sender].isVerified) {
super._forwardFunds();
}
}
/// @dev Forward funds
/// @param _weiAmount the amount to be transfered
function _forwardFunds(uint _weiAmount) internal {
pendingWeiAmount = pendingWeiAmount.sub(_weiAmount);
wallet.transfer(_weiAmount);
}
/// @dev Postvalidate purchase
/// @param _weiAmount the amount invested
function _postValidatePurchase(address, uint _weiAmount) internal {
super._postValidatePurchase(msg.sender, _weiAmount);
// checking invariant
assert(pendingWeiAmount <= address(this).balance);
}
}
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/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 {
_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);
}
}
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/CappedToken.sol
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
// File: node_modules/zeppelin-solidity/contracts/lifecycle/Pausable.sol
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
// File: node_modules/zeppelin-solidity/contracts/token/ERC20/PausableToken.sol
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
// File: contracts/VreoToken.sol
/// @title VreoToken
/// @author Sicos et al.
contract VreoToken is CappedToken, PausableToken, BurnableToken {
uint public constant TOTAL_TOKEN_CAP = 700000000e18; // = 700.000.000 e18
string public name = "VREO Token";
string public symbol = "VREO";
uint8 public decimals = 18;
/// @dev Constructor
constructor() public CappedToken(TOTAL_TOKEN_CAP) {
pause();
}
}
// File: contracts/VreoTokenSale.sol
/// @title VreoTokenSale
/// @author Sicos et al.
contract VreoTokenSale is PostKYCCrowdsale, FinalizableCrowdsale, MintedCrowdsale {
// Maxmimum number of tokens sold in Presale+Iconiq+Vreo sales
uint public constant TOTAL_TOKEN_CAP_OF_SALE = 450000000e18; // = 450.000.000 e18
// Extra tokens minted upon finalization
uint public constant TOKEN_SHARE_OF_TEAM = 85000000e18; // = 85.000.000 e18
uint public constant TOKEN_SHARE_OF_ADVISORS = 58000000e18; // = 58.000.000 e18
uint public constant TOKEN_SHARE_OF_LEGALS = 57000000e18; // = 57.000.000 e18
uint public constant TOKEN_SHARE_OF_BOUNTY = 50000000e18; // = 50.000.000 e18
// Extra token percentages
uint public constant BONUS_PCT_IN_ICONIQ_SALE = 30; // TBD
uint public constant BONUS_PCT_IN_VREO_SALE_PHASE_1 = 20;
uint public constant BONUS_PCT_IN_VREO_SALE_PHASE_2 = 10;
// Date/time constants
uint public constant ICONIQ_SALE_OPENING_TIME = 1553673600; // 2019-03-27 09:00:00 CEST
uint public constant ICONIQ_SALE_CLOSING_TIME = 1553674600;
uint public constant VREO_SALE_OPENING_TIME = 1553675600;
uint public constant VREO_SALE_PHASE_1_END_TIME = 1553676600;
uint public constant VREO_SALE_PHASE_2_END_TIME = 1553760000; // 2019-03-28 09:00:00 CEST
uint public constant VREO_SALE_CLOSING_TIME = 1554026400; // 2019-03-31 12:00:00 CEST
uint public constant KYC_VERIFICATION_END_TIME = 1554033600; // 2019-03-31 13:26:00 CEST
// Amount of ICONIQ token investors need per Wei invested in ICONIQ PreSale.
uint public constant ICONIQ_TOKENS_NEEDED_PER_INVESTED_WEI = 450;
// ICONIQ Token
ERC20Basic public iconiqToken;
// addresses token shares are minted to in finalization
address public teamAddress;
address public advisorsAddress;
address public legalsAddress;
address public bountyAddress;
// Amount of token available for purchase
uint public remainingTokensForSale;
/// @dev Log entry on rate changed
/// @param newRate the new rate
event RateChanged(uint newRate);
/// @dev Constructor
/// @param _token A VreoToken
/// @param _rate the initial rate.
/// @param _iconiqToken An IconiqInterface
/// @param _teamAddress Ethereum address of Team
/// @param _advisorsAddress Ethereum address of Advisors
/// @param _legalsAddress Ethereum address of Legals
/// @param _bountyAddress A VreoTokenBounty
/// @param _wallet MultiSig wallet address the ETH is forwarded to.
constructor(
VreoToken _token,
uint _rate,
ERC20Basic _iconiqToken,
address _teamAddress,
address _advisorsAddress,
address _legalsAddress,
address _bountyAddress,
address _wallet
)
public
Crowdsale(_rate, _wallet, _token)
TimedCrowdsale(ICONIQ_SALE_OPENING_TIME, VREO_SALE_CLOSING_TIME)
{
// Token sanity check
require(_token.cap() >= TOTAL_TOKEN_CAP_OF_SALE
+ TOKEN_SHARE_OF_TEAM
+ TOKEN_SHARE_OF_ADVISORS
+ TOKEN_SHARE_OF_LEGALS
+ TOKEN_SHARE_OF_BOUNTY);
// Sanity check of addresses
require(address(_iconiqToken) != address(0)
&& _teamAddress != address(0)
&& _advisorsAddress != address(0)
&& _legalsAddress != address(0)
&& _bountyAddress != address(0));
iconiqToken = _iconiqToken;
teamAddress = _teamAddress;
advisorsAddress = _advisorsAddress;
legalsAddress = _legalsAddress;
bountyAddress = _bountyAddress;
remainingTokensForSale = TOTAL_TOKEN_CAP_OF_SALE;
}
/// @dev Distribute presale
/// @param _investors list of investor addresses
/// @param _amounts list of token amounts purchased by investors
function distributePresale(address[] _investors, uint[] _amounts) public onlyOwner {
require(!hasClosed());
require(_investors.length == _amounts.length);
uint totalAmount = 0;
for (uint i = 0; i < _investors.length; ++i) {
VreoToken(token).mint(_investors[i], _amounts[i]);
totalAmount = totalAmount.add(_amounts[i]);
}
require(remainingTokensForSale >= totalAmount);
remainingTokensForSale = remainingTokensForSale.sub(totalAmount);
}
/// @dev Set rate
/// @param _newRate the new rate
function setRate(uint _newRate) public onlyOwner {
// A rate change by a magnitude order of ten and above is rather a typo than intention.
// If it was indeed desired, several setRate transactions have to be sent.
require(rate / 10 < _newRate && _newRate < 10 * rate);
rate = _newRate;
emit RateChanged(_newRate);
}
/// @dev unverified investors can withdraw their money only after the VREO Sale ended
function withdrawInvestment() public {
require(hasClosed());
super.withdrawInvestment();
}
/// @dev Is the sale for ICONIQ investors ongoing?
/// @return bool
function iconiqSaleOngoing() public view returns (bool) {
return ICONIQ_SALE_OPENING_TIME <= now && now <= ICONIQ_SALE_CLOSING_TIME;
}
/// @dev Is the Vreo main sale ongoing?
/// @return bool
function vreoSaleOngoing() public view returns (bool) {
return VREO_SALE_OPENING_TIME <= now && now <= VREO_SALE_CLOSING_TIME;
}
/// @dev Get maximum possible wei investment while Iconiq sale
/// @param _investor an investors Ethereum address
/// @return Maximum allowed wei investment
function getIconiqMaxInvestment(address _investor) public view returns (uint) {
uint iconiqBalance = iconiqToken.balanceOf(_investor);
uint prorataLimit = iconiqBalance.div(ICONIQ_TOKENS_NEEDED_PER_INVESTED_WEI);
// Substract Wei amount already invested.
require(prorataLimit >= investments[_investor].totalWeiInvested);
return prorataLimit.sub(investments[_investor].totalWeiInvested);
}
/// @dev Pre validate purchase
/// @param _beneficiary an investors Ethereum address
/// @param _weiAmount wei amount invested
function _preValidatePurchase(address _beneficiary, uint _weiAmount) internal {
super._preValidatePurchase(_beneficiary, _weiAmount);
require(iconiqSaleOngoing() && getIconiqMaxInvestment(msg.sender) >= _weiAmount || vreoSaleOngoing());
}
/// @dev Get token amount
/// @param _weiAmount wei amount invested
/// @return token amount with bonus
function _getTokenAmount(uint _weiAmount) internal view returns (uint) {
uint tokenAmount = super._getTokenAmount(_weiAmount);
if (now <= ICONIQ_SALE_CLOSING_TIME) {
return tokenAmount.mul(100 + BONUS_PCT_IN_ICONIQ_SALE).div(100);
}
if (now <= VREO_SALE_PHASE_1_END_TIME) {
return tokenAmount.mul(100 + BONUS_PCT_IN_VREO_SALE_PHASE_1).div(100);
}
if (now <= VREO_SALE_PHASE_2_END_TIME) {
return tokenAmount.mul(100 + BONUS_PCT_IN_VREO_SALE_PHASE_2).div(100);
}
return tokenAmount; // No bonus
}
/// @dev Deliver tokens
/// @param _beneficiary an investors Ethereum address
/// @param _tokenAmount token amount to deliver
function _deliverTokens(address _beneficiary, uint _tokenAmount) internal {
require(remainingTokensForSale >= _tokenAmount);
remainingTokensForSale = remainingTokensForSale.sub(_tokenAmount);
super._deliverTokens(_beneficiary, _tokenAmount);
}
/// @dev Finalization
function finalization() internal {
require(now >= KYC_VERIFICATION_END_TIME);
VreoToken(token).mint(teamAddress, TOKEN_SHARE_OF_TEAM);
VreoToken(token).mint(advisorsAddress, TOKEN_SHARE_OF_ADVISORS);
VreoToken(token).mint(legalsAddress, TOKEN_SHARE_OF_LEGALS);
VreoToken(token).mint(bountyAddress, TOKEN_SHARE_OF_BOUNTY);
VreoToken(token).finishMinting();
VreoToken(token).unpause();
super.finalization();
}
}
|
Distribute presale _investors list of investor addresses _amounts list of token amounts purchased by investors
|
function distributePresale(address[] _investors, uint[] _amounts) public onlyOwner {
require(!hasClosed());
require(_investors.length == _amounts.length);
uint totalAmount = 0;
for (uint i = 0; i < _investors.length; ++i) {
VreoToken(token).mint(_investors[i], _amounts[i]);
totalAmount = totalAmount.add(_amounts[i]);
}
require(remainingTokensForSale >= totalAmount);
remainingTokensForSale = remainingTokensForSale.sub(totalAmount);
}
| 7,310,450 |
./full_match/80001/0x5d12a2b9937B0F7EA99e5a13Ad89AaB05Ef7288b/sources/contracts/Settings.sol
|
Set Chainlink Price Aggregator/
|
function setAggregator(address _token_address) public virtual onlyOwner {
Settings storage s = getSettings();
s.aggregator = _token_address;
}
| 853,516 |
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;
}
}
// Pause functionality taken from OpenZeppelin. License below.
/* The MIT License (MIT)
Copyright (c) 2016 Smart Contract Solutions, Inc.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions: */
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event SetPaused(bool paused);
// starts unpaused
bool public paused = false;
/* @dev modifier to allow actions only when the contract IS paused */
modifier whenNotPaused() {
require(!paused);
_;
}
/* @dev modifier to allow actions only when the contract IS NOT paused */
modifier whenPaused() {
require(paused);
_;
}
function pause() public onlyOwner whenNotPaused returns (bool) {
paused = true;
SetPaused(paused);
return true;
}
function unpause() public onlyOwner whenPaused returns (bool) {
paused = false;
SetPaused(paused);
return true;
}
}
contract EtherbotsPrivileges is Pausable {
event ContractUpgrade(address newContract);
}
// import "./contracts/CratePreSale.sol";
// Central collection of storage on which all other contracts depend.
// Contains structs for parts, users and functions which control their
// transferrence.
contract EtherbotsBase is EtherbotsPrivileges {
function EtherbotsBase() public {
// scrapyard = address(this);
}
/*** EVENTS ***/
/// Forge fires when a new part is created - 4 times when a crate is opened,
/// and once when a battle takes place. Also has fires when
/// parts are combined in the furnace.
event Forge(address owner, uint256 partID, Part part);
/// Transfer event as defined in ERC721.
event Transfer(address from, address to, uint256 tokenId);
/*** DATA TYPES ***/
/// The main struct representation of a robot part. Each robot in Etherbots is represented by four copies
/// of this structure, one for each of the four parts comprising it:
/// 1. Right Arm (Melee),
/// 2. Left Arm (Defence),
/// 3. Head (Turret),
/// 4. Body.
// store token id on this?
struct Part {
uint32 tokenId;
uint8 partType;
uint8 partSubType;
uint8 rarity;
uint8 element;
uint32 battlesLastDay;
uint32 experience;
uint32 forgeTime;
uint32 battlesLastReset;
}
// Part type - can be shared with other part factories.
uint8 constant DEFENCE = 1;
uint8 constant MELEE = 2;
uint8 constant BODY = 3;
uint8 constant TURRET = 4;
// Rarity - can be shared with other part factories.
uint8 constant STANDARD = 1;
uint8 constant SHADOW = 2;
uint8 constant GOLD = 3;
// Store a user struct
// in order to keep track of experience and perk choices.
// This perk tree is a binary tree, efficiently encodable as an array.
// 0 reflects no perk selected. 1 is first choice. 2 is second. 3 is both.
// Each choice costs experience (deducted from user struct).
/*** ~~~~~ROBOT PERKS~~~~~ ***/
// PERK 1: ATTACK vs DEFENCE PERK CHOICE.
// Choose
// PERK TWO ATTACK/ SHOOT, or DEFEND/DODGE
// PERK 2: MECH vs ELEMENTAL PERK CHOICE ---
// Choose steel and electric (Mech path), or water and fire (Elemetal path)
// (... will the mechs win the war for Ethertopia? or will the androids
// be deluged in flood and fire? ...)
// PERK 3: Commit to a specific elemental pathway:
// 1. the path of steel: the iron sword; the burning frying pan!
// 2. the path of electricity: the deadly taser, the fearsome forcefield
// 3. the path of water: high pressure water blasters have never been so cool
// 4. the path of fire!: we will hunt you down, Aang...
struct User {
// address userAddress;
uint32 numShards; //limit shards to upper bound eg 10000
uint32 experience;
uint8[32] perks;
}
//Maintain an array of all users.
// User[] public users;
// Store a map of the address to a uint representing index of User within users
// we check if a user exists at multiple points, every time they acquire
// via a crate or the market. Users can also manually register their address.
mapping ( address => User ) public addressToUser;
// Array containing the structs of all parts in existence. The ID
// of each part is an index into this array.
Part[] parts;
// Mapping from part IDs to to owning address. Should always exist.
mapping (uint256 => address) public partIndexToOwner;
// A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count. REMOVE?
mapping (address => uint256) addressToTokensOwned;
// Mapping from Part ID to an address approved to call transferFrom().
// maximum of one approved address for transfer at any time.
mapping (uint256 => address) public partIndexToApproved;
address auction;
// address scrapyard;
// Array to store approved battle contracts.
// Can only ever be added to, not removed from.
// Once a ruleset is published, you will ALWAYS be able to use that contract
address[] approvedBattles;
function getUserByAddress(address _user) public view returns (uint32, uint8[32]) {
return (addressToUser[_user].experience, addressToUser[_user].perks);
}
// Transfer a part to an address
function _transfer(address _from, address _to, uint256 _tokenId) internal {
// No cap on number of parts
// Very unlikely to ever be 2^256 parts owned by one account
// Shouldn't waste gas checking for overflow
// no point making it less than a uint --> mappings don't pack
addressToTokensOwned[_to]++;
// transfer ownership
partIndexToOwner[_tokenId] = _to;
// New parts are transferred _from 0x0, but we can't account that address.
if (_from != address(0)) {
addressToTokensOwned[_from]--;
// clear any previously approved ownership exchange
delete partIndexToApproved[_tokenId];
}
// Emit the transfer event.
Transfer(_from, _to, _tokenId);
}
function getPartById(uint _id) external view returns (
uint32 tokenId,
uint8 partType,
uint8 partSubType,
uint8 rarity,
uint8 element,
uint32 battlesLastDay,
uint32 experience,
uint32 forgeTime,
uint32 battlesLastReset
) {
Part memory p = parts[_id];
return (p.tokenId, p.partType, p.partSubType, p.rarity, p.element, p.battlesLastDay, p.experience, p.forgeTime, p.battlesLastReset);
}
function substring(string str, uint startIndex, uint endIndex) internal pure returns (string) {
bytes memory strBytes = bytes(str);
bytes memory result = new bytes(endIndex-startIndex);
for (uint i = startIndex; i < endIndex; i++) {
result[i-startIndex] = strBytes[i];
}
return string(result);
}
// helper functions adapted from Jossie Calderon on stackexchange
function stringToUint32(string s) internal pure returns (uint32) {
bytes memory b = bytes(s);
uint result = 0;
for (uint i = 0; i < b.length; i++) { // c = b[i] was not needed
if (b[i] >= 48 && b[i] <= 57) {
result = result * 10 + (uint(b[i]) - 48); // bytes and int are not compatible with the operator -.
}
}
return uint32(result);
}
function stringToUint8(string s) internal pure returns (uint8) {
return uint8(stringToUint32(s));
}
function uintToString(uint v) internal pure returns (string) {
uint maxlength = 100;
bytes memory reversed = new bytes(maxlength);
uint i = 0;
while (v != 0) {
uint remainder = v % 10;
v = v / 10;
reversed[i++] = byte(48 + remainder);
}
bytes memory s = new bytes(i); // i + 1 is inefficient
for (uint j = 0; j < i; j++) {
s[j] = reversed[i - j - 1]; // to avoid the off-by-one error
}
string memory str = string(s);
return str;
}
}
// This contract implements both the original ERC-721 standard and
// the proposed 'deed' standard of 841
// I don't know which standard will eventually be adopted - support both for now
/// @title Interface for contracts conforming to ERC-721: Deed Standard
/// @author William Entriken (https://phor.net), et. al.
/// @dev Specification at https://github.com/ethereum/eips/841
/// can read the comments there
contract ERC721 {
// COMPLIANCE WITH ERC-165 (DRAFT)
/// @dev ERC-165 (draft) interface signature for itself
bytes4 internal constant INTERFACE_SIGNATURE_ERC165 =
bytes4(keccak256("supportsInterface(bytes4)"));
/// @dev ERC-165 (draft) interface signature for ERC721
bytes4 internal constant INTERFACE_SIGNATURE_ERC721 =
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("countOfDeeds()")) ^
bytes4(keccak256("countOfDeedsByOwner(address)")) ^
bytes4(keccak256("deedOfOwnerByIndex(address,uint256)")) ^
bytes4(keccak256("approve(address,uint256)")) ^
bytes4(keccak256("takeOwnership(uint256)"));
function supportsInterface(bytes4 _interfaceID) external pure returns (bool);
// PUBLIC QUERY FUNCTIONS //////////////////////////////////////////////////
function ownerOf(uint256 _deedId) public view returns (address _owner);
function countOfDeeds() external view returns (uint256 _count);
function countOfDeedsByOwner(address _owner) external view returns (uint256 _count);
function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId);
// TRANSFER MECHANISM //////////////////////////////////////////////////////
event Transfer(address indexed from, address indexed to, uint256 indexed deedId);
event Approval(address indexed owner, address indexed approved, uint256 indexed deedId);
function approve(address _to, uint256 _deedId) external payable;
function takeOwnership(uint256 _deedId) external payable;
}
/// @title Metadata extension to ERC-721 interface
/// @author William Entriken (https://phor.net)
/// @dev Specification at https://github.com/ethereum/eips/issues/XXXX
contract ERC721Metadata is ERC721 {
bytes4 internal constant INTERFACE_SIGNATURE_ERC721Metadata =
bytes4(keccak256("name()")) ^
bytes4(keccak256("symbol()")) ^
bytes4(keccak256("deedUri(uint256)"));
function name() public pure returns (string n);
function symbol() public pure returns (string s);
/// @notice A distinct URI (RFC 3986) for a given token.
/// @dev If:
/// * The URI is a URL
/// * The URL is accessible
/// * The URL points to a valid JSON file format (ECMA-404 2nd ed.)
/// * The JSON base element is an object
/// then these names of the base element SHALL have special meaning:
/// * "name": A string identifying the item to which `_deedId` grants
/// ownership
/// * "description": A string detailing the item to which `_deedId` grants
/// ownership
/// * "image": A URI pointing to a file of image/* mime type representing
/// the item to which `_deedId` grants ownership
/// Wallets and exchanges MAY display this to the end user.
/// Consider making any images at a width between 320 and 1080 pixels and
/// aspect ratio between 1.91:1 and 4:5 inclusive.
function deedUri(uint256 _deedId) external view returns (string _uri);
}
/// @title Enumeration extension to ERC-721 interface
/// @author William Entriken (https://phor.net)
/// @dev Specification at https://github.com/ethereum/eips/issues/XXXX
contract ERC721Enumerable is ERC721Metadata {
/// @dev ERC-165 (draft) interface signature for ERC721
bytes4 internal constant INTERFACE_SIGNATURE_ERC721Enumerable =
bytes4(keccak256("deedByIndex()")) ^
bytes4(keccak256("countOfOwners()")) ^
bytes4(keccak256("ownerByIndex(uint256)"));
function deedByIndex(uint256 _index) external view returns (uint256 _deedId);
function countOfOwners() external view returns (uint256 _count);
function ownerByIndex(uint256 _index) external view returns (address _owner);
}
contract ERC721Original {
bytes4 constant INTERFACE_SIGNATURE_ERC721Original =
bytes4(keccak256("totalSupply()")) ^
bytes4(keccak256("balanceOf(address)")) ^
bytes4(keccak256("ownerOf(uint256)")) ^
bytes4(keccak256("approve(address,uint256)")) ^
bytes4(keccak256("takeOwnership(uint256)")) ^
bytes4(keccak256("transfer(address,uint256)"));
// Core functions
function implementsERC721() public pure returns (bool);
function totalSupply() public view returns (uint256 _totalSupply);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint _tokenId) public view returns (address _owner);
function approve(address _to, uint _tokenId) external payable;
function transferFrom(address _from, address _to, uint _tokenId) public;
function transfer(address _to, uint _tokenId) public payable;
// Optional functions
function name() public pure returns (string _name);
function symbol() public pure returns (string _symbol);
function tokenOfOwnerByIndex(address _owner, uint _index) external view returns (uint _tokenId);
function tokenMetadata(uint _tokenId) public view returns (string _infoUrl);
// Events
// event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
// event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
}
contract ERC721AllImplementations is ERC721Original, ERC721Enumerable {
}
contract EtherbotsNFT is EtherbotsBase, ERC721Enumerable, ERC721Original {
function supportsInterface(bytes4 _interfaceID) external pure returns (bool) {
return (_interfaceID == ERC721Original.INTERFACE_SIGNATURE_ERC721Original) ||
(_interfaceID == ERC721.INTERFACE_SIGNATURE_ERC721) ||
(_interfaceID == ERC721Metadata.INTERFACE_SIGNATURE_ERC721Metadata) ||
(_interfaceID == ERC721Enumerable.INTERFACE_SIGNATURE_ERC721Enumerable);
}
function implementsERC721() public pure returns (bool) {
return true;
}
function name() public pure returns (string _name) {
return "Etherbots";
}
function symbol() public pure returns (string _smbol) {
return "ETHBOT";
}
// total supply of parts --> as no parts are ever deleted, this is simply
// the total supply of parts ever created
function totalSupply() public view returns (uint) {
return parts.length;
}
/// @notice Returns the total number of deeds currently in existence.
/// @dev Required for ERC-721 compliance.
function countOfDeeds() external view returns (uint256) {
return parts.length;
}
//--/ internal function which checks whether the token with id (_tokenId)
/// is owned by the (_claimant) address
function owns(address _owner, uint256 _tokenId) public view returns (bool) {
return (partIndexToOwner[_tokenId] == _owner);
}
/// internal function which checks whether the token with id (_tokenId)
/// is owned by the (_claimant) address
function ownsAll(address _owner, uint256[] _tokenIds) public view returns (bool) {
require(_tokenIds.length > 0);
for (uint i = 0; i < _tokenIds.length; i++) {
if (partIndexToOwner[_tokenIds[i]] != _owner) {
return false;
}
}
return true;
}
function _approve(uint256 _tokenId, address _approved) internal {
partIndexToApproved[_tokenId] = _approved;
}
function _approvedFor(address _newOwner, uint256 _tokenId) internal view returns (bool) {
return (partIndexToApproved[_tokenId] == _newOwner);
}
function ownerByIndex(uint256 _index) external view returns (address _owner){
return partIndexToOwner[_index];
}
// returns the NUMBER of tokens owned by (_owner)
function balanceOf(address _owner) public view returns (uint256 count) {
return addressToTokensOwned[_owner];
}
function countOfDeedsByOwner(address _owner) external view returns (uint256) {
return balanceOf(_owner);
}
// transfers a part to another account
function transfer(address _to, uint256 _tokenId) public whenNotPaused payable {
// payable for ERC721 --> don't actually send eth @_@
require(msg.value == 0);
// Safety checks to prevent accidental transfers to common accounts
require(_to != address(0));
require(_to != address(this));
// can't transfer parts to the auction contract directly
require(_to != address(auction));
// can't transfer parts to any of the battle contracts directly
for (uint j = 0; j < approvedBattles.length; j++) {
require(_to != approvedBattles[j]);
}
// Cannot send tokens you don't own
require(owns(msg.sender, _tokenId));
// perform state changes necessary for transfer
_transfer(msg.sender, _to, _tokenId);
}
// transfers a part to another account
function transferAll(address _to, uint256[] _tokenIds) public whenNotPaused payable {
require(msg.value == 0);
// Safety checks to prevent accidental transfers to common accounts
require(_to != address(0));
require(_to != address(this));
// can't transfer parts to the auction contract directly
require(_to != address(auction));
// can't transfer parts to any of the battle contracts directly
for (uint j = 0; j < approvedBattles.length; j++) {
require(_to != approvedBattles[j]);
}
// Cannot send tokens you don't own
require(ownsAll(msg.sender, _tokenIds));
for (uint k = 0; k < _tokenIds.length; k++) {
// perform state changes necessary for transfer
_transfer(msg.sender, _to, _tokenIds[k]);
}
}
// approves the (_to) address to use the transferFrom function on the token with id (_tokenId)
// if you want to clear all approvals, simply pass the zero address
function approve(address _to, uint256 _deedId) external whenNotPaused payable {
// payable for ERC721 --> don't actually send eth @_@
require(msg.value == 0);
// use internal function?
// Cannot approve the transfer of tokens you don't own
require(owns(msg.sender, _deedId));
// Store the approval (can only approve one at a time)
partIndexToApproved[_deedId] = _to;
Approval(msg.sender, _to, _deedId);
}
// approves many token ids
function approveMany(address _to, uint256[] _tokenIds) external whenNotPaused payable {
for (uint i = 0; i < _tokenIds.length; i++) {
uint _tokenId = _tokenIds[i];
// Cannot approve the transfer of tokens you don't own
require(owns(msg.sender, _tokenId));
// Store the approval (can only approve one at a time)
partIndexToApproved[_tokenId] = _to;
//create event for each approval? _tokenId guaranteed to hold correct value?
Approval(msg.sender, _to, _tokenId);
}
}
// transfer the part with id (_tokenId) from (_from) to (_to)
// (_to) must already be approved for this (_tokenId)
function transferFrom(address _from, address _to, uint256 _tokenId) public whenNotPaused {
// Safety checks to prevent accidents
require(_to != address(0));
require(_to != address(this));
// sender must be approved
require(partIndexToApproved[_tokenId] == msg.sender);
// from must currently own the token
require(owns(_from, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transfer(_from, _to, _tokenId);
}
// returns the current owner of the token with id = _tokenId
function ownerOf(uint256 _deedId) public view returns (address _owner) {
_owner = partIndexToOwner[_deedId];
// must result false if index key not found
require(_owner != address(0));
}
// returns a dynamic array of the ids of all tokens which are owned by (_owner)
// Looping through every possible part and checking it against the owner is
// actually much more efficient than storing a mapping or something, because
// it won't be executed as a transaction
function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) {
uint256 totalParts = totalSupply();
return tokensOfOwnerWithinRange(_owner, 0, totalParts);
}
function tokensOfOwnerWithinRange(address _owner, uint _start, uint _numToSearch) public view returns(uint256[] ownerTokens) {
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tmpResult = new uint256[](tokenCount);
if (tokenCount == 0) {
return tmpResult;
}
uint256 resultIndex = 0;
for (uint partId = _start; partId < _start + _numToSearch; partId++) {
if (partIndexToOwner[partId] == _owner) {
tmpResult[resultIndex] = partId;
resultIndex++;
if (resultIndex == tokenCount) { //found all tokens accounted for, no need to continue
break;
}
}
}
// copy number of tokens found in given range
uint resultLength = resultIndex;
uint256[] memory result = new uint256[](resultLength);
for (uint i=0; i<resultLength; i++) {
result[i] = tmpResult[i];
}
return result;
}
//same issues as above
// Returns an array of all part structs owned by the user. Free to call.
function getPartsOfOwner(address _owner) external view returns(bytes24[]) {
uint256 totalParts = totalSupply();
return getPartsOfOwnerWithinRange(_owner, 0, totalParts);
}
// This is public so it can be called by getPartsOfOwner. It should NOT be called by another contract
// as it is very gas hungry.
function getPartsOfOwnerWithinRange(address _owner, uint _start, uint _numToSearch) public view returns(bytes24[]) {
uint256 tokenCount = balanceOf(_owner);
uint resultIndex = 0;
bytes24[] memory result = new bytes24[](tokenCount);
for (uint partId = _start; partId < _start + _numToSearch; partId++) {
if (partIndexToOwner[partId] == _owner) {
result[resultIndex] = _partToBytes(parts[partId]);
resultIndex++;
}
}
return result; // will have 0 elements if tokenCount == 0
}
function _partToBytes(Part p) internal pure returns (bytes24 b) {
b = bytes24(p.tokenId);
b = b << 8;
b = b | bytes24(p.partType);
b = b << 8;
b = b | bytes24(p.partSubType);
b = b << 8;
b = b | bytes24(p.rarity);
b = b << 8;
b = b | bytes24(p.element);
b = b << 32;
b = b | bytes24(p.battlesLastDay);
b = b << 32;
b = b | bytes24(p.experience);
b = b << 32;
b = b | bytes24(p.forgeTime);
b = b << 32;
b = b | bytes24(p.battlesLastReset);
}
uint32 constant FIRST_LEVEL = 1000;
uint32 constant INCREMENT = 1000;
// every level, you need 1000 more exp to go up a level
function getLevel(uint32 _exp) public pure returns(uint32) {
uint32 c = 0;
for (uint32 i = FIRST_LEVEL; i <= FIRST_LEVEL + _exp; i += c * INCREMENT) {
c++;
}
return c;
}
string metadataBase = "https://api.etherbots.io/api/";
function setMetadataBase(string _base) external onlyOwner {
metadataBase = _base;
}
// part type, subtype,
// have one internal function which lets us implement the divergent interfaces
function _metadata(uint256 _id) internal view returns(string) {
Part memory p = parts[_id];
return strConcat(strConcat(
metadataBase,
uintToString(uint(p.partType)),
"/",
uintToString(uint(p.partSubType)),
"/"
), uintToString(uint(p.rarity)), "", "", "");
}
function strConcat(string _a, string _b, string _c, string _d, string _e) internal pure returns (string){
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
bytes memory _bc = bytes(_c);
bytes memory _bd = bytes(_d);
bytes memory _be = bytes(_e);
string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length);
bytes memory babcde = bytes(abcde);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) babcde[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) babcde[k++] = _bb[i];
for (i = 0; i < _bc.length; i++) babcde[k++] = _bc[i];
for (i = 0; i < _bd.length; i++) babcde[k++] = _bd[i];
for (i = 0; i < _be.length; i++) babcde[k++] = _be[i];
return string(babcde);
}
/// @notice A distinct URI (RFC 3986) for a given token.
/// @dev If:
/// * The URI is a URL
/// * The URL is accessible
/// * The URL points to a valid JSON file format (ECMA-404 2nd ed.)
/// * The JSON base element is an object
/// then these names of the base element SHALL have special meaning:
/// * "name": A string identifying the item to which `_deedId` grants
/// ownership
/// * "description": A string detailing the item to which `_deedId` grants
/// ownership
/// * "image": A URI pointing to a file of image/* mime type representing
/// the item to which `_deedId` grants ownership
/// Wallets and exchanges MAY display this to the end user.
/// Consider making any images at a width between 320 and 1080 pixels and
/// aspect ratio between 1.91:1 and 4:5 inclusive.
function deedUri(uint256 _deedId) external view returns (string _uri){
return _metadata(_deedId);
}
/// returns a metadata URI
function tokenMetadata(uint256 _tokenId) public view returns (string infoUrl) {
return _metadata(_tokenId);
}
function takeOwnership(uint256 _deedId) external payable {
// payable for ERC721 --> don't actually send eth @_@
require(msg.value == 0);
address _from = partIndexToOwner[_deedId];
require(_approvedFor(msg.sender, _deedId));
_transfer(_from, msg.sender, _deedId);
}
// parts are stored sequentially
function deedByIndex(uint256 _index) external view returns (uint256 _deedId){
return _index;
}
function countOfOwners() external view returns (uint256 _count){
// TODO: implement this
return 0;
}
// thirsty function
function tokenOfOwnerByIndex(address _owner, uint _index) external view returns (uint _tokenId){
return _tokenOfOwnerByIndex(_owner, _index);
}
// code duplicated
function _tokenOfOwnerByIndex(address _owner, uint _index) private view returns (uint _tokenId){
// The index should be valid.
require(_index < balanceOf(_owner));
// can loop through all without
uint256 seen = 0;
uint256 totalTokens = totalSupply();
for (uint i = 0; i < totalTokens; i++) {
if (partIndexToOwner[i] == _owner) {
if (seen == _index) {
return i;
}
seen++;
}
}
}
function deedOfOwnerByIndex(address _owner, uint256 _index) external view returns (uint256 _deedId){
return _tokenOfOwnerByIndex(_owner, _index);
}
}
// Auction contract, facilitating statically priced sales, as well as
// inflationary and deflationary pricing for items.
// Relies heavily on the ERC721 interface and so most of the methods
// are tightly bound to that implementation
contract NFTAuctionBase is Pausable {
ERC721AllImplementations public nftContract;
uint256 public ownerCut;
uint public minDuration;
uint public maxDuration;
// Represents an auction on an NFT (in this case, Robot part)
struct Auction {
// address of part owner
address seller;
// wei price of listing
uint256 startPrice;
// wei price of floor
uint256 endPrice;
// duration of sale in seconds.
uint64 duration;
// Time when sale started
// Reset to 0 after sale concluded
uint64 start;
}
function NFTAuctionBase() public {
minDuration = 60 minutes;
maxDuration = 30 days; // arbitrary
}
// map of all tokens and their auctions
mapping (uint256 => Auction) tokenIdToAuction;
event AuctionCreated(uint256 tokenId, uint256 startPrice, uint256 endPrice, uint64 duration, uint64 start);
event AuctionSuccessful(uint256 tokenId, uint256 totalPrice, address winner);
event AuctionCancelled(uint256 tokenId);
// returns true if the token with id _partId is owned by the _claimant address
function _owns(address _claimant, uint256 _partId) internal view returns (bool) {
return nftContract.ownerOf(_partId) == _claimant;
}
// returns false if auction start time is 0, likely from uninitialised struct
function _isActiveAuction(Auction _auction) internal pure returns (bool) {
return _auction.start > 0;
}
// assigns ownership of the token with id = _partId to this contract
// must have already been approved
function _escrow(address, uint _partId) internal {
// throws on transfer fail
nftContract.takeOwnership(_partId);
}
// transfer the token with id = _partId to buying address
function _transfer(address _purchasor, uint256 _partId) internal {
// successful purchaseder must takeOwnership of _partId
// nftContract.approve(_purchasor, _partId);
// actual transfer
nftContract.transfer(_purchasor, _partId);
}
// creates
function _newAuction(uint256 _partId, Auction _auction) internal {
require(_auction.duration >= minDuration);
require(_auction.duration <= maxDuration);
tokenIdToAuction[_partId] = _auction;
AuctionCreated(uint256(_partId),
uint256(_auction.startPrice),
uint256(_auction.endPrice),
uint64(_auction.duration),
uint64(_auction.start)
);
}
function setMinDuration(uint _duration) external onlyOwner {
minDuration = _duration;
}
function setMaxDuration(uint _duration) external onlyOwner {
maxDuration = _duration;
}
/// Removes auction from public view, returns token to the seller
function _cancelAuction(uint256 _partId, address _seller) internal {
_removeAuction(_partId);
_transfer(_seller, _partId);
AuctionCancelled(_partId);
}
event PrintEvent(string, address, uint);
// Calculates price and transfers purchase to owner. Part is NOT transferred to buyer.
function _purchase(uint256 _partId, uint256 _purchaseAmount) internal returns (uint256) {
Auction storage auction = tokenIdToAuction[_partId];
// check that this token is being auctioned
require(_isActiveAuction(auction));
// enforce purchase >= the current price
uint256 price = _currentPrice(auction);
require(_purchaseAmount >= price);
// Store seller before we delete auction.
address seller = auction.seller;
// Valid purchase. Remove auction to prevent reentrancy.
_removeAuction(_partId);
// Transfer proceeds to seller (if there are any!)
if (price > 0) {
// Calculate and take fee from purchase
uint256 auctioneerCut = _computeFee(price);
uint256 sellerProceeds = price - auctioneerCut;
PrintEvent("Seller, proceeds", seller, sellerProceeds);
// Pay the seller
seller.transfer(sellerProceeds);
}
// Calculate excess funds and return to buyer.
uint256 purchaseExcess = _purchaseAmount - price;
PrintEvent("Sender, excess", msg.sender, purchaseExcess);
// Return any excess funds. Reentrancy again prevented by deleting auction.
msg.sender.transfer(purchaseExcess);
AuctionSuccessful(_partId, price, msg.sender);
return price;
}
// returns the current price of the token being auctioned in _auction
function _currentPrice(Auction storage _auction) internal view returns (uint256) {
uint256 secsElapsed = now - _auction.start;
return _computeCurrentPrice(
_auction.startPrice,
_auction.endPrice,
_auction.duration,
secsElapsed
);
}
// Checks if NFTPart is currently being auctioned.
// function _isBeingAuctioned(Auction storage _auction) internal view returns (bool) {
// return (_auction.start > 0);
// }
// removes the auction of the part with id _partId
function _removeAuction(uint256 _partId) internal {
delete tokenIdToAuction[_partId];
}
// computes the current price of an deflating-price auction
function _computeCurrentPrice( uint256 _startPrice, uint256 _endPrice, uint256 _duration, uint256 _secondsPassed ) internal pure returns (uint256 _price) {
_price = _startPrice;
if (_secondsPassed >= _duration) {
// Has been up long enough to hit endPrice.
// Return this price floor.
_price = _endPrice;
// this is a statically price sale. Just return the price.
}
else if (_duration > 0) {
// This auction contract supports auctioning from any valid price to any other valid price.
// This means the price can dynamically increase upward, or downard.
int256 priceDifference = int256(_endPrice) - int256(_startPrice);
int256 currentPriceDifference = priceDifference * int256(_secondsPassed) / int256(_duration);
int256 currentPrice = int256(_startPrice) + currentPriceDifference;
_price = uint256(currentPrice);
}
return _price;
}
// Compute percentage fee of transaction
function _computeFee (uint256 _price) internal view returns (uint256) {
return _price * ownerCut / 10000;
}
}
// Clock auction for NFTParts.
// Only timed when pricing is dynamic (i.e. startPrice != endPrice).
// Else, this becomes an infinite duration statically priced sale,
// resolving when succesfully purchase for or cancelled.
contract DutchAuction is NFTAuctionBase, EtherbotsPrivileges {
// The ERC-165 interface signature for ERC-721.
bytes4 constant InterfaceSignature_ERC721 = bytes4(0xda671b9b);
function DutchAuction(address _nftAddress, uint256 _fee) public {
require(_fee <= 10000);
ownerCut = _fee;
ERC721AllImplementations candidateContract = ERC721AllImplementations(_nftAddress);
require(candidateContract.supportsInterface(InterfaceSignature_ERC721));
nftContract = candidateContract;
}
// Remove all ether from the contract. This will be marketplace fees.
// Transfers to the NFT contract.
// Can be called by owner or NFT contract.
function withdrawBalance() external {
address nftAddress = address(nftContract);
require(msg.sender == owner || msg.sender == nftAddress);
nftAddress.transfer(this.balance);
}
event PrintEvent(string, address, uint);
// Creates an auction and lists it.
function createAuction( uint256 _partId, uint256 _startPrice, uint256 _endPrice, uint256 _duration, address _seller ) external whenNotPaused {
// Sanity check that no inputs overflow how many bits we've allocated
// to store them in the auction struct.
require(_startPrice == uint256(uint128(_startPrice)));
require(_endPrice == uint256(uint128(_endPrice)));
require(_duration == uint256(uint64(_duration)));
require(_startPrice >= _endPrice);
require(msg.sender == address(nftContract));
_escrow(_seller, _partId);
Auction memory auction = Auction(
_seller,
uint128(_startPrice),
uint128(_endPrice),
uint64(_duration),
uint64(now) //seconds uint
);
PrintEvent("Auction Start", 0x0, auction.start);
_newAuction(_partId, auction);
}
// SCRAPYARD PRICING LOGIC
uint8 constant LAST_CONSIDERED = 5;
uint8 public scrapCounter = 0;
uint[5] public lastScrapPrices;
// Purchases an open auction
// Will transfer ownership if successful.
function purchase(uint256 _partId) external payable whenNotPaused {
address seller = tokenIdToAuction[_partId].seller;
// _purchase will throw if the purchase or funds transfer fails
uint256 price = _purchase(_partId, msg.value);
_transfer(msg.sender, _partId);
// If the seller is the scrapyard, track price information.
if (seller == address(nftContract)) {
lastScrapPrices[scrapCounter] = price;
if (scrapCounter == LAST_CONSIDERED - 1) {
scrapCounter = 0;
} else {
scrapCounter++;
}
}
}
function averageScrapPrice() public view returns (uint) {
uint sum = 0;
for (uint8 i = 0; i < LAST_CONSIDERED; i++) {
sum += lastScrapPrices[i];
}
return sum / LAST_CONSIDERED;
}
// Allows a user to cancel an auction before it's resolved.
// Returns the part to the seller.
function cancelAuction(uint256 _partId) external {
Auction storage auction = tokenIdToAuction[_partId];
require(_isActiveAuction(auction));
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_partId, seller);
}
// returns the current price of the auction of a token with id _partId
function getCurrentPrice(uint256 _partId) external view returns (uint256) {
Auction storage auction = tokenIdToAuction[_partId];
require(_isActiveAuction(auction));
return _currentPrice(auction);
}
// Returns the details of an auction from its _partId.
function getAuction(uint256 _partId) external view returns ( address seller, uint256 startPrice, uint256 endPrice, uint256 duration, uint256 startedAt ) {
Auction storage auction = tokenIdToAuction[_partId];
require(_isActiveAuction(auction));
return ( auction.seller, auction.startPrice, auction.endPrice, auction.duration, auction.start);
}
// Allows owner to cancel an auction.
// ONLY able to be used when contract is paused,
// in the case of emergencies.
// Parts returned to seller as it's equivalent to them
// calling cancel.
function cancelAuctionWhenPaused(uint256 _partId) whenPaused onlyOwner external {
Auction storage auction = tokenIdToAuction[_partId];
require(_isActiveAuction(auction));
_cancelAuction(_partId, auction.seller);
}
}
|
code duplicated The index should be valid. can loop through all without
|
function _tokenOfOwnerByIndex(address _owner, uint _index) private view returns (uint _tokenId){
require(_index < balanceOf(_owner));
uint256 seen = 0;
uint256 totalTokens = totalSupply();
for (uint i = 0; i < totalTokens; i++) {
if (partIndexToOwner[i] == _owner) {
if (seen == _index) {
return i;
}
seen++;
}
}
for (uint i = 0; i < totalTokens; i++) {
if (partIndexToOwner[i] == _owner) {
if (seen == _index) {
return i;
}
seen++;
}
}
for (uint i = 0; i < totalTokens; i++) {
if (partIndexToOwner[i] == _owner) {
if (seen == _index) {
return i;
}
seen++;
}
}
}
| 7,327,479 |
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.
*/
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
pragma solidity >=0.4.24 <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;
}
pragma solidity ^0.6.0;
import "../utils/EnumerableSet.sol";
import "../utils/Address.sol";
import "../GSN/Context.sol";
import "../Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, _msgSender()));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*/
abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe {
function __AccessControl_init() internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal initializer {
}
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 `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.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "./IERC165.sol";
import "../Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
contract ERC165UpgradeSafe is Initializable, 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;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// 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;
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
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) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
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);
}
pragma solidity ^0.6.0;
import "../../GSN/Context.sol";
import "./IERC721.sol";
import "./IERC721Metadata.sol";
import "./IERC721Enumerable.sol";
import "./IERC721Receiver.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
import "../../utils/EnumerableSet.sol";
import "../../utils/EnumerableMap.sol";
import "../../utils/Strings.sol";
import "../../Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721UpgradeSafe is Initializable, ContextUpgradeSafe, ERC165UpgradeSafe, IERC721, IERC721Metadata, IERC721Enumerable {
using SafeMath for uint256;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Mapping from token ID to approved address
mapping (uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
function __ERC721_init(string memory name, string memory symbol) internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name, symbol);
}
function __ERC721_init_unchained(string memory name, string memory symbol) internal initializer {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev Gets the balance of the specified address.
* @param owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev Gets the owner of the specified token ID.
* @param tokenId uint256 ID of the token to query the owner of
* @return address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev Gets the token name.
* @return string representing the token name
*/
function name() public view override returns (string memory) {
return _name;
}
/**
* @dev Gets the token symbol.
* @return string representing the token symbol
*/
function symbol() public view override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the URI for a given token ID. May return an empty string.
*
* If a base URI is set (via {_setBaseURI}), it is added as a prefix to the
* token's own URI (via {_setTokenURI}).
*
* If there is a base URI but no token URI, the token's ID will be used as
* its URI when appending it to the base URI. This pattern for autogenerated
* token URIs can lead to large gas savings.
*
* .Examples
* |===
* |`_setBaseURI()` |`_setTokenURI()` |`tokenURI()`
* | ""
* | ""
* | ""
* | ""
* | "token.uri/123"
* | "token.uri/123"
* | "token.uri/"
* | "123"
* | "token.uri/123"
* | "token.uri/"
* | ""
* | "token.uri/<tokenId>"
* |===
*
* Requirements:
*
* - `tokenId` must exist.
*/
function tokenURI(uint256 tokenId) public view override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
// If there is no base URI, return the token URI.
if (bytes(_baseURI).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(_baseURI, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(_baseURI, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view returns (string memory) {
return _baseURI;
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner.
* @param owner address owning the tokens list to be accessed
* @param index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
return _holderTokens[owner].at(index);
}
/**
* @dev Gets the total amount of tokens stored by the contract.
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens.
* @param index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param to address to be approved for the given token ID
* @param tokenId uint256 ID of the token to be approved
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* Reverts if the token ID does not exist.
* @param tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf.
* @param operator operator address to set the approval
* @param approved representing the status of the approval to be set
*/
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 Tells whether an operator is approved by a given owner.
* @param owner owner address which you want to query the approval of
* @param operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address.
* Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* Requires the msg.sender to be the owner, approved, or operator.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address from, address to, uint256 tokenId) public 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 Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement {IERC721Receiver-onERC721Received},
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the _msgSender() to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg.sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function _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 the specified token exists.
* @param tokenId uint256 ID of the token to query the existence of
* @return bool whether the token exists
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether the given spender can transfer a given token ID.
* @param spender address of the spender to query
* @param tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Internal function to safely mint a new token.
* Reverts if the given token ID already exists.
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
* @param _data bytes data to send along with a safe transfer check
*/
function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Internal function to mint a new token.
* Reverts if the given token ID already exists.
* @param to The address that will own the minted token
* @param tokenId uint256 ID of the token to be minted
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Internal function to burn a specific token.
* Reverts if the token does not exist.
* @param tokenId uint256 ID of the token being burned
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Internal function to transfer ownership of a given token ID to another address.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param tokenId uint256 ID of the token to be transferred
*/
function _transfer(address from, address to, uint256 tokenId) internal virtual {
require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Internal function to set the token URI for a given token.
*
* Reverts if the token ID does not exist.
*
* TIP: If all token IDs share a prefix (for example, if your URIs look like
* `https://api.myproject.com/token/<id>`), use {_setBaseURI} to store
* it and save gas.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data)
private returns (bool)
{
if (!to.isContract()) {
return true;
}
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = to.call(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
));
if (!success) {
if (returndata.length > 0) {
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} else {
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
}
function _approve(address to, uint256 tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(ownerOf(tokenId), to, tokenId);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - when `from` is zero, `tokenId` will be minted for `to`.
* - when `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` 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 { }
uint256[41] private __gap;
}
pragma solidity ^0.6.0;
import "./ERC721.sol";
import "../../utils/Pausable.sol";
import "../../Initializable.sol";
/**
* @dev ERC721 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 ERC721PausableUpgradeSafe is Initializable, ERC721UpgradeSafe, PausableUpgradeSafe {
function __ERC721Pausable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
}
function __ERC721Pausable_init_unchained() internal initializer {
}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
pragma solidity ^0.6.2;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of NFTs in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the NFT specified by `tokenId`.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
*
*
* Requirements:
* - `from`, `to` cannot be zero.
* - `tokenId` must be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this
* NFT by either {approve} or {setApprovalForAll}.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to
* another (`to`).
*
* Requirements:
* - If the caller is not `from`, it must be approved to move this NFT by
* either {approve} or {setApprovalForAll}.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
function approve(address to, uint256 tokenId) external;
function getApproved(uint256 tokenId) external view returns (address operator);
function setApprovalForAll(address operator, bool _approved) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
pragma solidity ^0.6.2;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
pragma solidity ^0.6.2;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
pragma solidity ^0.6.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a {IERC721-safeTransferFrom}. This function MUST return the function selector,
* otherwise the caller will revert the transaction. The selector to be
* returned can be obtained as `this.onERC721Received.selector`. This
* function MAY throw to revert and reject the transfer.
* Note: the ERC721 contract address is always the message sender.
* @param operator The address which called `safeTransferFrom` function
* @param from The address which previously owned the token
* @param tokenId The NFT identifier which is being transferred
* @param data Additional data with no specified format
* @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data)
external returns (bytes4);
}
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");
}
}
pragma solidity ^0.6.0;
import "../math/SafeMath.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library Counters {
using SafeMath for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
pragma solidity ^0.6.0;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map._entries.push(MapEntry({ _key: key, _value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) {
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
return _get(map, key, "EnumerableMap: nonexistent key");
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*/
function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) {
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) {
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map) internal view returns (uint256) {
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) {
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint256(value)));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*/
function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) {
return address(uint256(_get(map._inner, bytes32(key), errorMessage)));
}
}
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 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];
}
// 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));
}
}
pragma solidity ^0.6.0;
import "../GSN/Context.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 PausableUpgradeSafe is Initializable, ContextUpgradeSafe {
/**
* @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.
*/
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 Triggers stopped state.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
import "../Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
contract ReentrancyGuardUpgradeSafe is Initializable {
bool private _notEntered;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
// 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;
}
uint256[49] private __gap;
}
pragma solidity ^0.6.0;
/**
* @dev String operations.
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = byte(uint8(48 + temp % 10));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// solhint-disable
/*
This is copied from OZ preset: https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/blob/release-v3.0.0/contracts/presets/ERC721PresetMinterPauserAutoId.sol
Alterations:
* Make the counter public, so that we can use it in our custom mint function
* Removed ERC721Burnable parent contract, but added our own custom burn function.
* Removed original "mint" function, because we have a custom one.
* Removed default initialization functions, because they set msg.sender as the owner, which
we do not want, because we use a deployer account, which is separate from the protocol owner.
*/
pragma solidity 0.6.12;
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Counters.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/ERC721Pausable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
/**
* @dev {ERC721} 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
* - token ID and URI autogeneration
*
* 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 aother accounts
*/
contract ERC721PresetMinterPauserAutoIdUpgradeSafe is
Initializable,
ContextUpgradeSafe,
AccessControlUpgradeSafe,
ERC721PausableUpgradeSafe
{
using Counters for Counters.Counter;
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
Counters.Counter public _tokenIdTracker;
/**
* @dev Pauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function pause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to pause");
_pause();
}
/**
* @dev Unpauses all token transfers.
*
* See {ERC721Pausable} and {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the `PAUSER_ROLE`.
*/
function unpause() public {
require(hasRole(PAUSER_ROLE, _msgSender()), "ERC721PresetMinterPauserAutoId: must have pauser role to unpause");
_unpause();
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override(ERC721PausableUpgradeSafe) {
super._beforeTokenTransfer(from, to, tokenId);
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IBackerRewards {
function allocateRewards(uint256 _interestPaymentAmount) external;
function onTranchedPoolDrawdown(uint256 sliceIndex) external;
function setPoolTokenAccRewardsPerPrincipalDollarAtMint(address poolAddress, uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
// Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IERC20withDec.sol";
interface ICUSDCContract is IERC20withDec {
/*** User Interface ***/
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,
address cTokenCollateral
) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function balanceOfUnderlying(address owner) external returns (uint256);
function exchangeRateCurrent() external returns (uint256);
/*** Admin Functions ***/
function _addReserves(uint256 addAmount) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract ICreditDesk {
uint256 public totalWritedowns;
uint256 public totalLoansOutstanding;
function setUnderwriterGovernanceLimit(address underwriterAddress, uint256 limit) external virtual;
function drawdown(address creditLineAddress, uint256 amount) external virtual;
function pay(address creditLineAddress, uint256 amount) external virtual;
function assessCreditLine(address creditLineAddress) external virtual;
function applyPayment(address creditLineAddress, uint256 amount) external virtual;
function getNextPaymentAmount(address creditLineAddress, uint256 asOfBLock) external view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface ICreditLine {
function borrower() external view returns (address);
function limit() external view returns (uint256);
function maxLimit() external view returns (uint256);
function interestApr() external view returns (uint256);
function paymentPeriodInDays() external view returns (uint256);
function principalGracePeriodInDays() external view returns (uint256);
function termInDays() external view returns (uint256);
function lateFeeApr() external view returns (uint256);
function isLate() external view returns (bool);
function withinPrincipalGracePeriod() external view returns (bool);
// Accounting variables
function balance() external view returns (uint256);
function interestOwed() external view returns (uint256);
function principalOwed() external view returns (uint256);
function termEndTime() external view returns (uint256);
function nextDueTime() external view returns (uint256);
function interestAccruedAsOf() external view returns (uint256);
function lastFullPaymentTime() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// Taken from https://github.com/compound-finance/compound-protocol/blob/master/contracts/CTokenInterfaces.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface ICurveLP {
function token() external view returns (address);
function get_virtual_price() external view returns (uint256);
function calc_token_amount(uint256[2] calldata amounts) external view returns (uint256);
function add_liquidity(
uint256[2] calldata amounts,
uint256 min_mint_amount,
bool use_eth,
address receiver
) external returns (uint256);
function balances(uint256 arg0) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol";
/*
Only addition is the `decimals` function, which we need, and which both our Fidu and USDC use, along with most ERC20's.
*/
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20withDec is IERC20 {
/**
* @dev Returns the number of decimals used for the token
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IERC20withDec.sol";
interface IFidu is IERC20withDec {
function mintTo(address to, uint256 amount) external;
function burnFrom(address to, uint256 amount) external;
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IGo {
uint256 public constant ID_TYPE_0 = 0;
uint256 public constant ID_TYPE_1 = 1;
uint256 public constant ID_TYPE_2 = 2;
uint256 public constant ID_TYPE_3 = 3;
uint256 public constant ID_TYPE_4 = 4;
uint256 public constant ID_TYPE_5 = 5;
uint256 public constant ID_TYPE_6 = 6;
uint256 public constant ID_TYPE_7 = 7;
uint256 public constant ID_TYPE_8 = 8;
uint256 public constant ID_TYPE_9 = 9;
uint256 public constant ID_TYPE_10 = 10;
/// @notice Returns the address of the UniqueIdentity contract.
function uniqueIdentity() external virtual returns (address);
function go(address account) public view virtual returns (bool);
function goOnlyIdTypes(address account, uint256[] calldata onlyIdTypes) public view virtual returns (bool);
function goSeniorPool(address account) public view virtual returns (bool);
function updateGoldfinchConfig() external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IGoldfinchConfig {
function getNumber(uint256 index) external returns (uint256);
function getAddress(uint256 index) external returns (address);
function setAddress(uint256 index, address newAddress) external returns (address);
function setNumber(uint256 index, uint256 newNumber) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IGoldfinchFactory {
function createCreditLine() external returns (address);
function createBorrower(address owner) external returns (address);
function createPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256[] calldata _allowedUIDTypes
) external returns (address);
function createMigratedPool(
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256[] calldata _allowedUIDTypes
) external returns (address);
function updateGoldfinchConfig() external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
abstract contract IPool {
uint256 public sharePrice;
function deposit(uint256 amount) external virtual;
function withdraw(uint256 usdcAmount) external virtual;
function withdrawInFidu(uint256 fiduAmount) external virtual;
function collectInterestAndPrincipal(
address from,
uint256 interest,
uint256 principal
) public virtual;
function transferFrom(
address from,
address to,
uint256 amount
) public virtual returns (bool);
function drawdown(address to, uint256 amount) public virtual returns (bool);
function sweepToCompound() public virtual;
function sweepFromCompound() public virtual;
function distributeLosses(address creditlineAddress, int256 writedownDelta) external virtual;
function assets() public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC721/IERC721.sol";
interface IPoolTokens is IERC721 {
event TokenMinted(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 amount,
uint256 tranche
);
event TokenRedeemed(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed,
uint256 tranche
);
event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId);
struct TokenInfo {
address pool;
uint256 tranche;
uint256 principalAmount;
uint256 principalRedeemed;
uint256 interestRedeemed;
}
struct MintParams {
uint256 principalAmount;
uint256 tranche;
}
function mint(MintParams calldata params, address to) external returns (uint256);
function redeem(
uint256 tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed
) external;
function withdrawPrincipal(uint256 tokenId, uint256 principalAmount) external;
function burn(uint256 tokenId) external;
function onPoolCreated(address newPool) external;
function getTokenInfo(uint256 tokenId) external view returns (TokenInfo memory);
function validPool(address sender) external view returns (bool);
function isApprovedOrOwner(address spender, uint256 tokenId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ITranchedPool.sol";
abstract contract ISeniorPool {
uint256 public sharePrice;
uint256 public totalLoansOutstanding;
uint256 public totalWritedowns;
function deposit(uint256 amount) external virtual returns (uint256 depositShares);
function depositWithPermit(
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual returns (uint256 depositShares);
function withdraw(uint256 usdcAmount) external virtual returns (uint256 amount);
function withdrawInFidu(uint256 fiduAmount) external virtual returns (uint256 amount);
function sweepToCompound() public virtual;
function sweepFromCompound() public virtual;
function invest(ITranchedPool pool) public virtual;
function estimateInvestment(ITranchedPool pool) public view virtual returns (uint256);
function redeem(uint256 tokenId) public virtual;
function writedown(uint256 tokenId) public virtual;
function calculateWritedown(uint256 tokenId) public view virtual returns (uint256 writedownAmount);
function assets() public view virtual returns (uint256);
function getNumShares(uint256 amount) public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ISeniorPool.sol";
import "./ITranchedPool.sol";
abstract contract ISeniorPoolStrategy {
function getLeverageRatio(ITranchedPool pool) public view virtual returns (uint256);
function invest(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256 amount);
function estimateInvestment(ISeniorPool seniorPool, ITranchedPool pool) public view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface IStakingRewards {
function unstake(uint256 tokenId, uint256 amount) external;
function addToStake(uint256 tokenId, uint256 amount) external;
function stakedBalanceOf(uint256 tokenId) external view returns (uint256);
function depositToCurveAndStakeFrom(
address nftRecipient,
uint256 fiduAmount,
uint256 usdcAmount
) external;
function kick(uint256 tokenId) external;
function accumulatedRewardsPerToken() external view returns (uint256);
function lastUpdateTime() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./IV2CreditLine.sol";
abstract contract ITranchedPool {
IV2CreditLine public creditLine;
uint256 public createdAt;
enum Tranches {
Reserved,
Senior,
Junior
}
struct TrancheInfo {
uint256 id;
uint256 principalDeposited;
uint256 principalSharePrice;
uint256 interestSharePrice;
uint256 lockedUntil;
}
struct PoolSlice {
TrancheInfo seniorTranche;
TrancheInfo juniorTranche;
uint256 totalInterestAccrued;
uint256 principalDeployed;
}
struct SliceInfo {
uint256 reserveFeePercent;
uint256 interestAccrued;
uint256 principalAccrued;
}
struct ApplyResult {
uint256 interestRemaining;
uint256 principalRemaining;
uint256 reserveDeduction;
uint256 oldInterestSharePrice;
uint256 oldPrincipalSharePrice;
}
function initialize(
address _config,
address _borrower,
uint256 _juniorFeePercent,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays,
uint256 _fundableAt,
uint256[] calldata _allowedUIDTypes
) public virtual;
function getTranche(uint256 tranche) external view virtual returns (TrancheInfo memory);
function pay(uint256 amount) external virtual;
function lockJuniorCapital() external virtual;
function lockPool() external virtual;
function initializeNextSlice(uint256 _fundableAt) external virtual;
function totalJuniorDeposits() external view virtual returns (uint256);
function drawdown(uint256 amount) external virtual;
function setFundableAt(uint256 timestamp) external virtual;
function deposit(uint256 tranche, uint256 amount) external virtual returns (uint256 tokenId);
function assess() external virtual;
function depositWithPermit(
uint256 tranche,
uint256 amount,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external virtual returns (uint256 tokenId);
function availableToWithdraw(uint256 tokenId)
external
view
virtual
returns (uint256 interestRedeemable, uint256 principalRedeemable);
function withdraw(uint256 tokenId, uint256 amount)
external
virtual
returns (uint256 interestWithdrawn, uint256 principalWithdrawn);
function withdrawMax(uint256 tokenId)
external
virtual
returns (uint256 interestWithdrawn, uint256 principalWithdrawn);
function withdrawMultiple(uint256[] calldata tokenIds, uint256[] calldata amounts) external virtual;
function numSlices() external view virtual returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./ICreditLine.sol";
abstract contract IV2CreditLine is ICreditLine {
function principal() external view virtual returns (uint256);
function totalInterestAccrued() external view virtual returns (uint256);
function termStartTime() external view virtual returns (uint256);
function setLimit(uint256 newAmount) external virtual;
function setMaxLimit(uint256 newAmount) external virtual;
function setBalance(uint256 newBalance) external virtual;
function setPrincipal(uint256 _principal) external virtual;
function setTotalInterestAccrued(uint256 _interestAccrued) external virtual;
function drawdown(uint256 amount) external virtual;
function assess()
external
virtual
returns (
uint256,
uint256,
uint256
);
function initialize(
address _config,
address owner,
address _borrower,
uint256 _limit,
uint256 _interestApr,
uint256 _paymentPeriodInDays,
uint256 _termInDays,
uint256 _lateFeeApr,
uint256 _principalGracePeriodInDays
) public virtual;
function setTermEndTime(uint256 newTermEndTime) external virtual;
function setNextDueTime(uint256 newNextDueTime) external virtual;
function setInterestOwed(uint256 newInterestOwed) external virtual;
function setPrincipalOwed(uint256 newPrincipalOwed) external virtual;
function setInterestAccruedAsOf(uint256 newInterestAccruedAsOf) external virtual;
function setWritedownAmount(uint256 newWritedownAmount) external virtual;
function setLastFullPaymentTime(uint256 newLastFullPaymentTime) external virtual;
function setLateFeeApr(uint256 newLateFeeApr) external virtual;
function updateGoldfinchConfig() external virtual;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/Initializable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol";
import "./PauserPausable.sol";
/**
* @title BaseUpgradeablePausable contract
* @notice This is our Base contract that most other contracts inherit from. It includes many standard
* useful abilities like ugpradeability, pausability, access control, and re-entrancy guards.
* @author Goldfinch
*/
contract BaseUpgradeablePausable is
Initializable,
AccessControlUpgradeSafe,
PauserPausable,
ReentrancyGuardUpgradeSafe
{
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
using SafeMath for uint256;
// Pre-reserving a few slots in the base contract in case we need to add things in the future.
// This does not actually take up gas cost or storage cost, but it does reserve the storage slots.
// See OpenZeppelin's use of this pattern here:
// https://github.com/OpenZeppelin/openzeppelin-contracts-ethereum-package/blob/master/contracts/GSN/Context.sol#L37
uint256[50] private __gap1;
uint256[50] private __gap2;
uint256[50] private __gap3;
uint256[50] private __gap4;
// solhint-disable-next-line func-name-mixedcase
function __BaseUpgradeablePausable__init(address owner) public initializer {
require(owner != address(0), "Owner cannot be the zero address");
__AccessControl_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
_setupRole(OWNER_ROLE, owner);
_setupRole(PAUSER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./GoldfinchConfig.sol";
import "../../interfaces/IPool.sol";
import "../../interfaces/IFidu.sol";
import "../../interfaces/ISeniorPool.sol";
import "../../interfaces/ISeniorPoolStrategy.sol";
import "../../interfaces/ICreditDesk.sol";
import "../../interfaces/IERC20withDec.sol";
import "../../interfaces/ICUSDCContract.sol";
import "../../interfaces/IPoolTokens.sol";
import "../../interfaces/IBackerRewards.sol";
import "../../interfaces/IGoldfinchFactory.sol";
import "../../interfaces/IGo.sol";
import "../../interfaces/IStakingRewards.sol";
import "../../interfaces/ICurveLP.sol";
/**
* @title ConfigHelper
* @notice A convenience library for getting easy access to other contracts and constants within the
* protocol, through the use of the GoldfinchConfig contract
* @author Goldfinch
*/
library ConfigHelper {
function getPool(GoldfinchConfig config) internal view returns (IPool) {
return IPool(poolAddress(config));
}
function getSeniorPool(GoldfinchConfig config) internal view returns (ISeniorPool) {
return ISeniorPool(seniorPoolAddress(config));
}
function getSeniorPoolStrategy(GoldfinchConfig config) internal view returns (ISeniorPoolStrategy) {
return ISeniorPoolStrategy(seniorPoolStrategyAddress(config));
}
function getUSDC(GoldfinchConfig config) internal view returns (IERC20withDec) {
return IERC20withDec(usdcAddress(config));
}
function getCreditDesk(GoldfinchConfig config) internal view returns (ICreditDesk) {
return ICreditDesk(creditDeskAddress(config));
}
function getFidu(GoldfinchConfig config) internal view returns (IFidu) {
return IFidu(fiduAddress(config));
}
function getFiduUSDCCurveLP(GoldfinchConfig config) internal view returns (ICurveLP) {
return ICurveLP(fiduUSDCCurveLPAddress(config));
}
function getCUSDCContract(GoldfinchConfig config) internal view returns (ICUSDCContract) {
return ICUSDCContract(cusdcContractAddress(config));
}
function getPoolTokens(GoldfinchConfig config) internal view returns (IPoolTokens) {
return IPoolTokens(poolTokensAddress(config));
}
function getBackerRewards(GoldfinchConfig config) internal view returns (IBackerRewards) {
return IBackerRewards(backerRewardsAddress(config));
}
function getGoldfinchFactory(GoldfinchConfig config) internal view returns (IGoldfinchFactory) {
return IGoldfinchFactory(goldfinchFactoryAddress(config));
}
function getGFI(GoldfinchConfig config) internal view returns (IERC20withDec) {
return IERC20withDec(gfiAddress(config));
}
function getGo(GoldfinchConfig config) internal view returns (IGo) {
return IGo(goAddress(config));
}
function getStakingRewards(GoldfinchConfig config) internal view returns (IStakingRewards) {
return IStakingRewards(stakingRewardsAddress(config));
}
function oneInchAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.OneInch));
}
function creditLineImplementationAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CreditLineImplementation));
}
function trustedForwarderAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TrustedForwarder));
}
function configAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchConfig));
}
function poolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Pool));
}
function poolTokensAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.PoolTokens));
}
function backerRewardsAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.BackerRewards));
}
function seniorPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPool));
}
function seniorPoolStrategyAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.SeniorPoolStrategy));
}
function creditDeskAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CreditDesk));
}
function goldfinchFactoryAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GoldfinchFactory));
}
function gfiAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.GFI));
}
function fiduAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Fidu));
}
function fiduUSDCCurveLPAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.FiduUSDCCurveLP));
}
function cusdcContractAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.CUSDCContract));
}
function usdcAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.USDC));
}
function tranchedPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TranchedPoolImplementation));
}
function migratedTranchedPoolAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.MigratedTranchedPoolImplementation));
}
function reserveAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.TreasuryReserve));
}
function protocolAdminAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.ProtocolAdmin));
}
function borrowerImplementationAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.BorrowerImplementation));
}
function goAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.Go));
}
function stakingRewardsAddress(GoldfinchConfig config) internal view returns (address) {
return config.getAddress(uint256(ConfigOptions.Addresses.StakingRewards));
}
function getReserveDenominator(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.ReserveDenominator));
}
function getWithdrawFeeDenominator(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.WithdrawFeeDenominator));
}
function getLatenessGracePeriodInDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LatenessGracePeriodInDays));
}
function getLatenessMaxDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LatenessMaxDays));
}
function getDrawdownPeriodInSeconds(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.DrawdownPeriodInSeconds));
}
function getTransferRestrictionPeriodInDays(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.TransferRestrictionPeriodInDays));
}
function getLeverageRatio(GoldfinchConfig config) internal view returns (uint256) {
return config.getNumber(uint256(ConfigOptions.Numbers.LeverageRatio));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
/**
* @title ConfigOptions
* @notice A central place for enumerating the configurable options of our GoldfinchConfig contract
* @author Goldfinch
*/
library ConfigOptions {
// NEVER EVER CHANGE THE ORDER OF THESE!
// You can rename or append. But NEVER change the order.
enum Numbers {
TransactionLimit,
TotalFundsLimit,
MaxUnderwriterLimit,
ReserveDenominator,
WithdrawFeeDenominator,
LatenessGracePeriodInDays,
LatenessMaxDays,
DrawdownPeriodInSeconds,
TransferRestrictionPeriodInDays,
LeverageRatio
}
enum Addresses {
Pool,
CreditLineImplementation,
GoldfinchFactory,
CreditDesk,
Fidu,
USDC,
TreasuryReserve,
ProtocolAdmin,
OneInch,
TrustedForwarder,
CUSDCContract,
GoldfinchConfig,
PoolTokens,
TranchedPoolImplementation,
SeniorPool,
SeniorPoolStrategy,
MigratedTranchedPoolImplementation,
BorrowerImplementation,
GFI,
Go,
BackerRewards,
StakingRewards,
FiduUSDCCurveLP
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "./BaseUpgradeablePausable.sol";
import "../../interfaces/IGoldfinchConfig.sol";
import "./ConfigOptions.sol";
/**
* @title GoldfinchConfig
* @notice This contract stores mappings of useful "protocol config state", giving a central place
* for all other contracts to access it. For example, the TransactionLimit, or the PoolAddress. These config vars
* are enumerated in the `ConfigOptions` library, and can only be changed by admins of the protocol.
* Note: While this inherits from BaseUpgradeablePausable, it is not deployed as an upgradeable contract (this
* is mostly to save gas costs of having each call go through a proxy)
* @author Goldfinch
*/
contract GoldfinchConfig is BaseUpgradeablePausable {
bytes32 public constant GO_LISTER_ROLE = keccak256("GO_LISTER_ROLE");
mapping(uint256 => address) public addresses;
mapping(uint256 => uint256) public numbers;
mapping(address => bool) public goList;
event AddressUpdated(address owner, uint256 index, address oldValue, address newValue);
event NumberUpdated(address owner, uint256 index, uint256 oldValue, uint256 newValue);
event GoListed(address indexed member);
event NoListed(address indexed member);
bool public valuesInitialized;
function initialize(address owner) public initializer {
require(owner != address(0), "Owner address cannot be empty");
__BaseUpgradeablePausable__init(owner);
_setupRole(GO_LISTER_ROLE, owner);
_setRoleAdmin(GO_LISTER_ROLE, OWNER_ROLE);
}
function setAddress(uint256 addressIndex, address newAddress) public onlyAdmin {
require(addresses[addressIndex] == address(0), "Address has already been initialized");
emit AddressUpdated(msg.sender, addressIndex, addresses[addressIndex], newAddress);
addresses[addressIndex] = newAddress;
}
function setNumber(uint256 index, uint256 newNumber) public onlyAdmin {
emit NumberUpdated(msg.sender, index, numbers[index], newNumber);
numbers[index] = newNumber;
}
function setTreasuryReserve(address newTreasuryReserve) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.TreasuryReserve);
emit AddressUpdated(msg.sender, key, addresses[key], newTreasuryReserve);
addresses[key] = newTreasuryReserve;
}
function setSeniorPoolStrategy(address newStrategy) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.SeniorPoolStrategy);
emit AddressUpdated(msg.sender, key, addresses[key], newStrategy);
addresses[key] = newStrategy;
}
function setCreditLineImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.CreditLineImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setTranchedPoolImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.TranchedPoolImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setBorrowerImplementation(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.BorrowerImplementation);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function setGoldfinchConfig(address newAddress) public onlyAdmin {
uint256 key = uint256(ConfigOptions.Addresses.GoldfinchConfig);
emit AddressUpdated(msg.sender, key, addresses[key], newAddress);
addresses[key] = newAddress;
}
function initializeFromOtherConfig(
address _initialConfig,
uint256 numbersLength,
uint256 addressesLength
) public onlyAdmin {
require(!valuesInitialized, "Already initialized values");
IGoldfinchConfig initialConfig = IGoldfinchConfig(_initialConfig);
for (uint256 i = 0; i < numbersLength; i++) {
setNumber(i, initialConfig.getNumber(i));
}
for (uint256 i = 0; i < addressesLength; i++) {
if (getAddress(i) == address(0)) {
setAddress(i, initialConfig.getAddress(i));
}
}
valuesInitialized = true;
}
/**
* @dev Adds a user to go-list
* @param _member address to add to go-list
*/
function addToGoList(address _member) public onlyGoListerRole {
goList[_member] = true;
emit GoListed(_member);
}
/**
* @dev removes a user from go-list
* @param _member address to remove from go-list
*/
function removeFromGoList(address _member) public onlyGoListerRole {
goList[_member] = false;
emit NoListed(_member);
}
/**
* @dev adds many users to go-list at once
* @param _members addresses to ad to go-list
*/
function bulkAddToGoList(address[] calldata _members) external onlyGoListerRole {
for (uint256 i = 0; i < _members.length; i++) {
addToGoList(_members[i]);
}
}
/**
* @dev removes many users from go-list at once
* @param _members addresses to remove from go-list
*/
function bulkRemoveFromGoList(address[] calldata _members) external onlyGoListerRole {
for (uint256 i = 0; i < _members.length; i++) {
removeFromGoList(_members[i]);
}
}
/*
Using custom getters in case we want to change underlying implementation later,
or add checks or validations later on.
*/
function getAddress(uint256 index) public view returns (address) {
return addresses[index];
}
function getNumber(uint256 index) public view returns (uint256) {
return numbers[index];
}
modifier onlyGoListerRole() {
require(hasRole(GO_LISTER_ROLE, _msgSender()), "Must have go-lister role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts-ethereum-package/contracts/utils/Pausable.sol";
import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol";
/**
* @title PauserPausable
* @notice Inheriting from OpenZeppelin's Pausable contract, this does small
* augmentations to make it work with a PAUSER_ROLE, leveraging the AccessControl contract.
* It is meant to be inherited.
* @author Goldfinch
*/
contract PauserPausable is AccessControlUpgradeSafe, PausableUpgradeSafe {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
// solhint-disable-next-line func-name-mixedcase
function __PauserPausable__init() public initializer {
__Pausable_init_unchained();
}
/**
* @dev Pauses all functions guarded by Pause
*
* See {Pausable-_pause}.
*
* Requirements:
*
* - the caller must have the PAUSER_ROLE.
*/
function pause() public onlyPauserRole {
_pause();
}
/**
* @dev Unpauses the contract
*
* See {Pausable-_unpause}.
*
* Requirements:
*
* - the caller must have the Pauser role
*/
function unpause() public onlyPauserRole {
_unpause();
}
modifier onlyPauserRole() {
require(hasRole(PAUSER_ROLE, _msgSender()), "Must have pauser role to perform this action");
_;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "../../external/ERC721PresetMinterPauserAutoId.sol";
import "./GoldfinchConfig.sol";
import "./ConfigHelper.sol";
import "../../interfaces/ITranchedPool.sol";
import "../../interfaces/IPoolTokens.sol";
/**
* @title PoolTokens
* @notice PoolTokens is an ERC721 compliant contract, which can represent
* junior tranche or senior tranche shares of any of the borrower pools.
* @author Goldfinch
*/
contract PoolTokens is IPoolTokens, ERC721PresetMinterPauserAutoIdUpgradeSafe {
bytes32 public constant OWNER_ROLE = keccak256("OWNER_ROLE");
GoldfinchConfig public config;
using ConfigHelper for GoldfinchConfig;
struct PoolInfo {
uint256 totalMinted;
uint256 totalPrincipalRedeemed;
bool created;
}
// tokenId => tokenInfo
mapping(uint256 => TokenInfo) public tokens;
// poolAddress => poolInfo
mapping(address => PoolInfo) public pools;
event TokenMinted(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 amount,
uint256 tranche
);
event TokenRedeemed(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed,
uint256 tranche
);
event TokenPrincipalWithdrawn(
address indexed owner,
address indexed pool,
uint256 indexed tokenId,
uint256 principalWithdrawn,
uint256 tranche
);
event TokenBurned(address indexed owner, address indexed pool, uint256 indexed tokenId);
event GoldfinchConfigUpdated(address indexed who, address configAddress);
/*
We are using our own initializer function so that OZ doesn't automatically
set owner as msg.sender. Also, it lets us set our config contract
*/
// solhint-disable-next-line func-name-mixedcase
function __initialize__(address owner, GoldfinchConfig _config) external initializer {
require(owner != address(0) && address(_config) != address(0), "Owner and config addresses cannot be empty");
__Context_init_unchained();
__AccessControl_init_unchained();
__ERC165_init_unchained();
// This is setting name and symbol of the NFT's
__ERC721_init_unchained("Goldfinch V2 Pool Tokens", "GFI-V2-PT");
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
config = _config;
_setupRole(PAUSER_ROLE, owner);
_setupRole(OWNER_ROLE, owner);
_setRoleAdmin(PAUSER_ROLE, OWNER_ROLE);
_setRoleAdmin(OWNER_ROLE, OWNER_ROLE);
}
/**
* @notice Called by pool to create a debt position in a particular tranche and amount
* @param params Struct containing the tranche and the amount
* @param to The address that should own the position
* @return tokenId The token ID (auto-incrementing integer across all pools)
*/
function mint(MintParams calldata params, address to)
external
virtual
override
onlyPool
whenNotPaused
returns (uint256 tokenId)
{
address poolAddress = _msgSender();
tokenId = _createToken(params, poolAddress);
_mint(to, tokenId);
config.getBackerRewards().setPoolTokenAccRewardsPerPrincipalDollarAtMint(_msgSender(), tokenId);
emit TokenMinted(to, poolAddress, tokenId, params.principalAmount, params.tranche);
return tokenId;
}
/**
* @notice Updates a token to reflect the principal and interest amounts that have been redeemed.
* @param tokenId The token id to update (must be owned by the pool calling this function)
* @param principalRedeemed The incremental amount of principal redeemed (cannot be more than principal deposited)
* @param interestRedeemed The incremental amount of interest redeemed
*/
function redeem(
uint256 tokenId,
uint256 principalRedeemed,
uint256 interestRedeemed
) external virtual override onlyPool whenNotPaused {
TokenInfo storage token = tokens[tokenId];
address poolAddr = token.pool;
require(token.pool != address(0), "Invalid tokenId");
require(_msgSender() == poolAddr, "Only the token's pool can redeem");
PoolInfo storage pool = pools[poolAddr];
pool.totalPrincipalRedeemed = pool.totalPrincipalRedeemed.add(principalRedeemed);
require(pool.totalPrincipalRedeemed <= pool.totalMinted, "Cannot redeem more than we minted");
token.principalRedeemed = token.principalRedeemed.add(principalRedeemed);
require(
token.principalRedeemed <= token.principalAmount,
"Cannot redeem more than principal-deposited amount for token"
);
token.interestRedeemed = token.interestRedeemed.add(interestRedeemed);
emit TokenRedeemed(ownerOf(tokenId), poolAddr, tokenId, principalRedeemed, interestRedeemed, token.tranche);
}
/** @notice reduce a given pool token's principalAmount and principalRedeemed by a specified amount
* @dev uses safemath to prevent underflow
* @dev this function is only intended for use as part of the v2.6.0 upgrade
* to rectify a bug that allowed users to create a PoolToken that had a
* larger amount of principal than they actually made available to the
* borrower. This bug is fixed in v2.6.0 but still requires past pool tokens
* to have their principal redeemed and deposited to be rectified.
* @param tokenId id of token to decrease
* @param amount amount to decrease by
*/
function reducePrincipalAmount(uint256 tokenId, uint256 amount) external onlyAdmin {
TokenInfo storage tokenInfo = tokens[tokenId];
tokenInfo.principalAmount = tokenInfo.principalAmount.sub(amount);
tokenInfo.principalRedeemed = tokenInfo.principalRedeemed.sub(amount);
}
/**
* @notice Decrement a token's principal amount. This is different from `redeem`, which captures changes to
* principal and/or interest that occur when a loan is in progress.
* @param tokenId The token id to update (must be owned by the pool calling this function)
* @param principalAmount The incremental amount of principal redeemed (cannot be more than principal deposited)
*/
function withdrawPrincipal(uint256 tokenId, uint256 principalAmount)
external
virtual
override
onlyPool
whenNotPaused
{
TokenInfo storage token = tokens[tokenId];
address poolAddr = token.pool;
require(_msgSender() == poolAddr, "Invalid sender");
require(token.principalRedeemed == 0, "Token redeemed");
require(token.principalAmount >= principalAmount, "Insufficient principal");
PoolInfo storage pool = pools[poolAddr];
pool.totalMinted = pool.totalMinted.sub(principalAmount);
require(pool.totalPrincipalRedeemed <= pool.totalMinted, "Cannot withdraw more than redeemed");
token.principalAmount = token.principalAmount.sub(principalAmount);
emit TokenPrincipalWithdrawn(ownerOf(tokenId), poolAddr, tokenId, principalAmount, token.tranche);
}
/**
* @dev Burns a specific ERC721 token, and removes the data from our mappings
* @param tokenId uint256 id of the ERC721 token to be burned.
*/
function burn(uint256 tokenId) external virtual override whenNotPaused {
TokenInfo memory token = _getTokenInfo(tokenId);
bool canBurn = _isApprovedOrOwner(_msgSender(), tokenId);
bool fromTokenPool = _validPool(_msgSender()) && token.pool == _msgSender();
address owner = ownerOf(tokenId);
require(canBurn || fromTokenPool, "ERC721Burnable: caller cannot burn this token");
require(token.principalRedeemed == token.principalAmount, "Can only burn fully redeemed tokens");
_destroyAndBurn(tokenId);
emit TokenBurned(owner, token.pool, tokenId);
}
function getTokenInfo(uint256 tokenId) external view virtual override returns (TokenInfo memory) {
return _getTokenInfo(tokenId);
}
/**
* @notice Called by the GoldfinchFactory to register the pool as a valid pool. Only valid pools can mint/redeem
* tokens
* @param newPool The address of the newly created pool
*/
function onPoolCreated(address newPool) external override onlyGoldfinchFactory {
pools[newPool].created = true;
}
/**
* @notice Returns a boolean representing whether the spender is the owner or the approved spender of the token
* @param spender The address to check
* @param tokenId The token id to check for
* @return True if approved to redeem/transfer/burn the token, false if not
*/
function isApprovedOrOwner(address spender, uint256 tokenId) external view override returns (bool) {
return _isApprovedOrOwner(spender, tokenId);
}
function validPool(address sender) public view virtual override returns (bool) {
return _validPool(sender);
}
function _createToken(MintParams calldata params, address poolAddress) internal returns (uint256 tokenId) {
PoolInfo storage pool = pools[poolAddress];
_tokenIdTracker.increment();
tokenId = _tokenIdTracker.current();
tokens[tokenId] = TokenInfo({
pool: poolAddress,
tranche: params.tranche,
principalAmount: params.principalAmount,
principalRedeemed: 0,
interestRedeemed: 0
});
pool.totalMinted = pool.totalMinted.add(params.principalAmount);
return tokenId;
}
function _destroyAndBurn(uint256 tokenId) internal {
delete tokens[tokenId];
_burn(tokenId);
}
function _validPool(address poolAddress) internal view virtual returns (bool) {
return pools[poolAddress].created;
}
function _getTokenInfo(uint256 tokenId) internal view returns (TokenInfo memory) {
return tokens[tokenId];
}
/**
* @notice Migrates to a new goldfinch config address
*/
function updateGoldfinchConfig() external onlyAdmin {
config = GoldfinchConfig(config.configAddress());
emit GoldfinchConfigUpdated(msg.sender, address(config));
}
modifier onlyAdmin() {
require(isAdmin(), "Must have admin role to perform this action");
_;
}
function isAdmin() public view returns (bool) {
return hasRole(OWNER_ROLE, _msgSender());
}
modifier onlyGoldfinchFactory() {
require(_msgSender() == config.goldfinchFactoryAddress(), "Only Goldfinch factory is allowed");
_;
}
modifier onlyPool() {
require(_validPool(_msgSender()), "Invalid pool!");
_;
}
}
|
Burns a specific ERC721 token, and removes the data from our mappings tokenId uint256 id of the ERC721 token to be burned./
|
function burn(uint256 tokenId) external virtual override whenNotPaused {
TokenInfo memory token = _getTokenInfo(tokenId);
bool canBurn = _isApprovedOrOwner(_msgSender(), tokenId);
bool fromTokenPool = _validPool(_msgSender()) && token.pool == _msgSender();
address owner = ownerOf(tokenId);
require(canBurn || fromTokenPool, "ERC721Burnable: caller cannot burn this token");
require(token.principalRedeemed == token.principalAmount, "Can only burn fully redeemed tokens");
_destroyAndBurn(tokenId);
emit TokenBurned(owner, token.pool, tokenId);
}
| 6,890,081 |
./partial_match/137/0x3fFD3d584Eb4Ee6b8D2e3B420555A953af6a2D3d/sources/MarbleNFTCandidate.sol
|
Returns true if URI is already a candidate. Otherwise false. _uri URI to check/
|
function isCandidate(string _uri)
external
view
returns(bool isIndeed)
{
return _isCandidate(_uri);
}
| 3,530,664 |
./full_match/42/0x2B144997Bafca3A3a63B9acFE03DeD3Bc7DC9ACe/sources/managedVulcanDistributionContract_v2.sol
|
'balance' function will simply return the amount currently held in escrow
|
function balance() public view returns (uint) {
return address(this).balance;
}
| 16,264,042 |
pragma solidity ^0.5.0;
// Copyright 2019 OpenST Ltd.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// ----------------------------------------------------------------------------
//
// http://www.simpletoken.org/
//
// ----------------------------------------------------------------------------
import "../lib/EIP20Interface.sol";
import "../lib/GatewayLib.sol";
import "../lib/MessageBus.sol";
import "../lib/OrganizationInterface.sol";
import "../lib/Organized.sol";
import "../lib/SafeMath.sol";
import "../lib/StateRootInterface.sol";
/**
* @title GatewayBase is the base contract for EIP20Gateway and EIP20CoGateway.
*/
contract GatewayBase is Organized {
/* Usings */
using SafeMath for uint256;
/* Events */
/**
* Emitted whenever a Gateway/CoGateway contract is proven.
* wasAlreadyProved parameter differentiates between first call and replay
* call of proveGateway method for same block height.
*/
event GatewayProven(
address _gateway,
uint256 _blockHeight,
bytes32 _storageRoot,
bool _wasAlreadyProved
);
event BountyChangeInitiated(
uint256 _currentBounty,
uint256 _proposedBounty,
uint256 _unlockHeight
);
event BountyChangeConfirmed(
uint256 _currentBounty,
uint256 _changedBounty
);
/* Constants */
/** Position of message bus in the storage. */
uint8 constant MESSAGE_BOX_OFFSET = 7;
/**
* Penalty in bounty amount percentage charged to message sender on revert message.
*/
uint8 constant REVOCATION_PENALTY = 150;
//todo identify how to get block time for both chains
/**
* Unlock period of 7-days for change bounty in block height.
* Considering aux block generation time per block is 3-secs.
*/
uint256 public constant BOUNTY_CHANGE_UNLOCK_PERIOD = 201600;
/* Public Variables */
/**
* Address of contract which implements StateRootInterface.
*/
StateRootInterface public stateRootProvider;
/** Path to make Merkle account proof for Gateway/CoGateway contract. */
bytes public encodedGatewayPath;
/**
* Remote gateway contract address. If this is a gateway contract, then the
* remote gateway is a CoGateway and vice versa.
*/
address public remoteGateway;
/** Amount of ERC20 which is staked by facilitator. */
uint256 public bounty;
/** Proposed new bounty amount for bounty change. */
uint256 public proposedBounty;
/** Bounty proposal block height. */
uint256 public proposedBountyUnlockHeight;
/* Internal Variables */
/**
* Message box.
* @dev Keep this is at location 1, in case this is changed then update
* constant MESSAGE_BOX_OFFSET accordingly.
*/
MessageBus.MessageBox internal messageBox;
/** Maps messageHash to the Message object. */
mapping(bytes32 => MessageBus.Message) public messages;
/** Maps blockHeight to storageRoot. */
mapping(uint256 => bytes32) internal storageRoots;
/* Private Variables */
/**
* Maps address to message hash.
*
* Once the inbox process is started the corresponding
* message hash is stored against the address starting process.
* This is used to restrict simultaneous/multiple process
* for a particular address. This is also used to determine the
* nonce of the particular address. Refer getNonce for the details.
*/
mapping(address => bytes32) private inboxActiveProcess;
/**
* Maps address to message hash.
*
* Once the outbox process is started the corresponding
* message hash is stored against the address starting process.
* This is used to restrict simultaneous/multiple process
* for a particular address. This is also used to determine the
* nonce of the particular address. Refer getNonce for the details.
*/
mapping(address => bytes32) private outboxActiveProcess;
/* Constructor */
/**
* @notice Initialize the contract and set default values.
*
* @param _stateRootProvider Contract address which implements
* StateRootInterface.
* @param _bounty The amount that facilitator will stakes to initiate the
* message transfers.
* @param _organization Address of an organization contract.
*/
constructor(
StateRootInterface _stateRootProvider,
uint256 _bounty,
OrganizationInterface _organization
)
Organized(_organization)
public
{
require(
address(_stateRootProvider) != address(0),
"State root provider contract address must not be zero."
);
stateRootProvider = _stateRootProvider;
bounty = _bounty;
// The following variables are not known at construction:
messageBox = MessageBus.MessageBox();
encodedGatewayPath = '';
remoteGateway = address(0);
}
/* External Functions */
/**
* @notice This can be called by anyone to verify merkle proof of
* gateway/co-gateway contract address. Trust factor is brought by
* state roots of the contract which implements StateRootInterface.
* It's important to note that in replay calls of proveGateway
* bytes _rlpParentNodes variable is not validated. In this case
* input storage root derived from merkle proof account nodes is
* verified with stored storage root of given blockHeight.
* GatewayProven event has parameter wasAlreadyProved to
* differentiate between first call and replay calls.
*
* @param _blockHeight Block height at which Gateway/CoGateway is to be
* proven.
* @param _rlpAccount RLP encoded account node object.
* @param _rlpParentNodes RLP encoded value of account proof parent nodes.
*
* @return `true` if Gateway account is proved
*/
function proveGateway(
uint256 _blockHeight,
bytes calldata _rlpAccount,
bytes calldata _rlpParentNodes
)
external
returns (bool /* success */)
{
// _rlpAccount should be valid
require(
_rlpAccount.length != 0,
"Length of RLP account must not be 0."
);
// _rlpParentNodes should be valid
require(
_rlpParentNodes.length != 0,
"Length of RLP parent nodes is 0"
);
bytes32 stateRoot = stateRootProvider.getStateRoot(_blockHeight);
// State root should be present for the block height
require(
stateRoot != bytes32(0),
"State root must not be zero"
);
// If account already proven for block height
bytes32 provenStorageRoot = storageRoots[_blockHeight];
if (provenStorageRoot != bytes32(0)) {
// wasAlreadyProved is true here since proveOpenST is replay call
// for same block height
emit GatewayProven(
remoteGateway,
_blockHeight,
provenStorageRoot,
true
);
// return true
return true;
}
bytes32 storageRoot = GatewayLib.proveAccount(
_rlpAccount,
_rlpParentNodes,
encodedGatewayPath,
stateRoot
);
storageRoots[_blockHeight] = storageRoot;
// wasAlreadyProved is false since Gateway is called for the first time
// for a block height
emit GatewayProven(
remoteGateway,
_blockHeight,
storageRoot,
false
);
return true;
}
/**
* @notice Get the nonce for the given account address
*
* @param _account Account address for which the nonce is to fetched
*
* @return nonce
*/
function getNonce(address _account)
external
view
returns (uint256)
{
// call the private method
return _getOutboxNonce(_account);
}
/**
* @notice Method allows organization to propose new bounty amount.
*
* @param _proposedBounty proposed bounty amount.
*
* @return uint256 proposed bounty amount.
*/
function initiateBountyAmountChange(uint256 _proposedBounty)
external
onlyOrganization
returns(uint256)
{
return initiateBountyAmountChangeInternal(_proposedBounty, BOUNTY_CHANGE_UNLOCK_PERIOD);
}
/**
* @notice Method allows organization to confirm proposed bounty amount
* after unlock period.
*
* @return changedBountyAmount_ updated bounty amount.
* @return previousBountyAmount_ previous bounty amount.
*/
function confirmBountyAmountChange()
external
onlyOrganization
returns (
uint256 changedBountyAmount_,
uint256 previousBountyAmount_
)
{
require(
proposedBounty != bounty,
"Proposed bounty should be different from existing bounty."
);
require(
proposedBountyUnlockHeight < block.number,
"Confirm bounty amount change can only be done after unlock period."
);
changedBountyAmount_ = proposedBounty;
previousBountyAmount_ = bounty;
bounty = proposedBounty;
proposedBounty = 0;
proposedBountyUnlockHeight = 0;
emit BountyChangeConfirmed(previousBountyAmount_, changedBountyAmount_);
}
/**
* @notice Method to get the outbox message status for the given message
* hash. If message hash does not exist then it will return
* undeclared status.
*
* @param _messageHash Message hash to get the status.
*
* @return status_ Message status.
*/
function getOutboxMessageStatus(
bytes32 _messageHash
)
external
view
returns (MessageBus.MessageStatus status_)
{
status_ = messageBox.outbox[_messageHash];
}
/**
* @notice Method to get the inbox message status for the given message
* hash. If message hash does not exist then it will return
* undeclared status.
*
* @param _messageHash Message hash to get the status.
*
* @return status_ Message status.
*/
function getInboxMessageStatus(
bytes32 _messageHash
)
external
view
returns (MessageBus.MessageStatus status_)
{
status_ = messageBox.inbox[_messageHash];
}
/**
* @notice Method to get the active message hash and its status from inbox
* for the given account address. If message hash does not exist
* for the given account address then it will return zero hash and
* undeclared status.
*
* @param _account Account address.
*
* @return messageHash_ Message hash.
* @return status_ Message status.
*/
function getInboxActiveProcess(
address _account
)
external
view
returns (
bytes32 messageHash_,
MessageBus.MessageStatus status_
)
{
messageHash_ = inboxActiveProcess[_account];
status_ = messageBox.inbox[messageHash_];
}
/**
* @notice Method to get the active message hash and its status from outbox
* for the given account address. If message hash does not exist
* for the given account address then it will return zero hash and
* undeclared status.
*
* @param _account Account address.
*
* @return messageHash_ Message hash.
* @return status_ Message status.
*/
function getOutboxActiveProcess(
address _account
)
external
view
returns (
bytes32 messageHash_,
MessageBus.MessageStatus status_
)
{
messageHash_ = outboxActiveProcess[_account];
status_ = messageBox.outbox[messageHash_];
}
/* Internal Functions */
/**
* @notice Calculate the fee amount which is rewarded to facilitator for
* performing message transfers.
*
* @param _gasConsumed Gas consumption during message confirmation.
* @param _gasLimit Maximum amount of gas can be used for reward.
* @param _gasPrice Gas price at which reward is calculated.
* @param _initialGas Initial gas at the start of the process.
*
* @return fee_ Fee amount.
* @return totalGasConsumed_ Total gas consumed during message transfer.
*/
function feeAmount(
uint256 _gasConsumed,
uint256 _gasLimit,
uint256 _gasPrice,
uint256 _initialGas
)
internal
view
returns (
uint256 fee_,
uint256 totalGasConsumed_
)
{
totalGasConsumed_ = _initialGas.add(
_gasConsumed
).sub(
gasleft()
);
if (totalGasConsumed_ < _gasLimit) {
fee_ = totalGasConsumed_.mul(_gasPrice);
} else {
fee_ = _gasLimit.mul(_gasPrice);
}
}
/**
* @notice Create and return Message object.
*
* @dev This function is to avoid stack too deep error.
*
* @param _intentHash Intent hash
* @param _accountNonce Nonce for the account address
* @param _gasPrice Gas price
* @param _gasLimit Gas limit
* @param _account Account address
* @param _hashLock Hash lock
*
* @return Message object
*/
function getMessage(
bytes32 _intentHash,
uint256 _accountNonce,
uint256 _gasPrice,
uint256 _gasLimit,
address _account,
bytes32 _hashLock
)
internal
pure
returns (MessageBus.Message memory)
{
return MessageBus.Message({
intentHash : _intentHash,
nonce : _accountNonce,
gasPrice : _gasPrice,
gasLimit : _gasLimit,
sender : _account,
hashLock : _hashLock,
gasConsumed : 0
});
}
/**
* @notice Internal function to get the outbox nonce for the given account
* address
*
* @param _account Account address for which the nonce is to fetched
*
* @return nonce
*/
function _getOutboxNonce(address _account)
internal
view
returns (uint256 /* nonce */)
{
bytes32 previousProcessMessageHash = outboxActiveProcess[_account];
return getMessageNonce(previousProcessMessageHash);
}
/**
* @notice Internal function to get the inbox nonce for the given account
* address.
*
* @param _account Account address for which the nonce is to fetched
*
* @return nonce
*/
function _getInboxNonce(address _account)
internal
view
returns (uint256 /* nonce */)
{
bytes32 previousProcessMessageHash = inboxActiveProcess[_account];
return getMessageNonce(previousProcessMessageHash);
}
/**
* @notice Stores a message at its hash in the messages mapping.
*
* @param _message The message to store.
*
* @return messageHash_ The hash that represents the given message.
*/
function storeMessage(
MessageBus.Message memory _message
)
internal
returns (bytes32 messageHash_)
{
messageHash_ = MessageBus.messageDigest(
_message.intentHash,
_message.nonce,
_message.gasPrice,
_message.gasLimit,
_message.sender,
_message.hashLock
);
messages[messageHash_] = _message;
}
/**
* @notice Clears the previous outbox process. Validates the
* nonce. Updates the process with new process
*
* @param _account Account address
* @param _nonce Nonce for the account address
* @param _messageHash Message hash
*/
function registerOutboxProcess(
address _account,
uint256 _nonce,
bytes32 _messageHash
)
internal
{
require(
_nonce == _getOutboxNonce(_account),
"Invalid nonce."
);
bytes32 previousMessageHash = outboxActiveProcess[_account];
if (previousMessageHash != bytes32(0)) {
MessageBus.MessageStatus status =
messageBox.outbox[previousMessageHash];
require(
status == MessageBus.MessageStatus.Progressed ||
status == MessageBus.MessageStatus.Revoked,
"Previous process is not completed."
);
delete messages[previousMessageHash];
}
// Update the active process.
outboxActiveProcess[_account] = _messageHash;
}
/**
* @notice Clears the previous outbox process. Validates the
* nonce. Updates the process with new process.
*
* @param _account Account address.
* @param _nonce Nonce for the account address.
* @param _messageHash Message hash.
*/
function registerInboxProcess(
address _account,
uint256 _nonce,
bytes32 _messageHash
)
internal
{
require(
_nonce == _getInboxNonce(_account),
"Invalid nonce"
);
bytes32 previousMessageHash = inboxActiveProcess[_account];
if (previousMessageHash != bytes32(0)) {
MessageBus.MessageStatus status =
messageBox.inbox[previousMessageHash];
require(
status == MessageBus.MessageStatus.Progressed ||
status == MessageBus.MessageStatus.Revoked,
"Previous process is not completed"
);
delete messages[previousMessageHash];
}
// Update the active process.
inboxActiveProcess[_account] = _messageHash;
}
/**
* @notice Calculates the penalty amount for reverting a message transfer.
*
* @param _bounty The amount that facilitator has staked to initiate the
* message transfers.
*
* @return penalty_ Amount of penalty needs to be paid by message initiator
* to revert message transfers.
*/
function penaltyFromBounty(uint256 _bounty)
internal
pure
returns(uint256 penalty_)
{
penalty_ = _bounty.mul(REVOCATION_PENALTY).div(100);
}
/**
* Internal method to propose new bounty. This is added for large block
* heights value for unlocking bounty change.
*
* @param _proposedBounty proposed bounty amount.
* @param _bountyChangePeriod Unlock period for change bounty in
* block height.
*
* @return uint256 proposed bounty amount.
*/
function initiateBountyAmountChangeInternal(
uint256 _proposedBounty,
uint256 _bountyChangePeriod
)
internal
returns(uint256)
{
proposedBounty = _proposedBounty;
proposedBountyUnlockHeight = block.number.add(_bountyChangePeriod);
emit BountyChangeInitiated(
bounty,
_proposedBounty,
proposedBountyUnlockHeight
);
return _proposedBounty;
}
/* Private Functions */
/**
* @notice Returns the next nonce of inbox or outbox process
*
* @param _messageHash Message hash
*
* @return _nonce nonce of next inbox or outbox process
*/
function getMessageNonce(bytes32 _messageHash)
private
view
returns(uint256)
{
if (_messageHash == bytes32(0)) {
return 1;
}
MessageBus.Message storage message =
messages[_messageHash];
return message.nonce.add(1);
}
}
|
Create and return Message object. This function is to avoid stack too deep error. _intentHash Intent hash _accountNonce Nonce for the account address _gasPrice Gas price _gasLimit Gas limit _account Account address _hashLock Hash lock return Message object/
|
function getMessage(
bytes32 _intentHash,
uint256 _accountNonce,
uint256 _gasPrice,
uint256 _gasLimit,
address _account,
bytes32 _hashLock
)
internal
pure
returns (MessageBus.Message memory)
{
return MessageBus.Message({
intentHash : _intentHash,
nonce : _accountNonce,
gasPrice : _gasPrice,
gasLimit : _gasLimit,
sender : _account,
hashLock : _hashLock,
gasConsumed : 0
});
}
| 6,370,388 |
// contracts/Blog.sol
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "hardhat/console.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
contract Blog {
string public name;
address public owner;
using Counters for Counters.Counter;
Counters.Counter private _postIds;
struct Post {
uint256 id;
string title;
string content;
bool published;
}
/* mappings can be seen as hash tables */
/* here we create lookups for posts by id and posts by ipfs hash */
mapping(uint256 => Post) private idToPost;
mapping(string => Post) private hashToPost;
/* events facilitate communication between smart contractsand their user interfaces */
/* i.e. we can create listeners for events in the client and also use them in The Graph */
event PostCreated(uint256 id, string title, string hash);
event PostUpdated(uint256 id, string title, string hash, bool published);
/* when the blog is deployed, give it a name */
/* also set the creator as the owner of the contract */
constructor(string memory _name) {
console.log("Deploying Blog with name:", _name);
name = _name;
owner = msg.sender;
}
/* this modifier means only the contract owner can */
/* invoke the function */
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/* updates the blog name */
function updateName(string memory _name) public {
name = _name;
}
/* transfers ownership of the contract to another address */
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
/* fetches an individual post by the content hash */
function fetchPost(string memory hash) public view returns (Post memory) {
return hashToPost[hash];
}
/* creates a new post */
function createPost(string memory title, string memory hash)
public
onlyOwner
{
_postIds.increment();
uint256 postId = _postIds.current();
Post storage post = idToPost[postId];
post.id = postId;
post.title = title;
post.published = true;
post.content = hash;
hashToPost[hash] = post;
emit PostCreated(postId, title, hash);
}
/* updates an existing post */
function updatePost(
uint256 postId,
string memory title,
string memory hash,
bool published
) public onlyOwner {
Post storage post = idToPost[postId];
post.title = title;
post.published = published;
post.content = hash;
idToPost[postId] = post;
hashToPost[hash] = post;
emit PostUpdated(post.id, title, hash, published);
}
/* fetches all posts */
function fetchPosts() public view returns (Post[] memory) {
uint256 itemCount = _postIds.current();
Post[] memory posts = new Post[](itemCount);
for (uint256 i = 0; i < itemCount; i++) {
uint256 currentId = i + 1;
Post storage currentItem = idToPost[currentId];
posts[i] = currentItem;
}
return posts;
}
}
|
fetches an individual post by the content hash /
|
function fetchPost(string memory hash) public view returns (Post memory) {
return hashToPost[hash];
}
| 909,227 |
./full_match/1/0x44ae17e3C828D068D54093bfb72e4f005C4701ec/sources/contracts/EquityPool.sol
|
Gets all stakeholders of the contract as well as their stake return _holders An array of addresses of the stakeholders return _equityTokens An array of equity tokens
|
function getStakeHolders()
external
view
returns (address[] memory _holders, uint256[] memory _equityTokens)
{
_holders = new address[](stakeHolderAddresses.length);
_holders = stakeHolderAddresses;
_equityTokens = new uint256[](_holders.length);
for (uint256 i = 0; i < _holders.length; i++) {
_equityTokens[i] = stakeHolders[_holders[i]].equityTokens;
}
return (_holders, _equityTokens);
}
| 9,603,685 |
pragma solidity ^0.4.18;
contract Ownable {
// Contract's owner.
address owner;
modifier onlyOwner() {
require (msg.sender == owner);
_;
}
// Constructor.
function Ownable() public {
owner = msg.sender;
}
// Returns current contract's owner.
function getOwner() public constant returns(address) {
return owner;
}
// Transfers contract's ownership.
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
owner = newOwner;
}
}
contract ICKBase {
function ownerOf(uint256) public pure returns (address);
}
contract IKittyKendoStorage {
function createProposal(uint proposal, address proposalOwner) public;
function createVoter(address account) public;
function updateProposalOwner(uint proposal, address voter) public;
function voterExists(address voter) public constant returns (bool);
function proposalExists(uint proposal) public constant returns (bool);
function proposalOwner(uint proposal) public constant returns (address);
function proposalCreateTime(uint proposal) public constant returns (uint);
function voterVotingTime(address voter) public constant returns (uint);
function addProposalVote(uint proposal, address voter) public;
function addVoterVote(address voter) public;
function updateVoterTimes(address voter, uint time) public;
function getProposalTTL() public constant returns (uint);
function setProposalTTL(uint time) public;
function getVotesPerProposal() public constant returns (uint);
function setVotesPerProposal(uint votes) public;
function getTotalProposalsCount() public constant returns(uint);
function getTotalVotersCount() public constant returns(uint);
function getProposalVotersCount(uint proposal) public constant returns(uint);
function getProposalVotesCount(uint proposal) public constant returns(uint);
function getProposalVoterVotesCount(uint proposal, address voter) public constant returns(uint);
function getVoterProposalsCount(address voter) public constant returns(uint);
function getVoterVotesCount(address voter) public constant returns(uint);
function getVoterProposal(address voter, uint index) public constant returns(uint);
}
contract KittyKendoCore is Ownable {
IKittyKendoStorage kks;
address kksAddress;
// Event is emitted when new votes have been recorded.
event VotesRecorded (
address indexed from,
uint[] votes
);
// Event is emitted when new proposal has been added.
event ProposalAdded (
address indexed from,
uint indexed proposal
);
// Registering fee.
uint fee;
// Constructor.
function KittyKendoCore() public {
fee = 0;
kksAddress = address(0);
}
// Returns storage's address.
function storageAddress() onlyOwner public constant returns(address) {
return kksAddress;
}
// Sets storage's address.
function setStorageAddress(address addr) onlyOwner public {
kksAddress = addr;
kks = IKittyKendoStorage(kksAddress);
}
// Returns default register fee.
function getFee() public constant returns(uint) {
return fee;
}
// Sets default register fee.
function setFee(uint val) onlyOwner public {
fee = val;
}
// Contract balance withdrawal.
function withdraw(uint amount) onlyOwner public {
require(amount <= address(this).balance);
owner.transfer(amount);
}
// Returns contract's balance.
function getBalance() onlyOwner public constant returns(uint) {
return address(this).balance;
}
// Registering proposal in replacement for provided votes.
function registerProposal(uint proposal, uint[] votes) public payable {
// Value must be at least equal to default fee.
require(msg.value >= fee);
recordVotes(votes);
if (proposal > 0) {
addProposal(proposal);
}
}
// Recording proposals votes.
function recordVotes(uint[] votes) private {
require(kksAddress != address(0));
// Checking if voter already exists, otherwise adding it.
if (!kks.voterExists(msg.sender)) {
kks.createVoter(msg.sender);
}
// Recording all passed votes from voter.
for (uint i = 0; i < votes.length; i++) {
// Checking if proposal exists.
if (kks.proposalExists(votes[i])) {
// Proposal owner can't vote for own proposal.
require(kks.proposalOwner(votes[i]) != msg.sender);
// Checking if proposal isn't expired yet.
if (kks.proposalCreateTime(votes[i]) + kks.getProposalTTL() <= now) {
continue;
}
// Voter can vote for each proposal only once.
require(kks.getProposalVoterVotesCount(votes[i], msg.sender) == uint(0));
// Adding proposal's voter and updating total votes count per proposal.
kks.addProposalVote(votes[i], msg.sender);
}
// Recording vote per voter.
kks.addVoterVote(msg.sender);
}
// Updating voter's last voting time and updating create time for voter's proposals.
kks.updateVoterTimes(msg.sender, now);
// Emitting event.
VotesRecorded(msg.sender, votes);
}
// Adding new voter's proposal.
function addProposal(uint proposal) private {
require(kksAddress != address(0));
// Only existing voters can add own proposals.
require(kks.voterExists(msg.sender));
// Checking if voter has enough votes count to add own proposal.
require(kks.getVoterVotesCount(msg.sender) / kks.getVotesPerProposal() > kks.getVoterProposalsCount(msg.sender));
// Prevent voter from adding own proposal's too often.
//require(now - kks.voterVotingTime(msg.sender) > 1 minutes);
// Checking if proposal(i.e. Crypto Kitty Token) belongs to sender.
require(getCKOwner(proposal) == msg.sender);
// Checking if proposal already exists.
if (!kks.proposalExists(proposal)) {
// Adding new proposal.
kks.createProposal(proposal, msg.sender);
} else {
// Updating proposal's owner.
kks.updateProposalOwner(proposal, msg.sender);
}
// Emitting event.
ProposalAdded(msg.sender, proposal);
}
// Returns the CryptoKitty's owner address.
function getCKOwner(uint proposal) private pure returns(address) {
ICKBase ckBase = ICKBase(0x06012c8cf97BEaD5deAe237070F9587f8E7A266d);
return ckBase.ownerOf(uint256(proposal));
}
}
|
Returns storage's address.
|
function storageAddress() onlyOwner public constant returns(address) {
return kksAddress;
}
| 57,354 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "./OwnedRanges.sol";
interface IERC2309 {
event ConsecutiveTransfer(uint indexed fromTokenId, uint toTokenId, address indexed fromAddress, address indexed toAddress);
event TransferForLots(uint fromTokenId, uint toTokenId, address indexed fromAddress, address indexed toAddress);
}
/*
function _init(address to, uint number_of_tokens) internal virtual {
owners.init(to, number_of_tokens, number_of_tokens / 3);
emit ConsecutiveTransfer(0, number_of_tokens, address(0), to);
}
function _transferFotLots(address to, uint fromTokenId, uint toTokenId) internal virtual {
owners.init(to, number_of_tokens, number_of_tokens / 3);
emit TransferForLots(fromTokenId, toTokenId, msg.sender, to);
}
*/
contract NFTsERC2309 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable, IERC2309 {
using SafeMath for uint;
using Address for address;
using EnumerableSet for EnumerableSet.UintSet;
using EnumerableMap for EnumerableMap.UintToAddressMap;
using Strings for uint;
using OwnedRanges for OwnedRanges.OwnedRangesMapping;
// Equals to `bytes4(keccak("onERC721Received(address,address,uint,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
OwnedRanges.OwnedRangesMapping private owners;
// Mapping from token ID to approved address
mapping (uint => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) private _operatorApprovals;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping (address => EnumerableSet.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMap.UintToAddressMap private _tokenOwners;
// Optional mapping for token URIs
mapping (uint => string) private _tokenURIs;
string private _name;
string private _symbol;
// Base URI
string private _baseURI;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
address public contractOwner;
modifier onlyOwner() {
require(msg.sender == contractOwner, "require is not owner");
_;
}
// **************************************
// ************ CONSTRUCTOR *************
// **************************************
constructor (string memory name_, string memory symbol_, uint cant, string memory baseURI_) {
_name = name_;
_symbol = symbol_;
contractOwner = msg.sender;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
_init(msg.sender, cant);
_setBaseURI(baseURI_);
}
//IERC721-balanceOf
function balanceOf(address owner) public view virtual override returns(uint) {
require(owner != address(0), "ERC721: balance query for the zero address");
return owners.ownerBalance(owner);
}
//IERC721-ownerOf
function ownerOf(uint tokenId) public view virtual override returns(address) {
//(bool success, bytes32 value) = _tokenOwners.tryGet(tokenId)
//return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
return owners.ownerOf(tokenId);
}
//IERC721Metadata-name
function name() public view virtual override returns(string memory) {
return _name;
}
//IERC721Metadata-symbol
function symbol() public view virtual override returns(string memory) {
return _symbol;
}
//IERC721Metadata-tokenURI
function tokenURI(uint tokenId) public view virtual override returns(string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
//returnsthe base URI set via {_setBaseURI}. This will be automatically added as a prefix in {tokenURI} to each token's URI
function baseURI() public view virtual returns(string memory) {
return _baseURI;
}
/*returnsthe base URI set via {_setBaseURI}. This will be automatically added as a prefix in {tokenURI} to each token's URI
function setbaseURI(string memory baseURI) public virtual returns(string bool) {
return true;
}
*/
//IERC721Enumerable-tokenOfOwnerByIndex
function tokenOfOwnerByIndex(address owner, uint index) public view virtual override returns(uint) {
return owners.ownedIndexToIdx(owner, index);
}
//IERC721Enumerable-totalSupply
function totalSupply() public view virtual override returns(uint) {
// _tokenOwners are indexed by tokenIds, so .length() returnsthe number of tokenIds
return owners.length();
}
//IERC721Enumerable-tokenByIndex
function tokenByIndex(uint index) public view virtual override returns(uint) {
return index;
}
//IERC721-approve
function approve(address to, uint tokenId) public virtual override {
address owner = NFTsERC2309.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(_msgSender() == owner || NFTsERC2309.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
//IERC721-getApproved
function getApproved(uint tokenId) public view virtual override returns(address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
//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);
}
//IERC721-isApprovedForAll
function isApprovedForAll(address owner, address operator) public view virtual override returns(bool) {
//return _operatorApprovals[owner][operator];
require(!_operatorApprovals[owner][operator]);
return true;
}
//IERC721-transferFrom
function transferFrom(address from, address to, uint tokenId) public virtual onlyOwner override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
//IERC721-safeTransferFrom
function safeTransferFrom(address from, address to, uint tokenId) public virtual onlyOwner override {
safeTransferFrom(from, to, tokenId, "");
}
//IERC721-safeTransferFrom
function safeTransferFrom(address from, address to, uint tokenId, bytes memory _data) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
//Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
//`_data` is additional data, it has no specified format and it is sent in call to `to`.
function _safeTransfer(address from, address to, uint tokenId, bytes memory _data) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
//returnswhether `tokenId` exists.
//Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
function _exists(uint tokenId) internal view virtual returns(bool) {
return owners.length() > tokenId;
}
//returnswhether `spender` is allowed to manage `tokenId`.
function _isApprovedOrOwner(address spender, uint tokenId) internal view virtual returns(bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = NFTsERC2309.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || NFTsERC2309.isApprovedForAll(owner, spender));
}
//Safely mints `tokenId` and transfers it to `to`.
function _safeMint(address to, uint tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
//Same as ERC721-_safeMint-address-uint-}[`_safeMint`] with an additional `data` parameter which is
function _safeMint(address to, uint tokenId, bytes memory _data) internal virtual {
_mint(to, tokenId);
require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
//Mints `tokenId` and transfers it to `to`, but usage of this method is discouraged, use {_safeMint} whenever possible
function _mint(address to, uint tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
// Burn `tokenId`.
function _burn(uint tokenId) internal virtual {
address owner = ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
//Transfers `tokenId` from `from` to `to`.
//As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
function _transfer(address from, address to, uint tokenId) internal virtual {
require(NFTsERC2309.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
owners.setOwner(tokenId, to);
emit Transfer(from, to, tokenId);
}
//Sets `_tokenURI` as the tokenURI of `tokenId`.
function _setTokenURI(uint tokenId, string memory _tokenURI) internal virtual {
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
//Internal function to set the base URI for all token IDs
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_ ;
}
//Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
function _checkOnERC721Received(address from, address to, uint tokenId, bytes memory _data)
private returns(bool)
{
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(abi.encodeWithSelector(
IERC721Receiver(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
), "ERC721: transfer to non ERC721Receiver implementer");
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
function _approve(address to, uint tokenId) private {
_tokenApprovals[tokenId] = to;
emit Approval(NFTsERC2309.ownerOf(tokenId), to, tokenId); // internal owner
}
//Hook that is called before any token transfer. This includes minting and burning.
function _beforeTokenTransfer(address from, address to, uint tokenId) internal virtual { }
function _init(address to, uint number_of_tokens) internal virtual {
owners.init(to, number_of_tokens, number_of_tokens / 3);
emit ConsecutiveTransfer(0, number_of_tokens, address(0), to);
}
/*
function _transferFotLots(address to, uint number_of_tokens) internal virtual {
owners.init(to, number_of_tokens, number_of_tokens / 3);
emit ConsecutiveTransfer(0, number_of_tokens, address(0), to);
}
*/
}
|
Transfers `tokenId` from `from` to `to`.As opposed to {transferFrom}, this imposes no restrictions on msg.sender. Clear approvals from the previous owner
|
function _transfer(address from, address to, uint tokenId) internal virtual {
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
_approve(address(0), tokenId);
owners.setOwner(tokenId, to);
emit Transfer(from, to, tokenId);
}
| 12,948,069 |
./full_match/4/0xECc913B74bb323cF36DEB4c721d521b81B00bcBD/sources/browser/Untitled.sol
|
require(paxInterface(paxTokenAddress).transfer(caller, totalAmount),"token transfer failed");
|
function withdrawMyDividendNAll() public returns(uint)
{
address payable caller = msg.sender;
require(userInfos[caller].joined, 'User not exist');
uint from = eligibleUser[caller];
uint totalAmount;
if(from > 0)
{
from --;
uint lastDivPoolIndex = divPoolRecords.length;
if( lastDivPoolIndex > 1 )
{
lastDivPoolIndex = lastDivPoolIndex -2;
for(uint i=0;i<150;i++)
{
if(lastDivPoolIndex < i) break;
uint curIndex = lastDivPoolIndex - i;
if( curIndex >= from && !dividendReceived[curIndex][caller] )
{
totalAmount += ( divPoolRecords[curIndex].totalDividendCollection * 10000000000 / divPoolRecords[curIndex].totalEligibleCount ) / 10000000000;
dividendReceived[curIndex][caller] = true;
}
}
}
}
if(totalAmount > 0)
{
totalDivCollection -= totalAmount;
emit payDividendEv(now, totalAmount, caller);
}
totalAmount = totalAmount + netTotalUserWithdrawable[caller];
netTotalUserWithdrawable[caller] = 0;
totalGainInAutoPool[caller] = 0;
totalGainInMainNetwork[caller] = 0;
totalGainInUniLevel[caller] = 0;
require(paxInterface(paxTokenAddress).transfer(msg.sender, totalAmount),"token transfer failed");
emit withdrawMyGainEv(now, caller, totalAmount);
}
| 682,741 |
./full_match/80001/0x71F9bDB3C54f8Fc91D314eA3295e3BECbD30A993/sources/project_/contracts/MysticGalacticMission1.sol
|
Sets the feed for the price conversion in getPrice() _priceFeedAddress The address of the price feed oracle/
|
function setPriceConvert( address _priceFeedAddress ) public onlyOwnerOrAdmin {
priceFeedAddress = _priceFeedAddress;
}
| 5,672,576 |
pragma solidity ^0.4.24;
/**
* @title SortitionSumTreeFactory
* @author Enrique Piqueras - <[email protected]>
* @dev A factory of trees that keep track of staked values for sortition.
*/
contract SortitionSumTreeFactory {
/* Structs */
struct SortitionSumTree {
uint K;
uint[] stack;
uint[] tree;
mapping(address => uint) addressesToTreeIndexes;
mapping(uint => address) treeIndexesToAddresses;
}
/* Storage */
mapping(bytes32 => SortitionSumTree) internal sortitionSumTrees;
/* Internal */
/**
* @dev Create a sortition sum tree at the specified key.
* @param _key The key of the new tree.
* @param _K The number of children each node in the tree should have.
*/
function createTree(bytes32 _key, uint _K) internal {
SortitionSumTree storage tree = sortitionSumTrees[_key];
require(tree.K == 0, "Tree already exists.");
require(_K > 1, "K must be greater than one.");
tree.K = _K;
tree.stack.length = 0;
tree.tree.length = 0;
tree.tree.push(0);
}
/**
* @dev Delete a sortition sum tree at the specified key.
* @param _key The key of the tree to delete.
*/
function deleteTree(bytes32 _key) internal {
SortitionSumTree storage tree = sortitionSumTrees[_key];
tree.K = 0;
tree.stack.length = 0;
tree.tree.length = 0;
delete sortitionSumTrees[_key];
}
/**
* @dev Append a value to a tree.
* @param _key The key of the tree to append to.
* @param _value The value to append.
* @param _address The candidate's address.
* @return The index of the appended value in the tree.
*/
function append(bytes32 _key, uint _value, address _address) internal returns(uint treeIndex) {
SortitionSumTree storage tree = sortitionSumTrees[_key];
require(tree.addressesToTreeIndexes[_address] == 0, "Address already has a value in this tree.");
// Add node.
if (tree.stack.length == 0) { // No vacant spots.
// Get the index and append the value.
treeIndex = tree.tree.length;
tree.tree.push(_value);
// Potentially append a new node and make the parent a sum node.
if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child.
tree.tree.push(tree.tree[treeIndex / tree.K]);
uint _parentIndex = treeIndex / tree.K;
address _parentAddress = tree.treeIndexesToAddresses[_parentIndex];
uint _newIndex = treeIndex + 1;
delete tree.treeIndexesToAddresses[_parentIndex];
tree.addressesToTreeIndexes[_parentAddress] = _newIndex;
tree.treeIndexesToAddresses[_newIndex] = _parentAddress;
}
} else { // Some vacant spot.
// Pop the stack and append the value.
treeIndex = tree.stack[tree.stack.length - 1];
tree.stack.length--;
tree.tree[treeIndex] = _value;
}
// Add label.
tree.addressesToTreeIndexes[_address] = treeIndex;
tree.treeIndexesToAddresses[treeIndex] = _address;
updateParents(_key, treeIndex, true, _value);
}
/**
* @dev Remove a value from a tree.
* @param _key The key of the tree to remove from.
* @param _address The candidate's address.
*/
function remove(bytes32 _key, address _address) internal {
SortitionSumTree storage tree = sortitionSumTrees[_key];
uint _treeIndex = tree.addressesToTreeIndexes[_address];
require(_treeIndex != 0, "Address does not have a value in this tree.");
// Remember value and set to 0.
uint _value = tree.tree[_treeIndex];
tree.tree[_treeIndex] = 0;
// Push to stack.
tree.stack.push(_treeIndex);
// Clear label.
delete tree.addressesToTreeIndexes[tree.treeIndexesToAddresses[_treeIndex]];
delete tree.treeIndexesToAddresses[_treeIndex];
updateParents(_key, _treeIndex, false, _value);
}
/**
* @dev Set a value of a tree.
* @param _key The key of the tree.
* @param _value The new value.
* @param _address The candidate's address.
*/
function set(bytes32 _key, uint _value, address _address) internal {
SortitionSumTree storage tree = sortitionSumTrees[_key];
uint _treeIndex = tree.addressesToTreeIndexes[_address];
require(_treeIndex != 0, "Address does not have a value in this tree.");
bool _plusOrMinus = tree.tree[_treeIndex] <= _value;
uint _plusOrMinusValue = _plusOrMinus ? _value - tree.tree[_treeIndex] : tree.tree[_treeIndex] - _value;
tree.tree[_treeIndex] = _value;
updateParents(_key, _treeIndex, _plusOrMinus, _plusOrMinusValue);
}
/* Internal Views */
/**
* @dev Query the leafs of a tree.
* @param _key The key of the tree to get the leafs from.
* @param _cursor The pagination cursor.
* @param _count The number of items to return.
* @return The index at which leafs start, the values of the returned leafs, and wether there are more for pagination.
* Complexity: This function is O(n) where `n` is the max number of elements ever appended.
*/
function queryLeafs(bytes32 _key, uint _cursor, uint _count) internal view returns(uint startIndex, uint[] values, bool hasMore) {
SortitionSumTree storage tree = sortitionSumTrees[_key];
// Find the start index.
for (uint i = 0; i < tree.tree.length; i++) {
if ((tree.K * i) + 1 >= tree.tree.length) {
startIndex = i;
break;
}
}
// Get the values.
uint _startIndex = startIndex + _cursor;
values = new uint[](_startIndex + _count > tree.tree.length ? tree.tree.length - _startIndex : _count);
uint _valuesIndex = 0;
for (uint j = _startIndex; j < tree.tree.length; j++) {
if (_valuesIndex < _count) {
values[_valuesIndex] = tree.tree[j];
_valuesIndex++;
} else {
hasMore = true;
break;
}
}
}
/**
* @dev Draw an address from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0.
* @param _key The key of the tree.
* @param _drawnNumber The drawn number.
* @return The drawn address.
* Complexity: This function is O(n) where `n` is the max number of elements ever appended.
*/
function draw(bytes32 _key, uint _drawnNumber) internal view returns(address _address) {
SortitionSumTree storage tree = sortitionSumTrees[_key];
uint _treeIndex = 0;
uint _currentDrawnNumber = _drawnNumber % tree.tree[0];
while ((tree.K * _treeIndex) + 1 < tree.tree.length) // While it still has children.
for (uint i = 1; i <= tree.K; i++) { // Loop over children.
uint _nodeIndex = (tree.K * _treeIndex) + i;
uint _nodeValue = tree.tree[_nodeIndex];
if (_currentDrawnNumber >= _nodeValue) _currentDrawnNumber -= _nodeValue; // Go to the next child.
else { // Pick this child.
_treeIndex = _nodeIndex;
break;
}
}
_address = tree.treeIndexesToAddresses[_treeIndex];
}
/** @dev Gets a specified candidate's associated value.
* @param _key The key of the tree.
* @param _address The candidate's address.
*/
function stakeOf(bytes32 _key, address _address) internal view returns(uint value) {
SortitionSumTree storage tree = sortitionSumTrees[_key];
uint _treeIndex = tree.addressesToTreeIndexes[_address];
if (_treeIndex == 0) value = 0;
else value = tree.tree[_treeIndex];
}
/* Private */
/**
* @dev Update all the parents of a node.
* @param _key The key of the tree to update.
* @param _treeIndex The index of the node to start from.
* @param _plusOrMinus Wether to add (true) or substract (false).
* @param _value The value to add or substract.
* Complexity: This function is O(log(k)(n)) where `n` is the max number of elements ever appended.
*/
function updateParents(bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private {
SortitionSumTree storage tree = sortitionSumTrees[_key];
uint parentIndex = _treeIndex;
while (parentIndex != 0) {
parentIndex = (parentIndex - 1) / tree.K;
tree.tree[parentIndex] = _plusOrMinus ? tree.tree[parentIndex] + _value : tree.tree[parentIndex] - _value;
}
}
}
|
Delete a sortition sum tree at the specified key. _key The key of the tree to delete./
|
function deleteTree(bytes32 _key) internal {
SortitionSumTree storage tree = sortitionSumTrees[_key];
tree.K = 0;
tree.stack.length = 0;
tree.tree.length = 0;
delete sortitionSumTrees[_key];
}
| 2,491,850 |
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor() {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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 (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (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 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./interfaces/StakingRewardsInterface.sol";
contract StakingRewards is
Ownable,
Pausable,
ReentrancyGuard,
StakingRewardsInterface
{
using SafeERC20 for IERC20;
/* ========== STATE VARIABLES ========== */
/// @notice The staking token address
IERC20 public stakingToken;
/// @notice The list of rewards tokens
address[] public rewardsTokens;
/// @notice The reward tokens mapping
mapping(address => bool) public rewardsTokensMap;
/// @notice The period finish timestamp of every reward token
mapping(address => uint256) public periodFinish;
/// @notice The reward rate of every reward token
mapping(address => uint256) public rewardRate;
/// @notice The reward duration of every reward token
mapping(address => uint256) public rewardsDuration;
/// @notice The last updated timestamp of every reward token
mapping(address => uint256) public lastUpdateTime;
/// @notice The reward per token of every reward token
mapping(address => uint256) public rewardPerTokenStored;
/// @notice The reward per token paid to users of every reward token
mapping(address => mapping(address => uint256)) public rewardPerTokenPaid;
/// @notice The unclaimed rewards to users of every reward token
mapping(address => mapping(address => uint256)) public rewards;
/// @notice The helper contract that could stake, withdraw and claim rewards for users
address public helperContract;
/// @notice The total amount of the staking token staked in the contract
uint256 private _totalSupply;
/// @notice The user balance of the staking token staked in the contract
mapping(address => uint256) private _balances;
/* ========== CONSTRUCTOR ========== */
constructor(address _stakingToken, address _helperContract) {
stakingToken = IERC20(_stakingToken);
helperContract = _helperContract;
}
/* ========== VIEWS ========== */
/**
* @notice Return the total amount of the staking token staked in the contract.
* @return The total supply
*/
function totalSupply() external view returns (uint256) {
return _totalSupply;
}
/**
* @notice Return user balance of the staking token staked in the contract.
* @return The user balance
*/
function balanceOf(address account) external view returns (uint256) {
return _balances[account];
}
/**
* @notice Return the last time reward is applicable.
* @param _rewardsToken The reward token address
* @return The last applicable timestamp
*/
function lastTimeRewardApplicable(address _rewardsToken)
public
view
returns (uint256)
{
return
getBlockTimestamp() < periodFinish[_rewardsToken]
? getBlockTimestamp()
: periodFinish[_rewardsToken];
}
/**
* @notice Return the reward token amount per staking token.
* @param _rewardsToken The reward token address
* @return The reward token amount
*/
function rewardPerToken(address _rewardsToken)
public
view
returns (uint256)
{
// Return 0 if the rewards token is not supported.
if (!rewardsTokensMap[_rewardsToken]) {
return 0;
}
if (_totalSupply == 0) {
return rewardPerTokenStored[_rewardsToken];
}
// rewardPerTokenStored + [(lastTimeRewardApplicable - lastUpdateTime) * rewardRate / _totalSupply]
return
rewardPerTokenStored[_rewardsToken] +
(((lastTimeRewardApplicable(_rewardsToken) -
lastUpdateTime[_rewardsToken]) *
rewardRate[_rewardsToken] *
1e18) / _totalSupply);
}
/**
* @notice Return the reward token amount a user earned.
* @param _rewardsToken The reward token address
* @param account The user address
* @return The reward token amount
*/
function earned(address _rewardsToken, address account)
public
view
returns (uint256)
{
// Return 0 if the rewards token is not supported.
if (!rewardsTokensMap[_rewardsToken]) {
return 0;
}
// rewards + (rewardPerToken - rewardPerTokenPaid) * _balances
return
(_balances[account] *
(rewardPerToken(_rewardsToken) -
rewardPerTokenPaid[_rewardsToken][account])) /
1e18 +
rewards[_rewardsToken][account];
}
/**
* @notice Return the reward rate.
* @param _rewardsToken The reward token address
* @return The reward rate
*/
function getRewardRate(address _rewardsToken)
external
view
returns (uint256)
{
return rewardRate[_rewardsToken];
}
/**
* @notice Return the reward token for duration.
* @param _rewardsToken The reward token address
* @return The reward token amount
*/
function getRewardForDuration(address _rewardsToken)
external
view
returns (uint256)
{
return rewardRate[_rewardsToken] * rewardsDuration[_rewardsToken];
}
/**
* @notice Return the amount of reward tokens.
* @return The amount of reward tokens
*/
function getRewardsTokenCount() external view returns (uint256) {
return rewardsTokens.length;
}
/**
* @notice Return all the reward tokens.
* @return All the reward tokens
*/
function getAllRewardsTokens() external view returns (address[] memory) {
return rewardsTokens;
}
/**
* @notice Return the staking token.
* @return The staking token
*/
function getStakingToken() external view returns (address) {
return address(stakingToken);
}
/**
* @notice Return the current block timestamp.
* @return The current block timestamp
*/
function getBlockTimestamp() public view virtual returns (uint256) {
return block.timestamp;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Stake the staking token.
* @param amount The amount of the staking token
*/
function stake(uint256 amount)
external
nonReentrant
whenNotPaused
updateReward(msg.sender)
{
_stakeFor(msg.sender, amount);
}
/**
* @notice Stake the staking token for other user.
* @param account The user address
* @param amount The amount of the staking token
*/
function stakeFor(address account, uint256 amount)
external
nonReentrant
whenNotPaused
updateReward(account)
{
require(msg.sender == helperContract, "unauthorized");
require(account != address(0), "invalid account");
_stakeFor(account, amount);
}
function _stakeFor(address account, uint256 amount) internal {
require(amount > 0, "invalid amount");
_totalSupply = _totalSupply + amount;
_balances[account] = _balances[account] + amount;
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
emit Staked(account, amount);
}
/**
* @notice Withdraw the staked token.
* @param amount The amount of the staking token
*/
function withdraw(uint256 amount)
public
nonReentrant
updateReward(msg.sender)
{
_withdrawFor(msg.sender, amount);
}
/**
* @notice Withdraw the staked token for other user.
* @dev This function can only be called by helper.
* @param account The user address
* @param amount The amount of the staking token
*/
function withdrawFor(address account, uint256 amount)
public
nonReentrant
updateReward(account)
{
require(msg.sender == helperContract, "unauthorized");
require(account != address(0), "invalid account");
_withdrawFor(account, amount);
}
function _withdrawFor(address account, uint256 amount) internal {
require(amount > 0, "invalid amount");
_totalSupply = _totalSupply - amount;
_balances[account] = _balances[account] - amount;
stakingToken.safeTransfer(msg.sender, amount);
emit Withdrawn(account, amount);
}
/**
* @notice Claim rewards for the message sender.
*/
function getReward() public nonReentrant updateReward(msg.sender) {
_getRewardFor(msg.sender);
}
/**
* @notice Claim rewards for an account.
* @dev This function can only be called by helper.
* @param account The user address
*/
function getRewardFor(address account)
public
nonReentrant
updateReward(account)
{
require(msg.sender == helperContract, "unauthorized");
require(account != address(0), "invalid account");
_getRewardFor(account);
}
function _getRewardFor(address account) internal {
for (uint256 i = 0; i < rewardsTokens.length; i++) {
uint256 reward = rewards[rewardsTokens[i]][account];
uint256 remain = IERC20(rewardsTokens[i]).balanceOf(address(this));
if (reward > 0 && reward <= remain) {
rewards[rewardsTokens[i]][account] = 0;
IERC20(rewardsTokens[i]).safeTransfer(account, reward);
emit RewardPaid(account, rewardsTokens[i], reward);
}
}
}
/**
* @notice Withdraw all the staked tokens and claim rewards.
*/
function exit() external {
withdraw(_balances[msg.sender]);
getReward();
}
/* ========== RESTRICTED FUNCTIONS ========== */
/**
* @notice Set new reward amount.
* @dev Make sure the admin deposits `reward` of reward tokens into the contract before calling this function.
* @param rewardsToken The reward token address
* @param reward The reward amount
*/
function notifyRewardAmount(address rewardsToken, uint256 reward)
external
onlyOwner
updateReward(address(0))
{
require(rewardsTokensMap[rewardsToken], "reward token not supported");
if (getBlockTimestamp() >= periodFinish[rewardsToken]) {
rewardRate[rewardsToken] = reward / rewardsDuration[rewardsToken];
} else {
uint256 remaining = periodFinish[rewardsToken] -
getBlockTimestamp();
uint256 leftover = remaining * rewardRate[rewardsToken];
rewardRate[rewardsToken] =
(reward + leftover) /
rewardsDuration[rewardsToken];
}
// Ensure the provided reward amount is not more than the balance in the contract.
// This keeps the reward rate in the right range, preventing overflows due to
// very high values of rewardRate in the earned and rewardsPerToken functions;
// Reward + leftover must be less than 2^256 / 10^18 to avoid overflow.
uint256 balance = IERC20(rewardsToken).balanceOf(address(this));
require(
rewardRate[rewardsToken] <= balance / rewardsDuration[rewardsToken],
"reward rate too high"
);
lastUpdateTime[rewardsToken] = getBlockTimestamp();
periodFinish[rewardsToken] =
getBlockTimestamp() +
rewardsDuration[rewardsToken];
emit RewardAdded(rewardsToken, reward);
}
/**
* @notice Seize the accidentally deposited tokens.
* @dev Thes staking tokens cannot be seized.
* @param tokenAddress The token address
* @param tokenAmount The token amount
*/
function recoverToken(address tokenAddress, uint256 tokenAmount)
external
onlyOwner
{
require(
tokenAddress != address(stakingToken),
"cannot withdraw staking token"
);
IERC20(tokenAddress).safeTransfer(owner(), tokenAmount);
emit Recovered(tokenAddress, tokenAmount);
}
/**
* @notice Set the rewards duration.
* @param rewardsToken The reward token address
* @param duration The new duration
*/
function setRewardsDuration(address rewardsToken, uint256 duration)
external
onlyOwner
{
require(rewardsTokensMap[rewardsToken], "reward token not supported");
require(
getBlockTimestamp() > periodFinish[rewardsToken],
"previous rewards not complete"
);
_setRewardsDuration(rewardsToken, duration);
}
/**
* @notice Support new rewards token.
* @param rewardsToken The reward token address
* @param duration The duration
*/
function addRewardsToken(address rewardsToken, uint256 duration)
external
onlyOwner
{
require(
!rewardsTokensMap[rewardsToken],
"rewards token already supported"
);
rewardsTokens.push(rewardsToken);
rewardsTokensMap[rewardsToken] = true;
emit RewardsTokenAdded(rewardsToken);
_setRewardsDuration(rewardsToken, duration);
}
/**
* @notice Set the helper contract.
* @param helper The helper contract address
*/
function setHelperContract(address helper) external onlyOwner {
helperContract = helper;
emit HelperContractSet(helper);
}
/**
* @notice Pause the staking.
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Unpause the staking.
*/
function unpause() external onlyOwner {
_unpause();
}
function _setRewardsDuration(address rewardsToken, uint256 duration)
internal
{
rewardsDuration[rewardsToken] = duration;
emit RewardsDurationUpdated(rewardsToken, duration);
}
/* ========== MODIFIERS ========== */
/**
* @notice Update the reward information.
* @param user The user address
*/
modifier updateReward(address user) {
for (uint256 i = 0; i < rewardsTokens.length; i++) {
address token = rewardsTokens[i];
rewardPerTokenStored[token] = rewardPerToken(token);
lastUpdateTime[token] = lastTimeRewardApplicable(token);
if (user != address(0)) {
rewards[token][user] = earned(token, user);
rewardPerTokenPaid[token][user] = rewardPerTokenStored[token];
}
}
_;
}
/* ========== EVENTS ========== */
/**
* @notice Emitted when new reward tokens are added
*/
event RewardAdded(address rewardsToken, uint256 reward);
/**
* @notice Emitted when user staked
*/
event Staked(address indexed user, uint256 amount);
/**
* @notice Emitted when user withdrew
*/
event Withdrawn(address indexed user, uint256 amount);
/**
* @notice Emitted when rewards are paied
*/
event RewardPaid(
address indexed user,
address rewardsToken,
uint256 reward
);
/**
* @notice Emitted when a reward duration is updated
*/
event RewardsDurationUpdated(address rewardsToken, uint256 newDuration);
/**
* @notice Emitted when a token is recovered by admin
*/
event Recovered(address token, uint256 amount);
/**
* @notice Emitted when a reward token is added
*/
event RewardsTokenAdded(address rewardsToken);
/**
* @notice Emitted when new helper contract is set
*/
event HelperContractSet(address helper);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./StakingRewards.sol";
import "./interfaces/ITokenInterface.sol";
import "./interfaces/StakingRewardsFactoryInterface.sol";
contract StakingRewardsFactory is Ownable, StakingRewardsFactoryInterface {
using SafeERC20 for IERC20;
/// @notice The list of staking rewards contract
address[] private _stakingRewards;
/// @notice The staking token - staking rewards contract mapping
mapping(address => address) private _stakingRewardsMap;
/// @notice The underlying - staking token mapping
mapping(address => address) public _stakingTokenMap;
/**
* @notice Emitted when a staking rewards contract is deployed
*/
event StakingRewardsCreated(
address indexed stakingRewards,
address indexed stakingToken
);
/**
* @notice Emitted when a staking rewards contract is removed
*/
event StakingRewardsRemoved(address indexed stakingToken);
/**
* @notice Emitted when tokens are seized
*/
event TokenSeized(address token, uint256 amount);
/**
* @notice Return the amount of staking reward contracts.
* @return The amount of staking reward contracts
*/
function getStakingRewardsCount() external view returns (uint256) {
return _stakingRewards.length;
}
/**
* @notice Return all the staking reward contracts.
* @return All the staking reward contracts
*/
function getAllStakingRewards() external view returns (address[] memory) {
return _stakingRewards;
}
/**
* @notice Return the staking rewards contract of a given staking token
* @param stakingToken The staking token
* @return The staking reward contracts
*/
function getStakingRewards(address stakingToken)
external
view
returns (address)
{
return _stakingRewardsMap[stakingToken];
}
/**
* @notice Return the staking token of a given underlying token
* @param underlying The underlying token
* @return The staking token
*/
function getStakingToken(address underlying)
external
view
returns (address)
{
return _stakingTokenMap[underlying];
}
/**
* @notice Create staking reward contracts.
* @param stakingTokens The staking token list
*/
function createStakingRewards(
address[] calldata stakingTokens,
address helperContract
) external onlyOwner {
for (uint256 i = 0; i < stakingTokens.length; i++) {
address stakingToken = stakingTokens[i];
address underlying = ITokenInterface(stakingToken).underlying();
require(underlying != address(0), "invalid underlying");
require(
_stakingRewardsMap[stakingToken] == address(0),
"staking rewards contract already exist"
);
// Create a new staking rewards contract.
StakingRewards sr = new StakingRewards(
stakingToken,
helperContract
);
sr.transferOwnership(msg.sender);
_stakingRewards.push(address(sr));
_stakingRewardsMap[stakingToken] = address(sr);
_stakingTokenMap[underlying] = stakingToken;
emit StakingRewardsCreated(address(sr), stakingToken);
}
}
/**
* @notice Remove a staking reward contract.
* @param stakingToken The staking token
*/
function removeStakingRewards(address stakingToken) external onlyOwner {
address underlying = ITokenInterface(stakingToken).underlying();
require(underlying != address(0), "invalid underlying");
require(
_stakingRewardsMap[stakingToken] != address(0),
"staking rewards contract not exist"
);
for (uint256 i = 0; i < _stakingRewards.length; i++) {
if (_stakingRewardsMap[stakingToken] == _stakingRewards[i]) {
_stakingRewards[i] = _stakingRewards[
_stakingRewards.length - 1
];
delete _stakingRewards[_stakingRewards.length - 1];
_stakingRewards.pop();
break;
}
}
_stakingRewardsMap[stakingToken] = address(0);
_stakingTokenMap[underlying] = address(0);
emit StakingRewardsRemoved(stakingToken);
}
/**
* @notice Seize tokens in this contract.
* @param token The token
* @param amount The amount
*/
function seize(address token, uint256 amount) external onlyOwner {
IERC20(token).safeTransfer(owner(), amount);
emit TokenSeized(token, amount);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ITokenInterface {
function underlying() external view returns (address);
function supplyRatePerBlock() external view returns (uint256);
function exchangeRateStored() external view returns (uint256);
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface StakingRewardsFactoryInterface {
function getStakingRewardsCount() external view returns (uint256);
function getAllStakingRewards() external view returns (address[] memory);
function getStakingRewards(address stakingToken)
external
view
returns (address);
function getStakingToken(address underlying)
external
view
returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface StakingRewardsInterface {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function lastTimeRewardApplicable(address _rewardsToken)
external
view
returns (uint256);
function rewardPerToken(address _rewardsToken)
external
view
returns (uint256);
function earned(address _rewardsToken, address account)
external
view
returns (uint256);
function getRewardRate(address _rewardsToken)
external
view
returns (uint256);
function getRewardForDuration(address _rewardsToken)
external
view
returns (uint256);
function getRewardsTokenCount() external view returns (uint256);
function getAllRewardsTokens() external view returns (address[] memory);
function getStakingToken() external view returns (address);
function stake(uint256 amount) external;
function stakeFor(address account, uint256 amount) external;
function withdraw(uint256 amount) external;
function withdrawFor(address account, uint256 amount) external;
function getReward() external;
function getRewardFor(address account) external;
function exit() external;
}
|
Return the current block timestamp. return The current block timestamp/
|
function getBlockTimestamp() public view virtual returns (uint256) {
return block.timestamp;
}
| 11,994,564 |
pragma solidity ^0.5.0;
import "../libraries/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "../libraries/openzeppelin-solidity/contracts/token/ERC20/SafeERC20.sol";
import "../libraries/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol";
import "../libraries/openzeppelin-solidity/contracts/utils/Address.sol";
import "../libraries/openzeppelin-upgradeability/VersionedInitializable.sol";
import "../libraries/CoreLibrary.sol";
import "../configuration/LendingPoolAddressesProvider.sol";
import "../interfaces/ILendingRateOracle.sol";
import "../interfaces/IReserveInterestRateStrategy.sol";
import "../libraries/WadRayMath.sol";
import "../tokenization/AToken.sol";
import "../libraries/TrxAddressLib.sol";
/**
* @title LendingPoolCore contract
* @author Aave
* @notice Holds the state of the lending pool and all the funds deposited
* @dev NOTE: The core does not enforce security checks on the update of the state
* (eg, updateStateOnBorrow() does not enforce that borrowed is enabled on the reserve).
* The check that an action can be performed is a duty of the overlying LendingPool contract.
**/
contract LendingPoolCore is VersionedInitializable {
using SafeMath for uint256;
using WadRayMath for uint256;
using CoreLibrary for CoreLibrary.ReserveData;
using CoreLibrary for CoreLibrary.UserReserveData;
using SafeERC20 for ERC20;
using Address for address payable;
/**
* @dev Emitted when the state of a reserve is updated
* @param reserve the address of the reserve
* @param liquidityRate the new liquidity rate
* @param stableBorrowRate the new stable borrow rate
* @param variableBorrowRate the new variable borrow rate
* @param liquidityIndex the new liquidity index
* @param variableBorrowIndex the new variable borrow index
**/
event ReserveUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
address public lendingPoolAddress;
LendingPoolAddressesProvider public addressesProvider;
/**
* @dev only lending pools can use functions affected by this modifier
**/
modifier onlyLendingPool {
require(lendingPoolAddress == msg.sender, "The caller must be a lending pool contract");
_;
}
/**
* @dev only lending pools configurator can use functions affected by this modifier
**/
modifier onlyLendingPoolConfigurator {
require(
addressesProvider.getLendingPoolConfigurator() == msg.sender,
"The caller must be a lending pool configurator contract"
);
_;
}
mapping(address => CoreLibrary.ReserveData) internal reserves;
mapping(address => mapping(address => CoreLibrary.UserReserveData)) internal usersReserveData;
address[] public reservesList;
uint256 public constant CORE_REVISION = 0x4;
/**
* @dev returns the revision number of the contract
**/
function getRevision() internal pure returns (uint256) {
return CORE_REVISION;
}
/**
* @dev initializes the Core contract, invoked upon registration on the AddressesProvider
* @param _addressesProvider the addressesProvider contract
**/
function initialize(LendingPoolAddressesProvider _addressesProvider) public initializer {
addressesProvider = _addressesProvider;
refreshConfigInternal();
}
/**
* @dev updates the state of the core as a result of a deposit action
* @param _reserve the address of the reserve in which the deposit is happening
* @param _user the address of the the user depositing
* @param _amount the amount being deposited
* @param _isFirstDeposit true if the user is depositing for the first time
**/
function updateStateOnDeposit(
address _reserve,
address _user,
uint256 _amount,
bool _isFirstDeposit
) external onlyLendingPool {
reserves[_reserve].updateCumulativeIndexes();
updateReserveInterestRatesAndTimestampInternal(_reserve, _amount, 0);
if (_isFirstDeposit) {
//if this is the first deposit of the user, we configure the deposit as enabled to be used as collateral
setUserUseReserveAsCollateral(_reserve, _user, true);
}
}
/**
* @dev updates the state of the core as a result of a redeem action
* @param _reserve the address of the reserve in which the redeem is happening
* @param _user the address of the the user redeeming
* @param _amountRedeemed the amount being redeemed
* @param _userRedeemedEverything true if the user is redeeming everything
**/
function updateStateOnRedeem(
address _reserve,
address _user,
uint256 _amountRedeemed,
bool _userRedeemedEverything
) external onlyLendingPool {
//compound liquidity and variable borrow interests
reserves[_reserve].updateCumulativeIndexes();
updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountRedeemed);
//if user redeemed everything the useReserveAsCollateral flag is reset
if (_userRedeemedEverything) {
setUserUseReserveAsCollateral(_reserve, _user, false);
}
}
/**
* @dev updates the state of the core as a consequence of a borrow action.
* @param _reserve the address of the reserve on which the user is borrowing
* @param _user the address of the borrower
* @param _amountBorrowed the new amount borrowed
* @param _borrowFee the fee on the amount borrowed
* @param _rateMode the borrow rate mode (stable, variable)
* @return the new borrow rate for the user
**/
function updateStateOnBorrow(
address _reserve,
address _user,
uint256 _amountBorrowed,
uint256 _borrowFee,
CoreLibrary.InterestRateMode _rateMode
) external onlyLendingPool returns (uint256, uint256) {
// getting the previous borrow data of the user
(uint256 principalBorrowBalance, , uint256 balanceIncrease) = getUserBorrowBalances(
_reserve,
_user
);
updateReserveStateOnBorrowInternal(
_reserve,
_user,
principalBorrowBalance,
balanceIncrease,
_amountBorrowed,
_rateMode
);
updateUserStateOnBorrowInternal(
_reserve,
_user,
_amountBorrowed,
balanceIncrease,
_borrowFee,
_rateMode
);
updateReserveInterestRatesAndTimestampInternal(_reserve, 0, _amountBorrowed);
return (getUserCurrentBorrowRate(_reserve, _user), balanceIncrease);
}
/**
* @dev updates the state of the core as a consequence of a repay action.
* @param _reserve the address of the reserve on which the user is repaying
* @param _user the address of the borrower
* @param _paybackAmountMinusFees the amount being paid back minus fees
* @param _originationFeeRepaid the fee on the amount that is being repaid
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _repaidWholeLoan true if the user is repaying the whole loan
**/
function updateStateOnRepay(
address _reserve,
address _user,
uint256 _paybackAmountMinusFees,
uint256 _originationFeeRepaid,
uint256 _balanceIncrease,
bool _repaidWholeLoan
) external onlyLendingPool {
updateReserveStateOnRepayInternal(
_reserve,
_user,
_paybackAmountMinusFees,
_balanceIncrease
);
updateUserStateOnRepayInternal(
_reserve,
_user,
_paybackAmountMinusFees,
_originationFeeRepaid,
_balanceIncrease,
_repaidWholeLoan
);
updateReserveInterestRatesAndTimestampInternal(_reserve, _paybackAmountMinusFees, 0);
}
/**
* @dev updates the state of the core as a consequence of a swap rate action.
* @param _reserve the address of the reserve on which the user is repaying
* @param _user the address of the borrower
* @param _principalBorrowBalance the amount borrowed by the user
* @param _compoundedBorrowBalance the amount borrowed plus accrued interest
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _currentRateMode the current interest rate mode for the user
**/
function updateStateOnSwapRate(
address _reserve,
address _user,
uint256 _principalBorrowBalance,
uint256 _compoundedBorrowBalance,
uint256 _balanceIncrease,
CoreLibrary.InterestRateMode _currentRateMode
) external onlyLendingPool returns (CoreLibrary.InterestRateMode, uint256) {
updateReserveStateOnSwapRateInternal(
_reserve,
_user,
_principalBorrowBalance,
_compoundedBorrowBalance,
_currentRateMode
);
CoreLibrary.InterestRateMode newRateMode = updateUserStateOnSwapRateInternal(
_reserve,
_user,
_balanceIncrease,
_currentRateMode
);
updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0);
return (newRateMode, getUserCurrentBorrowRate(_reserve, _user));
}
/**
* @dev updates the state of the core as a consequence of a liquidation action.
* @param _principalReserve the address of the principal reserve that is being repaid
* @param _collateralReserve the address of the collateral reserve that is being liquidated
* @param _user the address of the borrower
* @param _amountToLiquidate the amount being repaid by the liquidator
* @param _collateralToLiquidate the amount of collateral being liquidated
* @param _feeLiquidated the amount of origination fee being liquidated
* @param _liquidatedCollateralForFee the amount of collateral equivalent to the origination fee + bonus
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _liquidatorReceivesAToken true if the liquidator will receive aTokens, false otherwise
**/
function updateStateOnLiquidation(
address _principalReserve,
address _collateralReserve,
address _user,
uint256 _amountToLiquidate,
uint256 _collateralToLiquidate,
uint256 _feeLiquidated,
uint256 _liquidatedCollateralForFee,
uint256 _balanceIncrease,
bool _liquidatorReceivesAToken
) external onlyLendingPool {
updatePrincipalReserveStateOnLiquidationInternal(
_principalReserve,
_user,
_amountToLiquidate,
_balanceIncrease
);
updateCollateralReserveStateOnLiquidationInternal(
_collateralReserve
);
updateUserStateOnLiquidationInternal(
_principalReserve,
_user,
_amountToLiquidate,
_feeLiquidated,
_balanceIncrease
);
updateReserveInterestRatesAndTimestampInternal(_principalReserve, _amountToLiquidate, 0);
if (!_liquidatorReceivesAToken) {
updateReserveInterestRatesAndTimestampInternal(
_collateralReserve,
0,
_collateralToLiquidate.add(_liquidatedCollateralForFee)
);
}
}
/**
* @dev updates the state of the core as a consequence of a stable rate rebalance
* @param _reserve the address of the principal reserve where the user borrowed
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
* @return the new stable rate for the user
**/
function updateStateOnRebalance(address _reserve, address _user, uint256 _balanceIncrease)
external
onlyLendingPool
returns (uint256)
{
updateReserveStateOnRebalanceInternal(_reserve, _user, _balanceIncrease);
//update user data and rebalance the rate
updateUserStateOnRebalanceInternal(_reserve, _user, _balanceIncrease);
updateReserveInterestRatesAndTimestampInternal(_reserve, 0, 0);
return usersReserveData[_user][_reserve].stableBorrowRate;
}
/**
* @dev enables or disables a reserve as collateral
* @param _reserve the address of the principal reserve where the user deposited
* @param _user the address of the depositor
* @param _useAsCollateral true if the depositor wants to use the reserve as collateral
**/
function setUserUseReserveAsCollateral(address _reserve, address _user, bool _useAsCollateral)
public
onlyLendingPool
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
user.useAsCollateral = _useAsCollateral;
}
/**
* @notice TRX/token transfer functions
**/
/**
* @dev fallback function enforces that the caller is a contract, to support flashloan transfers
**/
function() external payable {
//only contracts can send TRX to the core
require(msg.sender.isContract(), "Only contracts can send ether to the Lending pool core");
}
/**
* @dev transfers to the user a specific amount from the reserve.
* @param _reserve the address of the reserve where the transfer is happening
* @param _user the address of the user receiving the transfer
* @param _amount the amount being transferred
**/
function transferToUser(address _reserve, address payable _user, uint256 _amount)
external
onlyLendingPool
{
if (_reserve != TrxAddressLib.trxAddress()) {
ERC20(_reserve).safeTransfer(_user, _amount);
} else {
//solium-disable-next-line
(bool result, ) = _user.call.value(_amount).gas(50000)("");
require(result, "Transfer of TRX failed");
}
}
/**
* @dev transfers the protocol fees to the fees collection address
* @param _token the address of the token being transferred
* @param _user the address of the user from where the transfer is happening
* @param _amount the amount being transferred
* @param _destination the fee receiver address
**/
function transferToFeeCollectionAddress(
address _token,
address _user,
uint256 _amount,
address _destination
) external payable onlyLendingPool {
address payable feeAddress = address(uint160(_destination)); //cast the address to payable
if (_token != TrxAddressLib.trxAddress()) {
require(
msg.value == 0,
"User is sending TRX along with the ERC20 transfer. Check the value attribute of the transaction"
);
ERC20(_token).safeTransferFrom(_user, feeAddress, _amount);
} else {
require(msg.value >= _amount, "The amount and the value sent to deposit do not match");
//solium-disable-next-line
(bool result, ) = feeAddress.call.value(_amount).gas(50000)("");
require(result, "Transfer of TRX failed");
}
}
/**
* @dev transfers the fees to the fees collection address in the case of liquidation
* @param _token the address of the token being transferred
* @param _amount the amount being transferred
* @param _destination the fee receiver address
**/
function liquidateFee(
address _token,
uint256 _amount,
address _destination
) external payable onlyLendingPool {
address payable feeAddress = address(uint160(_destination)); //cast the address to payable
require(
msg.value == 0,
"Fee liquidation does not require any transfer of value"
);
if (_token != TrxAddressLib.trxAddress()) {
ERC20(_token).safeTransfer(feeAddress, _amount);
} else {
//solium-disable-next-line
(bool result, ) = feeAddress.call.value(_amount).gas(50000)("");
require(result, "Transfer of TRX failed");
}
}
/**
* @dev transfers an amount from a user to the destination reserve
* @param _reserve the address of the reserve where the amount is being transferred
* @param _user the address of the user from where the transfer is happening
* @param _amount the amount being transferred
**/
function transferToReserve(address _reserve, address payable _user, uint256 _amount)
external
payable
onlyLendingPool
{
if (_reserve != TrxAddressLib.trxAddress()) {
require(msg.value == 0, "User is sending TRX along with the ERC20 transfer.");
ERC20(_reserve).safeTransferFrom(_user, address(this), _amount);
} else {
require(msg.value >= _amount, "The amount and the value sent to deposit do not match");
if (msg.value > _amount) {
//send back excess TRX
uint256 excessAmount = msg.value.sub(_amount);
//solium-disable-next-line
(bool result, ) = _user.call.value(excessAmount).gas(50000)("");
require(result, "Transfer of TRX failed");
}
}
}
/**
* @notice data access functions
**/
/**
* @dev returns the basic data (balances, fee accrued, reserve enabled/disabled as collateral)
* needed to calculate the global account data in the LendingPoolDataProvider
* @param _reserve the address of the reserve
* @param _user the address of the user
* @return the user deposited balance, the principal borrow balance, the fee, and if the reserve is enabled as collateral or not
**/
function getUserBasicReserveData(address _reserve, address _user)
external
view
returns (uint256, uint256, uint256, bool)
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
uint256 underlyingBalance = getUserUnderlyingAssetBalance(_reserve, _user);
if (user.principalBorrowBalance == 0) {
return (underlyingBalance, 0, 0, user.useAsCollateral);
}
return (
underlyingBalance,
user.getCompoundedBorrowBalance(reserve),
user.originationFee,
user.useAsCollateral
);
}
/**
* @dev checks if a user is allowed to borrow at a stable rate
* @param _reserve the reserve address
* @param _user the user
* @param _amount the amount the the user wants to borrow
* @return true if the user is allowed to borrow at a stable rate, false otherwise
**/
function isUserAllowedToBorrowAtStable(address _reserve, address _user, uint256 _amount)
external
view
returns (bool)
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (!reserve.isStableBorrowRateEnabled) return false;
return
!user.useAsCollateral ||
!reserve.usageAsCollateralEnabled ||
_amount > getUserUnderlyingAssetBalance(_reserve, _user);
}
/**
* @dev gets the underlying asset balance of a user based on the corresponding aToken balance.
* @param _reserve the reserve address
* @param _user the user address
* @return the underlying deposit balance of the user
**/
function getUserUnderlyingAssetBalance(address _reserve, address _user)
public
view
returns (uint256)
{
AToken aToken = AToken(reserves[_reserve].aTokenAddress);
return aToken.balanceOf(_user);
}
/**
* @dev gets the interest rate strategy contract address for the reserve
* @param _reserve the reserve address
* @return the address of the interest rate strategy contract
**/
function getReserveInterestRateStrategyAddress(address _reserve) public view returns (address) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.interestRateStrategyAddress;
}
/**
* @dev gets the aToken contract address for the reserve
* @param _reserve the reserve address
* @return the address of the aToken contract
**/
function getReserveATokenAddress(address _reserve) public view returns (address) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.aTokenAddress;
}
/**
* @dev gets the available liquidity in the reserve. The available liquidity is the balance of the core contract
* @param _reserve the reserve address
* @return the available liquidity
**/
function getReserveAvailableLiquidity(address _reserve) public view returns (uint256) {
uint256 balance = 0;
if (_reserve == TrxAddressLib.trxAddress()) {
balance = address(this).balance;
} else {
balance = IERC20(_reserve).balanceOf(address(this));
}
return balance;
}
/**
* @dev gets the total liquidity in the reserve. The total liquidity is the balance of the core contract + total borrows
* @param _reserve the reserve address
* @return the total liquidity
**/
function getReserveTotalLiquidity(address _reserve) public view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return getReserveAvailableLiquidity(_reserve).add(reserve.getTotalBorrows());
}
/**
* @dev gets the normalized income of the reserve. a value of 1e27 means there is no income. A value of 2e27 means there
* there has been 100% income.
* @param _reserve the reserve address
* @return the reserve normalized income
**/
function getReserveNormalizedIncome(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.getNormalizedIncome();
}
/**
* @dev gets the reserve total borrows
* @param _reserve the reserve address
* @return the total borrows (stable + variable)
**/
function getReserveTotalBorrows(address _reserve) public view returns (uint256) {
return reserves[_reserve].getTotalBorrows();
}
/**
* @dev gets the reserve total borrows stable
* @param _reserve the reserve address
* @return the total borrows stable
**/
function getReserveTotalBorrowsStable(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.totalBorrowsStable;
}
/**
* @dev gets the reserve total borrows variable
* @param _reserve the reserve address
* @return the total borrows variable
**/
function getReserveTotalBorrowsVariable(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.totalBorrowsVariable;
}
/**
* @dev gets the reserve liquidation threshold
* @param _reserve the reserve address
* @return the reserve liquidation threshold
**/
function getReserveLiquidationThreshold(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.liquidationThreshold;
}
/**
* @dev gets the reserve liquidation bonus
* @param _reserve the reserve address
* @return the reserve liquidation bonus
**/
function getReserveLiquidationBonus(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.liquidationBonus;
}
/**
* @dev gets the reserve current variable borrow rate. Is the base variable borrow rate if the reserve is empty
* @param _reserve the reserve address
* @return the reserve current variable borrow rate
**/
function getReserveCurrentVariableBorrowRate(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
if (reserve.currentVariableBorrowRate == 0) {
return
IReserveInterestRateStrategy(reserve.interestRateStrategyAddress)
.getBaseVariableBorrowRate();
}
return reserve.currentVariableBorrowRate;
}
/**
* @dev gets the reserve current stable borrow rate. Is the market rate if the reserve is empty
* @param _reserve the reserve address
* @return the reserve current stable borrow rate
**/
function getReserveCurrentStableBorrowRate(address _reserve) public view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
ILendingRateOracle oracle = ILendingRateOracle(addressesProvider.getLendingRateOracle());
if (reserve.currentStableBorrowRate == 0) {
//no stable rate borrows yet
return oracle.getMarketBorrowRate(_reserve);
}
return reserve.currentStableBorrowRate;
}
/**
* @dev gets the reserve average stable borrow rate. The average stable rate is the weighted average
* of all the loans taken at stable rate.
* @param _reserve the reserve address
* @return the reserve current average borrow rate
**/
function getReserveCurrentAverageStableBorrowRate(address _reserve)
external
view
returns (uint256)
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.currentAverageStableBorrowRate;
}
/**
* @dev gets the reserve liquidity rate
* @param _reserve the reserve address
* @return the reserve liquidity rate
**/
function getReserveCurrentLiquidityRate(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.currentLiquidityRate;
}
/**
* @dev gets the reserve liquidity cumulative index
* @param _reserve the reserve address
* @return the reserve liquidity cumulative index
**/
function getReserveLiquidityCumulativeIndex(address _reserve) external view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.lastLiquidityCumulativeIndex;
}
/**
* @dev gets the reserve variable borrow index
* @param _reserve the reserve address
* @return the reserve variable borrow index
**/
function getReserveVariableBorrowsCumulativeIndex(address _reserve)
external
view
returns (uint256)
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.lastVariableBorrowCumulativeIndex;
}
/**
* @dev this function aggregates the configuration parameters of the reserve.
* It's used in the LendingPoolDataProvider specifically to save gas, and avoid
* multiple external contract calls to fetch the same data.
* @param _reserve the reserve address
* @return the reserve decimals
* @return the base ltv as collateral
* @return the liquidation threshold
* @return if the reserve is used as collateral or not
**/
function getReserveConfiguration(address _reserve)
external
view
returns (uint256, uint256, uint256, bool)
{
uint256 decimals;
uint256 baseLTVasCollateral;
uint256 liquidationThreshold;
bool usageAsCollateralEnabled;
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
decimals = reserve.decimals;
baseLTVasCollateral = reserve.baseLTVasCollateral;
liquidationThreshold = reserve.liquidationThreshold;
usageAsCollateralEnabled = reserve.usageAsCollateralEnabled;
return (decimals, baseLTVasCollateral, liquidationThreshold, usageAsCollateralEnabled);
}
/**
* @dev returns the decimals of the reserve
* @param _reserve the reserve address
* @return the reserve decimals
**/
function getReserveDecimals(address _reserve) external view returns (uint256) {
return reserves[_reserve].decimals;
}
/**
* @dev returns true if the reserve is enabled for borrowing
* @param _reserve the reserve address
* @return true if the reserve is enabled for borrowing, false otherwise
**/
function isReserveBorrowingEnabled(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.borrowingEnabled;
}
/**
* @dev returns true if the reserve is enabled as collateral
* @param _reserve the reserve address
* @return true if the reserve is enabled as collateral, false otherwise
**/
function isReserveUsageAsCollateralEnabled(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.usageAsCollateralEnabled;
}
/**
* @dev returns true if the stable rate is enabled on reserve
* @param _reserve the reserve address
* @return true if the stable rate is enabled on reserve, false otherwise
**/
function getReserveIsStableBorrowRateEnabled(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.isStableBorrowRateEnabled;
}
/**
* @dev returns true if the reserve is active
* @param _reserve the reserve address
* @return true if the reserve is active, false otherwise
**/
function getReserveIsActive(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.isActive;
}
/**
* @notice returns if a reserve is freezed
* @param _reserve the reserve for which the information is needed
* @return true if the reserve is freezed, false otherwise
**/
function getReserveIsFreezed(address _reserve) external view returns (bool) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
return reserve.isFreezed;
}
/**
* @notice returns the timestamp of the last action on the reserve
* @param _reserve the reserve for which the information is needed
* @return the last updated timestamp of the reserve
**/
function getReserveLastUpdate(address _reserve) external view returns (uint40 timestamp) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
timestamp = reserve.lastUpdateTimestamp;
}
/**
* @dev returns the utilization rate U of a specific reserve
* @param _reserve the reserve for which the information is needed
* @return the utilization rate in ray
**/
function getReserveUtilizationRate(address _reserve) public view returns (uint256) {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
uint256 totalBorrows = reserve.getTotalBorrows();
if (totalBorrows == 0) {
return 0;
}
uint256 availableLiquidity = getReserveAvailableLiquidity(_reserve);
return totalBorrows.rayDiv(availableLiquidity.add(totalBorrows));
}
/**
* @return the array of reserves configured on the core
**/
function getReserves() external view returns (address[] memory) {
return reservesList;
}
/**
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return true if the user has chosen to use the reserve as collateral, false otherwise
**/
function isUserUseReserveAsCollateralEnabled(address _reserve, address _user)
external
view
returns (bool)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
return user.useAsCollateral;
}
/**
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the origination fee for the user
**/
function getUserOriginationFee(address _reserve, address _user)
external
view
returns (uint256)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
return user.originationFee;
}
/**
* @dev users with no loans in progress have NONE as borrow rate mode
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the borrow rate mode for the user,
**/
function getUserCurrentBorrowRateMode(address _reserve, address _user)
public
view
returns (CoreLibrary.InterestRateMode)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (user.principalBorrowBalance == 0) {
return CoreLibrary.InterestRateMode.NONE;
}
return
user.stableBorrowRate > 0
? CoreLibrary.InterestRateMode.STABLE
: CoreLibrary.InterestRateMode.VARIABLE;
}
/**
* @dev gets the current borrow rate of the user
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the borrow rate for the user,
**/
function getUserCurrentBorrowRate(address _reserve, address _user)
internal
view
returns (uint256)
{
CoreLibrary.InterestRateMode rateMode = getUserCurrentBorrowRateMode(_reserve, _user);
if (rateMode == CoreLibrary.InterestRateMode.NONE) {
return 0;
}
return
rateMode == CoreLibrary.InterestRateMode.STABLE
? usersReserveData[_user][_reserve].stableBorrowRate
: reserves[_reserve].currentVariableBorrowRate;
}
/**
* @dev the stable rate returned is 0 if the user is borrowing at variable or not borrowing at all
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the user stable rate
**/
function getUserCurrentStableBorrowRate(address _reserve, address _user)
external
view
returns (uint256)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
return user.stableBorrowRate;
}
/**
* @dev calculates and returns the borrow balances of the user
* @param _reserve the address of the reserve
* @param _user the address of the user
* @return the principal borrow balance, the compounded balance and the balance increase since the last borrow/repay/swap/rebalance
**/
function getUserBorrowBalances(address _reserve, address _user)
public
view
returns (uint256, uint256, uint256)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (user.principalBorrowBalance == 0) {
return (0, 0, 0);
}
uint256 principal = user.principalBorrowBalance;
uint256 compoundedBalance = CoreLibrary.getCompoundedBorrowBalance(
user,
reserves[_reserve]
);
return (principal, compoundedBalance, compoundedBalance.sub(principal));
}
/**
* @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the variable borrow index for the user
**/
function getUserVariableBorrowCumulativeIndex(address _reserve, address _user)
external
view
returns (uint256)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
return user.lastVariableBorrowCumulativeIndex;
}
/**
* @dev the variable borrow index of the user is 0 if the user is not borrowing or borrowing at stable
* @param _reserve the address of the reserve for which the information is needed
* @param _user the address of the user for which the information is needed
* @return the variable borrow index for the user
**/
function getUserLastUpdate(address _reserve, address _user)
external
view
returns (uint256 timestamp)
{
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
timestamp = user.lastUpdateTimestamp;
}
/**
* @dev updates the lending pool core configuration
**/
function refreshConfiguration() external onlyLendingPoolConfigurator {
refreshConfigInternal();
}
/**
* @dev initializes a reserve
* @param _reserve the address of the reserve
* @param _aTokenAddress the address of the overlying aToken contract
* @param _decimals the decimals of the reserve currency
* @param _interestRateStrategyAddress the address of the interest rate strategy contract
**/
function initReserve(
address _reserve,
address _aTokenAddress,
uint256 _decimals,
address _interestRateStrategyAddress
) external onlyLendingPoolConfigurator {
reserves[_reserve].init(_aTokenAddress, _decimals, _interestRateStrategyAddress);
addReserveToListInternal(_reserve);
}
/**
* @dev removes the last added reserve in the reservesList array
* @param _reserveToRemove the address of the reserve
**/
function removeLastAddedReserve(address _reserveToRemove)
external onlyLendingPoolConfigurator {
address lastReserve = reservesList[reservesList.length-1];
require(lastReserve == _reserveToRemove, "Reserve being removed is different than the reserve requested");
//as we can't check if totalLiquidity is 0 (since the reserve added might not be an ERC20) we at least check that there is nothing borrowed
require(getReserveTotalBorrows(lastReserve) == 0, "Cannot remove a reserve with liquidity deposited");
reserves[lastReserve].isActive = false;
reserves[lastReserve].aTokenAddress = address(0);
reserves[lastReserve].decimals = 0;
reserves[lastReserve].lastLiquidityCumulativeIndex = 0;
reserves[lastReserve].lastVariableBorrowCumulativeIndex = 0;
reserves[lastReserve].borrowingEnabled = false;
reserves[lastReserve].usageAsCollateralEnabled = false;
reserves[lastReserve].baseLTVasCollateral = 0;
reserves[lastReserve].liquidationThreshold = 0;
reserves[lastReserve].liquidationBonus = 0;
reserves[lastReserve].interestRateStrategyAddress = address(0);
reservesList.pop();
}
/**
* @dev updates the address of the interest rate strategy contract
* @param _reserve the address of the reserve
* @param _rateStrategyAddress the address of the interest rate strategy contract
**/
function setReserveInterestRateStrategyAddress(address _reserve, address _rateStrategyAddress)
external
onlyLendingPoolConfigurator
{
reserves[_reserve].interestRateStrategyAddress = _rateStrategyAddress;
}
/**
* @dev enables borrowing on a reserve. Also sets the stable rate borrowing
* @param _reserve the address of the reserve
* @param _stableBorrowRateEnabled true if the stable rate needs to be enabled, false otherwise
**/
function enableBorrowingOnReserve(address _reserve, bool _stableBorrowRateEnabled)
external
onlyLendingPoolConfigurator
{
reserves[_reserve].enableBorrowing(_stableBorrowRateEnabled);
}
/**
* @dev disables borrowing on a reserve
* @param _reserve the address of the reserve
**/
function disableBorrowingOnReserve(address _reserve) external onlyLendingPoolConfigurator {
reserves[_reserve].disableBorrowing();
}
/**
* @dev enables a reserve to be used as collateral
* @param _reserve the address of the reserve
**/
function enableReserveAsCollateral(
address _reserve,
uint256 _baseLTVasCollateral,
uint256 _liquidationThreshold,
uint256 _liquidationBonus
) external onlyLendingPoolConfigurator {
reserves[_reserve].enableAsCollateral(
_baseLTVasCollateral,
_liquidationThreshold,
_liquidationBonus
);
}
/**
* @dev disables a reserve to be used as collateral
* @param _reserve the address of the reserve
**/
function disableReserveAsCollateral(address _reserve) external onlyLendingPoolConfigurator {
reserves[_reserve].disableAsCollateral();
}
/**
* @dev enable the stable borrow rate mode on a reserve
* @param _reserve the address of the reserve
**/
function enableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isStableBorrowRateEnabled = true;
}
/**
* @dev disable the stable borrow rate mode on a reserve
* @param _reserve the address of the reserve
**/
function disableReserveStableBorrowRate(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isStableBorrowRateEnabled = false;
}
/**
* @dev activates a reserve
* @param _reserve the address of the reserve
**/
function activateReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
require(
reserve.lastLiquidityCumulativeIndex > 0 &&
reserve.lastVariableBorrowCumulativeIndex > 0,
"Reserve has not been initialized yet"
);
reserve.isActive = true;
}
/**
* @dev deactivates a reserve
* @param _reserve the address of the reserve
**/
function deactivateReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isActive = false;
}
/**
* @notice allows the configurator to freeze the reserve.
* A freezed reserve does not allow any action apart from repay, redeem, liquidationCall, rebalance.
* @param _reserve the address of the reserve
**/
function freezeReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isFreezed = true;
}
/**
* @notice allows the configurator to unfreeze the reserve. A unfreezed reserve allows any action to be executed.
* @param _reserve the address of the reserve
**/
function unfreezeReserve(address _reserve) external onlyLendingPoolConfigurator {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.isFreezed = false;
}
/**
* @notice allows the configurator to update the loan to value of a reserve
* @param _reserve the address of the reserve
* @param _ltv the new loan to value
**/
function setReserveBaseLTVasCollateral(address _reserve, uint256 _ltv)
external
onlyLendingPoolConfigurator
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.baseLTVasCollateral = _ltv;
}
/**
* @notice allows the configurator to update the liquidation threshold of a reserve
* @param _reserve the address of the reserve
* @param _threshold the new liquidation threshold
**/
function setReserveLiquidationThreshold(address _reserve, uint256 _threshold)
external
onlyLendingPoolConfigurator
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.liquidationThreshold = _threshold;
}
/**
* @notice allows the configurator to update the liquidation bonus of a reserve
* @param _reserve the address of the reserve
* @param _bonus the new liquidation bonus
**/
function setReserveLiquidationBonus(address _reserve, uint256 _bonus)
external
onlyLendingPoolConfigurator
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.liquidationBonus = _bonus;
}
/**
* @notice allows the configurator to update the reserve decimals
* @param _reserve the address of the reserve
* @param _decimals the decimals of the reserve
**/
function setReserveDecimals(address _reserve, uint256 _decimals)
external
onlyLendingPoolConfigurator
{
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
reserve.decimals = _decimals;
}
/**
* @notice internal functions
**/
/**
* @dev updates the state of a reserve as a consequence of a borrow action.
* @param _reserve the address of the reserve on which the user is borrowing
* @param _user the address of the borrower
* @param _principalBorrowBalance the previous borrow balance of the borrower before the action
* @param _balanceIncrease the accrued interest of the user on the previous borrowed amount
* @param _amountBorrowed the new amount borrowed
* @param _rateMode the borrow rate mode (stable, variable)
**/
function updateReserveStateOnBorrowInternal(
address _reserve,
address _user,
uint256 _principalBorrowBalance,
uint256 _balanceIncrease,
uint256 _amountBorrowed,
CoreLibrary.InterestRateMode _rateMode
) internal {
reserves[_reserve].updateCumulativeIndexes();
//increasing reserve total borrows to account for the new borrow balance of the user
//NOTE: Depending on the previous borrow mode, the borrows might need to be switched from variable to stable or vice versa
updateReserveTotalBorrowsByRateModeInternal(
_reserve,
_user,
_principalBorrowBalance,
_balanceIncrease,
_amountBorrowed,
_rateMode
);
}
/**
* @dev updates the state of a user as a consequence of a borrow action.
* @param _reserve the address of the reserve on which the user is borrowing
* @param _user the address of the borrower
* @param _amountBorrowed the amount borrowed
* @param _balanceIncrease the accrued interest of the user on the previous borrowed amount
* @param _rateMode the borrow rate mode (stable, variable)
* @return the final borrow rate for the user. Emitted by the borrow() event
**/
function updateUserStateOnBorrowInternal(
address _reserve,
address _user,
uint256 _amountBorrowed,
uint256 _balanceIncrease,
uint256 _fee,
CoreLibrary.InterestRateMode _rateMode
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
if (_rateMode == CoreLibrary.InterestRateMode.STABLE) {
//stable
//reset the user variable index, and update the stable rate
user.stableBorrowRate = reserve.currentStableBorrowRate;
user.lastVariableBorrowCumulativeIndex = 0;
} else if (_rateMode == CoreLibrary.InterestRateMode.VARIABLE) {
//variable
//reset the user stable rate, and store the new borrow index
user.stableBorrowRate = 0;
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
} else {
revert("Invalid borrow rate mode");
}
//increase the principal borrows and the origination fee
user.principalBorrowBalance = user.principalBorrowBalance.add(_amountBorrowed).add(
_balanceIncrease
);
user.originationFee = user.originationFee.add(_fee);
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
}
/**
* @dev updates the state of the reserve as a consequence of a repay action.
* @param _reserve the address of the reserve on which the user is repaying
* @param _user the address of the borrower
* @param _paybackAmountMinusFees the amount being paid back minus fees
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updateReserveStateOnRepayInternal(
address _reserve,
address _user,
uint256 _paybackAmountMinusFees,
uint256 _balanceIncrease
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_reserve][_user];
CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(_reserve, _user);
//update the indexes
reserves[_reserve].updateCumulativeIndexes();
//compound the cumulated interest to the borrow balance and then subtracting the payback amount
if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) {
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
_balanceIncrease,
user.stableBorrowRate
);
reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(
_paybackAmountMinusFees,
user.stableBorrowRate
);
} else {
reserve.increaseTotalBorrowsVariable(_balanceIncrease);
reserve.decreaseTotalBorrowsVariable(_paybackAmountMinusFees);
}
}
/**
* @dev updates the state of the user as a consequence of a repay action.
* @param _reserve the address of the reserve on which the user is repaying
* @param _user the address of the borrower
* @param _paybackAmountMinusFees the amount being paid back minus fees
* @param _originationFeeRepaid the fee on the amount that is being repaid
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _repaidWholeLoan true if the user is repaying the whole loan
**/
function updateUserStateOnRepayInternal(
address _reserve,
address _user,
uint256 _paybackAmountMinusFees,
uint256 _originationFeeRepaid,
uint256 _balanceIncrease,
bool _repaidWholeLoan
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
//update the user principal borrow balance, adding the cumulated interest and then subtracting the payback amount
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub(
_paybackAmountMinusFees
);
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
//if the balance decrease is equal to the previous principal (user is repaying the whole loan)
//and the rate mode is stable, we reset the interest rate mode of the user
if (_repaidWholeLoan) {
user.stableBorrowRate = 0;
user.lastVariableBorrowCumulativeIndex = 0;
}
user.originationFee = user.originationFee.sub(_originationFeeRepaid);
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
}
/**
* @dev updates the state of the user as a consequence of a swap rate action.
* @param _reserve the address of the reserve on which the user is performing the rate swap
* @param _user the address of the borrower
* @param _principalBorrowBalance the the principal amount borrowed by the user
* @param _compoundedBorrowBalance the principal amount plus the accrued interest
* @param _currentRateMode the rate mode at which the user borrowed
**/
function updateReserveStateOnSwapRateInternal(
address _reserve,
address _user,
uint256 _principalBorrowBalance,
uint256 _compoundedBorrowBalance,
CoreLibrary.InterestRateMode _currentRateMode
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
//compounding reserve indexes
reserve.updateCumulativeIndexes();
if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) {
uint256 userCurrentStableRate = user.stableBorrowRate;
//swap to variable
reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(
_principalBorrowBalance,
userCurrentStableRate
); //decreasing stable from old principal balance
reserve.increaseTotalBorrowsVariable(_compoundedBorrowBalance); //increase variable borrows
} else if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
//swap to stable
uint256 currentStableRate = reserve.currentStableBorrowRate;
reserve.decreaseTotalBorrowsVariable(_principalBorrowBalance);
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
_compoundedBorrowBalance,
currentStableRate
);
} else {
revert("Invalid rate mode received");
}
}
/**
* @dev updates the state of the user as a consequence of a swap rate action.
* @param _reserve the address of the reserve on which the user is performing the swap
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _currentRateMode the current rate mode of the user
**/
function updateUserStateOnSwapRateInternal(
address _reserve,
address _user,
uint256 _balanceIncrease,
CoreLibrary.InterestRateMode _currentRateMode
) internal returns (CoreLibrary.InterestRateMode) {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.InterestRateMode newMode = CoreLibrary.InterestRateMode.NONE;
if (_currentRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
//switch to stable
newMode = CoreLibrary.InterestRateMode.STABLE;
user.stableBorrowRate = reserve.currentStableBorrowRate;
user.lastVariableBorrowCumulativeIndex = 0;
} else if (_currentRateMode == CoreLibrary.InterestRateMode.STABLE) {
newMode = CoreLibrary.InterestRateMode.VARIABLE;
user.stableBorrowRate = 0;
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
} else {
revert("Invalid interest rate mode received");
}
//compounding cumulated interest
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease);
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
return newMode;
}
/**
* @dev updates the state of the principal reserve as a consequence of a liquidation action.
* @param _principalReserve the address of the principal reserve that is being repaid
* @param _user the address of the borrower
* @param _amountToLiquidate the amount being repaid by the liquidator
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updatePrincipalReserveStateOnLiquidationInternal(
address _principalReserve,
address _user,
uint256 _amountToLiquidate,
uint256 _balanceIncrease
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_principalReserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_principalReserve];
//update principal reserve data
reserve.updateCumulativeIndexes();
CoreLibrary.InterestRateMode borrowRateMode = getUserCurrentBorrowRateMode(
_principalReserve,
_user
);
if (borrowRateMode == CoreLibrary.InterestRateMode.STABLE) {
//increase the total borrows by the compounded interest
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
_balanceIncrease,
user.stableBorrowRate
);
//decrease by the actual amount to liquidate
reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(
_amountToLiquidate,
user.stableBorrowRate
);
} else {
//increase the total borrows by the compounded interest
reserve.increaseTotalBorrowsVariable(_balanceIncrease);
//decrease by the actual amount to liquidate
reserve.decreaseTotalBorrowsVariable(_amountToLiquidate);
}
}
/**
* @dev updates the state of the collateral reserve as a consequence of a liquidation action.
* @param _collateralReserve the address of the collateral reserve that is being liquidated
**/
function updateCollateralReserveStateOnLiquidationInternal(
address _collateralReserve
) internal {
//update collateral reserve
reserves[_collateralReserve].updateCumulativeIndexes();
}
/**
* @dev updates the state of the user being liquidated as a consequence of a liquidation action.
* @param _reserve the address of the principal reserve that is being repaid
* @param _user the address of the borrower
* @param _amountToLiquidate the amount being repaid by the liquidator
* @param _feeLiquidated the amount of origination fee being liquidated
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updateUserStateOnLiquidationInternal(
address _reserve,
address _user,
uint256 _amountToLiquidate,
uint256 _feeLiquidated,
uint256 _balanceIncrease
) internal {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
//first increase by the compounded interest, then decrease by the liquidated amount
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease).sub(
_amountToLiquidate
);
if (
getUserCurrentBorrowRateMode(_reserve, _user) == CoreLibrary.InterestRateMode.VARIABLE
) {
user.lastVariableBorrowCumulativeIndex = reserve.lastVariableBorrowCumulativeIndex;
}
if(_feeLiquidated > 0){
user.originationFee = user.originationFee.sub(_feeLiquidated);
}
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
}
/**
* @dev updates the state of the reserve as a consequence of a stable rate rebalance
* @param _reserve the address of the principal reserve where the user borrowed
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updateReserveStateOnRebalanceInternal(
address _reserve,
address _user,
uint256 _balanceIncrease
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
reserve.updateCumulativeIndexes();
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
_balanceIncrease,
user.stableBorrowRate
);
}
/**
* @dev updates the state of the user as a consequence of a stable rate rebalance
* @param _reserve the address of the principal reserve where the user borrowed
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
**/
function updateUserStateOnRebalanceInternal(
address _reserve,
address _user,
uint256 _balanceIncrease
) internal {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
user.principalBorrowBalance = user.principalBorrowBalance.add(_balanceIncrease);
user.stableBorrowRate = reserve.currentStableBorrowRate;
//solium-disable-next-line
user.lastUpdateTimestamp = uint40(block.timestamp);
}
/**
* @dev updates the state of the user as a consequence of a stable rate rebalance
* @param _reserve the address of the principal reserve where the user borrowed
* @param _user the address of the borrower
* @param _balanceIncrease the accrued interest on the borrowed amount
* @param _amountBorrowed the accrued interest on the borrowed amount
**/
function updateReserveTotalBorrowsByRateModeInternal(
address _reserve,
address _user,
uint256 _principalBalance,
uint256 _balanceIncrease,
uint256 _amountBorrowed,
CoreLibrary.InterestRateMode _newBorrowRateMode
) internal {
CoreLibrary.InterestRateMode previousRateMode = getUserCurrentBorrowRateMode(
_reserve,
_user
);
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
if (previousRateMode == CoreLibrary.InterestRateMode.STABLE) {
CoreLibrary.UserReserveData storage user = usersReserveData[_user][_reserve];
reserve.decreaseTotalBorrowsStableAndUpdateAverageRate(
_principalBalance,
user.stableBorrowRate
);
} else if (previousRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
reserve.decreaseTotalBorrowsVariable(_principalBalance);
}
uint256 newPrincipalAmount = _principalBalance.add(_balanceIncrease).add(_amountBorrowed);
if (_newBorrowRateMode == CoreLibrary.InterestRateMode.STABLE) {
reserve.increaseTotalBorrowsStableAndUpdateAverageRate(
newPrincipalAmount,
reserve.currentStableBorrowRate
);
} else if (_newBorrowRateMode == CoreLibrary.InterestRateMode.VARIABLE) {
reserve.increaseTotalBorrowsVariable(newPrincipalAmount);
} else {
revert("Invalid new borrow rate mode");
}
}
/**
* @dev Updates the reserve current stable borrow rate Rf, the current variable borrow rate Rv and the current liquidity rate Rl.
* Also updates the lastUpdateTimestamp value. Please refer to the whitepaper for further information.
* @param _reserve the address of the reserve to be updated
* @param _liquidityAdded the amount of liquidity added to the protocol (deposit or repay) in the previous action
* @param _liquidityTaken the amount of liquidity taken from the protocol (redeem or borrow)
**/
function updateReserveInterestRatesAndTimestampInternal(
address _reserve,
uint256 _liquidityAdded,
uint256 _liquidityTaken
) internal {
CoreLibrary.ReserveData storage reserve = reserves[_reserve];
(uint256 newLiquidityRate, uint256 newStableRate, uint256 newVariableRate) = IReserveInterestRateStrategy(
reserve
.interestRateStrategyAddress
)
.calculateInterestRates(
_reserve,
getReserveAvailableLiquidity(_reserve).add(_liquidityAdded).sub(_liquidityTaken),
reserve.totalBorrowsStable,
reserve.totalBorrowsVariable,
reserve.currentAverageStableBorrowRate
);
reserve.currentLiquidityRate = newLiquidityRate;
reserve.currentStableBorrowRate = newStableRate;
reserve.currentVariableBorrowRate = newVariableRate;
//solium-disable-next-line
reserve.lastUpdateTimestamp = uint40(block.timestamp);
emit ReserveUpdated(
_reserve,
newLiquidityRate,
newStableRate,
newVariableRate,
reserve.lastLiquidityCumulativeIndex,
reserve.lastVariableBorrowCumulativeIndex
);
}
/**
* @dev updates the internal configuration of the core
**/
function refreshConfigInternal() internal {
lendingPoolAddress = addressesProvider.getLendingPool();
}
/**
* @dev adds a reserve to the array of the reserves address
**/
function addReserveToListInternal(address _reserve) internal {
bool reserveAlreadyAdded = false;
for (uint256 i = 0; i < reservesList.length; i++)
if (reservesList[i] == _reserve) {
reserveAlreadyAdded = true;
}
if (!reserveAlreadyAdded) reservesList.push(_reserve);
}
}
|
transfers to the user a specific amount from the reserve. _reserve the address of the reserve where the transfer is happening _user the address of the user receiving the transfer _amount the amount being transferred/solium-disable-next-line
|
function transferToUser(address _reserve, address payable _user, uint256 _amount)
external
onlyLendingPool
{
if (_reserve != TrxAddressLib.trxAddress()) {
ERC20(_reserve).safeTransfer(_user, _amount);
(bool result, ) = _user.call.value(_amount).gas(50000)("");
require(result, "Transfer of TRX failed");
}
}
| 12,742,109 |
pragma solidity ^0.5.11;
import "./DonateTokenInterface.sol";
import "./EIP20Interface.sol";
import "./CTokenInterface.sol";
import "./UniswapFactoryInterface.sol";
import "./KyberNetworkProxyInterface.sol";
import "./TokenswapInterface.sol";
/**
* @dev Implementation of Growdrop. from creating growdrop to starting, funding, refunding, ending, withdraw.
*/
contract Growdrop {
/**
* @notice Address to get owner fee from Growdrop.
*/
address public owner;
/**
* @notice Check whether address is admin.
*/
mapping(address => bool) public CheckOwner;
/**
* @notice Current DonateToken contract
*/
DonateTokenInterface public DonateToken;
/**
* @notice Current Tokenswap contract
*/
TokenswapInterface public Tokenswap;
/**
* @notice Growdrop's sequential number
*/
uint256 public GrowdropCount;
/**
* @notice Growdrop event's sequential number
*/
uint256 public EventIdx;
/**
* @notice Address of receiving accrued interest address by Growdrop's identifier
*/
mapping(uint256 => address) public Beneficiary;
/**
* @notice Compound CToken amount per investor address by Growdrop's identifier
*/
mapping(uint256 => mapping(address => uint256)) public CTokenPerAddress;
/**
* @notice Funded ERC20 token amount per investor address by Growdrop's identifier
*/
mapping(uint256 => mapping(address => uint256)) public InvestAmountPerAddress;
/**
* @notice Actual amount per investor address by Growdrop's identifier
*/
mapping(uint256 => mapping(address => uint256)) public ActualPerAddress;
/**
* @notice Actual Compound CToken amount per investor address by Growdrop's identifier
*/
mapping(uint256 => mapping(address => uint256)) public ActualCTokenPerAddress;
/**
* @notice Check whether address withdrawn or not by Growdrop's identifier
*/
mapping(uint256 => mapping(address => bool)) public WithdrawOver;
/**
* @notice ERC20 token amount to send to investors by Growdrop's identifier
*/
mapping(uint256 => uint256) public GrowdropAmount;
/**
* @notice Growdrop's start timestamp by Growdrop's identifier
*/
mapping(uint256 => uint256) public GrowdropStartTime;
/**
* @notice Growdrop's end timestamp by Growdrop's identifier
*/
mapping(uint256 => uint256) public GrowdropEndTime;
/**
* @notice Growdrop's total funded ERC20 token amount by Growdrop's identifier
*/
mapping(uint256 => uint256) public TotalMintedAmount;
/**
* @notice Growdrop's total Compound CToken amount by Growdrop's identifier
*/
mapping(uint256 => uint256) public TotalCTokenAmount;
/**
* @notice Growdrop's total actual amount by Growdrop's identifier
*/
mapping(uint256 => uint256) public TotalMintedActual;
/**
* @notice Growdrop's total actual Compound CToken amount by Growdrop's identifier
*/
mapping(uint256 => uint256) public TotalCTokenActual;
/**
* @notice Compound's exchange rate when Growdrop is over by Growdrop's identifier
*/
mapping(uint256 => uint256) public ExchangeRateOver;
/**
* @notice Growdrop's total accrued interest when Growdrop is over by Growdrop's identifier
*/
mapping(uint256 => uint256) public TotalInterestOver;
/**
* @notice Growdrop's total actual accrued interest when Growdrop is over by Growdrop's identifier
*/
mapping(uint256 => uint256) public TotalInterestOverActual;
/**
* @notice ERC20 token amount to add to UniswapExchange by Growdrop's identifier
*/
mapping(uint256 => uint256) public ToUniswapTokenAmount;
/**
* @notice Percentage of Growdrop's total accrued interest to add to UniswapExchage by Growdrop's identifier
*/
mapping(uint256 => uint256) public ToUniswapInterestRate;
/**
* @notice Check whether Growdrop is over by Growdrop's identifier
*/
mapping(uint256 => bool) public GrowdropOver;
/**
* @notice Check whether Growdrop is started by Growdrop's identifier
*/
mapping(uint256 => bool) public GrowdropStart;
/**
* @notice Growdrop's Donation identifier by Growdrop's identifier
*/
mapping(uint256 => uint256) public DonateId;
/**
* @notice ERC20 Token to fund by Growdrop's identifier
*/
mapping(uint256 => EIP20Interface) public Token;
/**
* @notice ERC20 Token to send to investors by Growdrop's identifier
*/
mapping(uint256 => EIP20Interface) public GrowdropToken;
/**
* @notice Compound CToken by Growdrop's identifier
*/
mapping(uint256 => CTokenInterface) public CToken;
/**
* @notice Percentage of owner fee to get from Growdrop's total accrued interest by Growdrop's identifier
*/
mapping(uint256 => uint256) public GrowdropOwnerFeePercent;
/**
* @notice Check whether Growdrop adds liquidity to UniswapExchange
*/
mapping(uint256 => bool) public AddToUniswap;
/**
* @notice Current percentage of owner fee
*/
uint256 public CurrentOwnerFeePercent;
/**
* @notice Total funded ERC20 token amount with investor address and ERC20 token address
*/
mapping(address => mapping(address => uint256)) public TotalUserInvestedAmount;
/**
* @notice Event emitted when new Growdrop is created
*/
event NewGrowdrop(
uint256 indexed event_idx,
uint256 indexed growdrop_count,
address indexed from_address,
uint256 timestamp
);
/**
* @notice Event emitted when Growdrop's event occurred
*/
event GrowdropAction(
uint256 indexed event_idx,
uint256 indexed growdrop_count,
address indexed from_address,
uint256 amount1,
uint256 amount2,
uint256 action_idx,
uint256 timestamp
);
/**
* @notice Event emitted when Growdrop's donation ERC721 token event occurred
*/
event DonateAction(
uint256 indexed event_idx,
address indexed from_address,
address indexed to_address,
address supporter,
address beneficiary,
address token_address,
uint256 donate_id,
uint256 token_id,
uint256 amount,
uint256 action_idx,
uint256 timestamp
);
/**
* @dev Constructor, set 'owner' and set 'CurrentOwnerFeePercent'.
*/
constructor () public {
owner = msg.sender;
CheckOwner[msg.sender] = true;
CurrentOwnerFeePercent = 3;
}
/**
* @dev Create new Growdrop.
* Only Address that 'CheckOwner' is true can call.
* 'GrowdropTokenAddr' cannot be tokens which is in Compound's available markets.
*
* Emits {NewGrowdrop} event indicating Growdrop's identifier.
*
* @param TokenAddr ERC20 token address to fund tokens
* @param CTokenAddr Compound CToken address which is pair of 'TokenAddr'
* @param GrowdropTokenAddr ERC20 token address to send tokens to investors
* @param BeneficiaryAddr address to receive Growdrop's accrued interest amount
* @param _GrowdropAmount ERC20 token amount to send to investors
* @param GrowdropPeriod period timestamp to get funds
* @param _ToUniswapTokenAmount ERC20 token amount to add to UniswapExchange. If project does not want to add liquidity to UniswapExchage at all, 0.
* @param _ToUniswapInterestRate percentage of Growdrop's accrued interest amount to add liquidity to UniswapExchange.
* @param _DonateId Growdrop's donation identifier. If Growdrop is donation, not 0. else 0
*/
function newGrowdrop(
address TokenAddr,
address CTokenAddr,
address GrowdropTokenAddr,
address BeneficiaryAddr,
uint256 _GrowdropAmount,
uint256 GrowdropPeriod,
uint256 _ToUniswapTokenAmount,
uint256 _ToUniswapInterestRate,
uint256 _DonateId) public {
require(CheckOwner[msg.sender]);
require(DonateToken.DonateIdOwner(_DonateId)==BeneficiaryAddr || _DonateId==0);
require(_ToUniswapTokenAmount==0 || (_ToUniswapInterestRate>0 && _ToUniswapInterestRate<101-CurrentOwnerFeePercent && _ToUniswapTokenAmount>1e4));
require(_DonateId!=0 || _GrowdropAmount>1e6);
Add(_GrowdropAmount,_ToUniswapTokenAmount);
GrowdropCount += 1;
GrowdropOwnerFeePercent[GrowdropCount] = CurrentOwnerFeePercent;
AddToUniswap[GrowdropCount] = _ToUniswapTokenAmount==0 ? false : true;
Token[GrowdropCount] = EIP20Interface(TokenAddr);
CToken[GrowdropCount] = CTokenInterface(CTokenAddr);
GrowdropToken[GrowdropCount] = EIP20Interface(GrowdropTokenAddr);
Beneficiary[GrowdropCount] = BeneficiaryAddr;
GrowdropAmount[GrowdropCount] = _GrowdropAmount;
GrowdropEndTime[GrowdropCount] = GrowdropPeriod;
ToUniswapTokenAmount[GrowdropCount] = _ToUniswapTokenAmount;
ToUniswapInterestRate[GrowdropCount] = _ToUniswapInterestRate;
DonateId[GrowdropCount] = _DonateId;
EventIdx += 1;
emit NewGrowdrop(EventIdx, GrowdropCount, BeneficiaryAddr, now);
}
/**
* @dev Start Growdrop by Growdrop's identifier.
* Only 'Beneficiary' address can call.
* Transfers ERC20 token amount of 'GrowdropAmount' and 'ToUniswapTokenAmount' to this contract.
*
* Emits {GrowdropAction} event indicating Growdrop's identifier and event information.
*
* @param _GrowdropCount Growdrop's identifier
*/
function StartGrowdrop(uint256 _GrowdropCount) public {
require(msg.sender==Beneficiary[_GrowdropCount], "not beneficiary");
require(!GrowdropStart[_GrowdropCount], "already started");
GrowdropStart[_GrowdropCount] = true;
if(DonateId[_GrowdropCount]==0) {
require(GrowdropToken[_GrowdropCount].transferFrom(msg.sender, address(this), GrowdropAmount[_GrowdropCount]+ToUniswapTokenAmount[_GrowdropCount]), "transfer growdrop error");
}
GrowdropStartTime[_GrowdropCount] = now;
GrowdropEndTime[_GrowdropCount] = Add(GrowdropEndTime[_GrowdropCount], now);
EventIdx += 1;
emit GrowdropAction(EventIdx, _GrowdropCount, address(0x0), 0, 0, 5, now);
}
/**
* @dev Investor funds ERC20 token to Growdrop by Growdrop's identifier.
* Should be approved before call.
* Funding amount will be calculated as CToken and recalculated to minimum which has same value as calculated CToken before funding.
* Funding ctoken amount should be bigger than 0.
* Can be funded only with Growdrop's 'Token'.
* Can fund only after started and before ended.
*
* Emits {GrowdropAction} event indicating Growdrop's identifier and event information.
*
* @param _GrowdropCount Growdrop's identifier
* @param Amount ERC20 token amount to fund to Growdrop
*/
function Mint(uint256 _GrowdropCount, uint256 Amount) public {
require(GrowdropStart[_GrowdropCount], "not started");
require(now<GrowdropEndTime[_GrowdropCount], "already ended");
require(msg.sender!=Beneficiary[_GrowdropCount], "beneficiary cannot mint");
uint256 _exchangeRateCurrent = CToken[_GrowdropCount].exchangeRateCurrent();
uint256 _ctoken;
uint256 _toMinAmount;
(_ctoken, _toMinAmount) = toMinAmount(Amount, _exchangeRateCurrent);
require(_ctoken>0, "amount too low");
uint256 actualAmount;
uint256 actualCToken;
(actualCToken, actualAmount) = toActualAmount(_toMinAmount, _exchangeRateCurrent);
CTokenPerAddress[_GrowdropCount][msg.sender] = Add(CTokenPerAddress[_GrowdropCount][msg.sender], _ctoken);
TotalCTokenAmount[_GrowdropCount] = Add(TotalCTokenAmount[_GrowdropCount], _ctoken);
ActualCTokenPerAddress[_GrowdropCount][msg.sender] = Add(ActualCTokenPerAddress[_GrowdropCount][msg.sender], actualCToken);
TotalCTokenActual[_GrowdropCount] = Add(TotalCTokenActual[_GrowdropCount], actualCToken);
InvestAmountPerAddress[_GrowdropCount][msg.sender] = Add(InvestAmountPerAddress[_GrowdropCount][msg.sender], _toMinAmount);
TotalMintedAmount[_GrowdropCount] = Add(TotalMintedAmount[_GrowdropCount], _toMinAmount);
ActualPerAddress[_GrowdropCount][msg.sender] = Add(ActualPerAddress[_GrowdropCount][msg.sender], actualAmount);
TotalMintedActual[_GrowdropCount] = Add(TotalMintedActual[_GrowdropCount], actualAmount);
require(Token[_GrowdropCount].transferFrom(msg.sender, address(this), _toMinAmount), "transfer token error");
require(Token[_GrowdropCount].approve(address(CToken[_GrowdropCount]), _toMinAmount), "approve token error");
require(CToken[_GrowdropCount].mint(_toMinAmount)==0, "error in mint");
TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])] = Add(TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])],_toMinAmount);
EventIdx += 1;
emit GrowdropAction(EventIdx,_GrowdropCount, msg.sender, InvestAmountPerAddress[_GrowdropCount][msg.sender], CTokenPerAddress[_GrowdropCount][msg.sender], 0, now);
}
/**
* @dev Investor refunds ERC20 token to Growdrop by Growdrop's identifier.
* Refunding CToken amount should be bigger than 0.
* Refunding amount calculated as CToken should be smaller than investor's funded amount calculated as CToken by Growdrop's identifier.
* Can refund only after started and before ended.
*
* Emits {GrowdropAction} event indicating Growdrop's identifier and event information.
*
* @param _GrowdropCount Growdrop's identifier
* @param Amount ERC20 token amount to refund to Growdrop
*/
function Redeem(uint256 _GrowdropCount, uint256 Amount) public {
require(GrowdropStart[_GrowdropCount], "not started");
require(now<GrowdropEndTime[_GrowdropCount], "already ended");
uint256 _exchangeRateCurrent = CToken[_GrowdropCount].exchangeRateCurrent();
uint256 _ctoken;
uint256 _toMinAmount;
(_ctoken,_toMinAmount) = toMinAmount(Amount, _exchangeRateCurrent);
require(_ctoken>0 && _ctoken<=MulAndDiv(InvestAmountPerAddress[_GrowdropCount][msg.sender], 1e18, _exchangeRateCurrent), "redeem error");
uint256 actualAmount;
uint256 actualCToken;
(actualCToken, actualAmount) = toActualAmount(_toMinAmount, _exchangeRateCurrent);
CTokenPerAddress[_GrowdropCount][msg.sender] = Sub(CTokenPerAddress[_GrowdropCount][msg.sender], _ctoken);
TotalCTokenAmount[_GrowdropCount] = Sub(TotalCTokenAmount[_GrowdropCount],_ctoken);
ActualCTokenPerAddress[_GrowdropCount][msg.sender] = Sub(ActualCTokenPerAddress[_GrowdropCount][msg.sender], actualCToken);
TotalCTokenActual[_GrowdropCount] = Sub(TotalCTokenActual[_GrowdropCount], actualCToken);
InvestAmountPerAddress[_GrowdropCount][msg.sender] = Sub(InvestAmountPerAddress[_GrowdropCount][msg.sender], _toMinAmount);
TotalMintedAmount[_GrowdropCount] = Sub(TotalMintedAmount[_GrowdropCount], _toMinAmount);
ActualPerAddress[_GrowdropCount][msg.sender] = Sub(ActualPerAddress[_GrowdropCount][msg.sender], actualAmount);
TotalMintedActual[_GrowdropCount] = Sub(TotalMintedActual[_GrowdropCount], actualAmount);
require(CToken[_GrowdropCount].redeemUnderlying(Amount)==0, "error in redeem");
require(Token[_GrowdropCount].transfer(msg.sender, Amount), "transfer token error");
TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])] = Sub(TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])], _toMinAmount);
EventIdx += 1;
emit GrowdropAction(EventIdx, _GrowdropCount, msg.sender, InvestAmountPerAddress[_GrowdropCount][msg.sender], CTokenPerAddress[_GrowdropCount][msg.sender], 1, now);
}
/**
* @dev Investor and Investee withdraws from Growdrop by Growdrop's identifier.
* Investor withdraws investor's all funded ERC20 token amount and 'GrowdropToken' calculated by percentage of investor's accrued interest amount.
* If Growdrop is donation, Investor withdraws investor's all funded ERC20 token amount and ERC721 token from 'DonateToken'.
* Investee withdraws all investor's accrued interest if 'ToUniswap' is false.
* Else add liquidity to Uniswap with 'ToUniswapInterestRate' percentage of all investor's accrued interest amount and 'ToUniswapTokenAmount' ERC20 token
* and withdraw rest of all investor's accured interest amount.
* If Growdrop is donation, Investee withdraws investor's all funded ERC20 token amount.
* Owner fee is transferred when Investee withdraws.
* Can withdraw only once per address.
* Can withdraw only after ended.
*
* Emits {GrowdropAction} event indicating Growdrop's identifier and event information.
* Emits {DonateAction} event indicating ERC721 token information from 'DonateToken' if Growdrop is donation.
*
* @param _GrowdropCount Growdrop's identifier
* @param ToUniswap if investee wants to add liquidity to UniswapExchange, true. Else false.
*/
function Withdraw(uint256 _GrowdropCount, bool ToUniswap) public {
require(!WithdrawOver[_GrowdropCount][msg.sender], "already done");
WithdrawOver[_GrowdropCount][msg.sender] = true;
EndGrowdrop(_GrowdropCount);
//If investee did not want to add to UniswapExchange, does not add to UniswapExchange.
if(!AddToUniswap[_GrowdropCount]) {
ToUniswap = false;
}
//If caller is investee
if(msg.sender==Beneficiary[_GrowdropCount]) {
uint256 beneficiaryinterest;
bool success;
if(TotalInterestOverActual[_GrowdropCount]==0) {
ToUniswap=false;
success=true;
}
uint256 OwnerFee = MulAndDiv(TotalInterestOver[_GrowdropCount], GrowdropOwnerFeePercent[_GrowdropCount], 100);
if(ToUniswap) {
uint256 ToUniswapInterestRateCalculated = MulAndDiv(TotalInterestOver[_GrowdropCount], ToUniswapInterestRate[_GrowdropCount], 100);
beneficiaryinterest = TotalInterestOver[_GrowdropCount]-ToUniswapInterestRateCalculated-OwnerFee;
require(Token[_GrowdropCount].approve(address(Tokenswap), ToUniswapInterestRateCalculated), "approve token error");
require(GrowdropToken[_GrowdropCount].approve(address(Tokenswap), ToUniswapTokenAmount[_GrowdropCount]), "approve growdrop error");
success = Tokenswap.addPoolToUniswap(
address(Token[_GrowdropCount]),
address(GrowdropToken[_GrowdropCount]),
Beneficiary[_GrowdropCount],
ToUniswapInterestRateCalculated,
ToUniswapTokenAmount[_GrowdropCount]
);
if(!success) {
beneficiaryinterest += ToUniswapInterestRateCalculated;
}
} else {
beneficiaryinterest = TotalInterestOver[_GrowdropCount]-OwnerFee;
if(DonateId[_GrowdropCount]!=0) {
success=true;
}
}
sendTokenInWithdraw(_GrowdropCount, Beneficiary[_GrowdropCount], beneficiaryinterest, success ? 0 : ToUniswapTokenAmount[_GrowdropCount]);
require(Token[_GrowdropCount].transfer(owner, OwnerFee), "transfer fee error");
EventIdx += 1;
emit GrowdropAction(EventIdx, _GrowdropCount, msg.sender, beneficiaryinterest, success ? 1 : 0, 2, now);
} else {
//If caller is investor
uint256 investorTotalInterest = MulAndDiv(ActualCTokenPerAddress[_GrowdropCount][msg.sender], ExchangeRateOver[_GrowdropCount], 1) - ActualPerAddress[_GrowdropCount][msg.sender];
uint256 tokenByInterest = DonateId[_GrowdropCount]==0 ? MulAndDiv(
investorTotalInterest,
GrowdropAmount[_GrowdropCount],
(TotalInterestOverActual[_GrowdropCount]==0 ? 1 : TotalInterestOverActual[_GrowdropCount])
) : investorTotalInterest;
tokenByInterest = sendTokenInWithdraw(_GrowdropCount, msg.sender, InvestAmountPerAddress[_GrowdropCount][msg.sender], tokenByInterest);
TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])] = Sub(TotalUserInvestedAmount[msg.sender][address(Token[_GrowdropCount])], InvestAmountPerAddress[_GrowdropCount][msg.sender]);
EventIdx += 1;
emit GrowdropAction(EventIdx, _GrowdropCount, msg.sender, InvestAmountPerAddress[_GrowdropCount][msg.sender], tokenByInterest, 3, now);
}
}
/**
* @dev Transfers ERC20 tokens to 'To' address.
* If Growdrop by '_GrowdropCount' is donation, 'DonateToken' mints new ERC721 token.
*
* Emits {DonateAction} event indicating ERC721 token information from 'DonateToken' if Growdrop is donation.
*
* @param _GrowdropCount Growdrop's identifier
* @param To address to send ERC20 tokens
* @param TokenAmount ERC20 token amount of 'Token'
* @param GrowdropTokenAmount ERC20 token amount of 'GrowdropToken'
* @return if Growdrop by '_GrowdropCount' is donation, return new ERC721 token's identifier. Else return ERC20 token amount of 'GrowdropToken'
*/
function sendTokenInWithdraw(uint256 _GrowdropCount, address To, uint256 TokenAmount, uint256 GrowdropTokenAmount) private returns (uint256) {
require(Token[_GrowdropCount].transfer(To, TokenAmount), "transfer token error");
if(DonateId[_GrowdropCount]==0) {
require(GrowdropToken[_GrowdropCount].transfer(To, GrowdropTokenAmount), "transfer growdrop error");
return GrowdropTokenAmount;
} else {
return DonateToken.mint(msg.sender, Beneficiary[_GrowdropCount], address(Token[_GrowdropCount]), GrowdropTokenAmount, DonateId[_GrowdropCount]);
}
}
/**
* @dev Ends Growdrop by '_GrowdropCount'.
* If total actual accrued interest is 0 and Growdrop is not donation, transfers 'GrowdropAmount' and 'ToUniswapTokenAmount' back to 'Beneficiary'.
* Total accrued interest is calculated -> maximum amount of Growdrop's all CToken to ERC20 token - total funded ERC20 amount of Growdrop.
*
* Emits {GrowdropAction} event indicating Growdrop's identifier and event information.
*
* @param _GrowdropCount Growdrop's identifier
*/
function EndGrowdrop(uint256 _GrowdropCount) private {
require(GrowdropStart[_GrowdropCount] && GrowdropEndTime[_GrowdropCount]<=now, "cannot end now");
if(!GrowdropOver[_GrowdropCount]) {
GrowdropOver[_GrowdropCount] = true;
ExchangeRateOver[_GrowdropCount] = CToken[_GrowdropCount].exchangeRateCurrent();
uint256 _toAmount = TotalCTokenAmount[_GrowdropCount]>0 ? MulAndDiv(TotalCTokenAmount[_GrowdropCount]+1, ExchangeRateOver[_GrowdropCount], 1e18) : 0;
if(TotalCTokenAmount[_GrowdropCount]!=0) {
require(CToken[_GrowdropCount].redeemUnderlying(_toAmount)==0, "error in redeem");
}
TotalInterestOverActual[_GrowdropCount] = MulAndDiv(TotalCTokenActual[_GrowdropCount], ExchangeRateOver[_GrowdropCount], 1) - TotalMintedActual[_GrowdropCount];
TotalInterestOver[_GrowdropCount] = _toAmount>TotalMintedAmount[_GrowdropCount] ? _toAmount-TotalMintedAmount[_GrowdropCount] : 0;
if(TotalInterestOverActual[_GrowdropCount]==0) {
if(DonateId[_GrowdropCount]==0) {
require(
GrowdropToken[_GrowdropCount].transfer(
Beneficiary[_GrowdropCount],
GrowdropAmount[_GrowdropCount]+ToUniswapTokenAmount[_GrowdropCount]
)
);
}
}
EventIdx += 1;
emit GrowdropAction(EventIdx, _GrowdropCount, msg.sender, TotalInterestOverActual[_GrowdropCount]==0 ? 1 : 0, 0, 6, now);
}
}
/**
* @dev Calculates CToken and maximum amount of ERC20 token from ERC20 token amount and exchange rate of Compound CToken.
* @param tokenAmount ERC20 token amount
* @param exchangeRate exchange rate of Compound CToken
* @return calculated CToken amount
* @return calculated maximum amount of ERC20 token
*/
function toMaxAmount(uint256 tokenAmount, uint256 exchangeRate) private pure returns (uint256, uint256) {
uint256 _ctoken = MulAndDiv(tokenAmount, 1e18, exchangeRate);
return (_ctoken, MulAndDiv(
Add(_ctoken, 1),
exchangeRate,
1e18
));
}
/**
* @dev Calculates CToken and minimum amount of ERC20 token from ERC20 token amount and exchange rate of Compound CToken.
* @param tokenAmount ERC20 token amount
* @param exchangeRate exchange rate of Compound CToken
* @return calculated CToken amount
* @return calculated minimum amount of ERC20 token
*/
function toMinAmount(uint256 tokenAmount, uint256 exchangeRate) private pure returns (uint256, uint256) {
uint256 _ctoken = MulAndDiv(tokenAmount, 1e18, exchangeRate);
return (_ctoken, Add(
MulAndDiv(
_ctoken,
exchangeRate,
1e18
),
1
));
}
/**
* @dev Calculates actual CToken and amount of ERC20 token from ERC20 token amount and exchange rate of Compound CToken.
* Need for calculating percentage of interest accrued.
* @param tokenAmount ERC20 token amount
* @param exchangeRate exchange rate of Compound CToken
* @return calculated actual CToken amount
* @return calculated actual minimum amount of ERC20 token
*/
function toActualAmount(uint256 tokenAmount, uint256 exchangeRate) private pure returns (uint256, uint256) {
uint256 _ctoken = MulAndDiv(tokenAmount, 1e29, exchangeRate);
uint256 _token = MulAndDiv(_ctoken, exchangeRate, 1);
return (_ctoken, _token);
}
function MulAndDiv(uint256 a, uint256 b, uint256 c) private pure returns (uint256) {
uint256 temp = a*b;
require(temp/b==a && c>0, "arithmetic error");
return temp/c;
}
function Add(uint256 a, uint256 b) private pure returns (uint256) {
require(a+b>=a, "add overflow");
return a+b;
}
function Sub(uint256 a, uint256 b) private pure returns (uint256) {
require(a>=b, "subtract overflow");
return a-b;
}
/**
* @dev Emits {DonateAction} event from 'DonateToken' contract.
* Only 'DonateToken' contract can call.
*
* Emits {DonateAction} event indicating ERC721 token information from 'DonateToken'.
*
* @param From 'DonateToken' ERC721 token's previous owner
* @param To 'DonateToken' ERC721 token's next owner
* @param Supporter 'DonateToken' ERC721 token's 'supporter'
* @param beneficiary 'DonateToken' ERC721 token's 'beneficiary'
* @param token 'DonateToken' ERC721 token's 'tokenAddress'
* @param donateId 'DonateToken' ERC721 token's 'donateId'
* @param tokenId 'DonateToken' ERC721 token's identifier
* @param Amount 'DonateToken' ERC721 token's 'tokenAmount'
* @param ActionIdx DonateAction event identifier
* @return EventIdx event sequential identifier
*/
function emitDonateActionEvent(
address From,
address To,
address Supporter,
address beneficiary,
address token,
uint256 donateId,
uint256 tokenId,
uint256 Amount,
uint256 ActionIdx) public returns (uint256) {
require(msg.sender==address(DonateToken), "not donatetoken contract");
EventIdx += 1;
emit DonateAction(EventIdx, From, To, Supporter, beneficiary, token, donateId, tokenId, Amount, ActionIdx, now);
return EventIdx;
}
/**
* @dev Set 'DonateToken' contract address.
* @param DonateTokenAddress 'DonateToken' contract address
*/
function setDonateToken(address DonateTokenAddress) public {
require(CheckOwner[msg.sender]);
DonateToken = DonateTokenInterface(DonateTokenAddress);
}
/**
* @dev Set 'Tokenswap' contract address.
* @param TokenswapAddress 'Tokenswap' contract address
*/
function setTokenswap(address TokenswapAddress) public {
require(CheckOwner[msg.sender]);
Tokenswap = TokenswapInterface(TokenswapAddress);
}
/**
* @dev Change 'CheckOwner' state of address .
* @param _Owner address to change state
*/
function addOwner(address _Owner) public {
require(CheckOwner[msg.sender]);
CheckOwner[_Owner] = !CheckOwner[_Owner];
}
/**
* @dev Set 'owner' address .
* @param _Owner address to set
*/
function setOwner(address _Owner) public {
require(CheckOwner[msg.sender] && CheckOwner[_Owner], "not proper owner");
owner=_Owner;
}
/**
* @dev Set 'CurrentOwnerFeePercent'.
* @param _OwnerFeePercent value to set
*/
function setOwnerFeePercent(uint256 _OwnerFeePercent) public {
require(CheckOwner[msg.sender], "not owner");
require(_OwnerFeePercent>0 && _OwnerFeePercent<100, "not proper percent");
CurrentOwnerFeePercent=_OwnerFeePercent;
}
function () external payable {
}
}
|
Set 'DonateToken' contract address. DonateTokenAddress 'DonateToken' contract address/
|
function setDonateToken(address DonateTokenAddress) public {
require(CheckOwner[msg.sender]);
DonateToken = DonateTokenInterface(DonateTokenAddress);
}
| 7,299,698 |
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();
}
}
contract IController is Pausable {
event SetContractInfo(bytes32 id, address contractAddress, bytes20 gitCommitHash);
function setContractInfo(bytes32 _id, address _contractAddress, bytes20 _gitCommitHash) external;
function updateController(bytes32 _id, address _controller) external;
function getContract(bytes32 _id) public view returns (address);
}
contract IManager {
event SetController(address controller);
event ParameterUpdate(string param);
function setController(address _controller) external;
}
contract Manager is IManager {
// Controller that contract is registered with
IController public controller;
// Check if sender is controller
modifier onlyController() {
require(msg.sender == address(controller));
_;
}
// Check if sender is controller owner
modifier onlyControllerOwner() {
require(msg.sender == controller.owner());
_;
}
// Check if controller is not paused
modifier whenSystemNotPaused() {
require(!controller.paused());
_;
}
// Check if controller is paused
modifier whenSystemPaused() {
require(controller.paused());
_;
}
function Manager(address _controller) public {
controller = IController(_controller);
}
/*
* @dev Set controller. Only callable by current controller
* @param _controller Controller contract address
*/
function setController(address _controller) external onlyController {
controller = IController(_controller);
SetController(_controller);
}
}
/**
* @title Interface for a Verifier. Can be backed by any implementaiton including oracles or Truebit
*/
contract IVerifier {
function verify(
uint256 _jobId,
uint256 _claimId,
uint256 _segmentNumber,
string _transcodingOptions,
string _dataStorageHash,
bytes32[2] _dataHashes
)
external
payable;
function getPrice() public view returns (uint256);
}
/*
* @title Interface for contract that receives verification results
*/
contract IVerifiable {
// External functions
function receiveVerification(uint256 _jobId, uint256 _claimId, uint256 _segmentNumber, bool _result) external;
}
/**
* @title LivepeerVerifier
* @dev Manages transcoding verification requests that are processed by a trusted solver
*/
contract LivepeerVerifier is Manager, IVerifier {
// IPFS hash of verification computation archive
string public verificationCodeHash;
// Solver that can submit results for requests
address public solver;
struct Request {
uint256 jobId;
uint256 claimId;
uint256 segmentNumber;
bytes32 commitHash;
}
mapping (uint256 => Request) public requests;
uint256 public requestCount;
event VerifyRequest(uint256 indexed requestId, uint256 indexed jobId, uint256 indexed claimId, uint256 segmentNumber, string transcodingOptions, string dataStorageHash, bytes32 dataHash, bytes32 transcodedDataHash);
event Callback(uint256 indexed requestId, uint256 indexed jobId, uint256 indexed claimId, uint256 segmentNumber, bool result);
event SolverUpdate(address solver);
// Check if sender is JobsManager
modifier onlyJobsManager() {
require(msg.sender == controller.getContract(keccak256("JobsManager")));
_;
}
// Check if sender is a solver
modifier onlySolver() {
require(msg.sender == solver);
_;
}
/**
* @dev LivepeerVerifier constructor
* @param _controller Controller address
* @param _solver Solver address to register
* @param _verificationCodeHash Content addressed hash specifying location of transcoding verification code
*/
function LivepeerVerifier(address _controller, address _solver, string _verificationCodeHash) public Manager(_controller) {
// Solver must not be null address
require(_solver != address(0));
// Set solver
solver = _solver;
// Set verification code hash
verificationCodeHash = _verificationCodeHash;
}
/**
* @dev Set content addressed hash specifying location of transcoding verification code. Only callable by Controller owner
* @param _verificationCodeHash Content addressed hash specifying location of transcoding verification code
*/
function setVerificationCodeHash(string _verificationCodeHash) external onlyControllerOwner {
verificationCodeHash = _verificationCodeHash;
}
/**
* @dev Set registered solver address that is allowed to submit the result of transcoding verification computation
* via `__callback()`. Only callable by Controller owner
* @param _solver Solver address to register
*/
function setSolver(address _solver) external onlyControllerOwner {
// Must not be null address
require(_solver != address(0));
solver = _solver;
SolverUpdate(_solver);
}
/**
* @dev Fire VerifyRequest event which solvers should listen for to retrieve verification parameters
*/
function verify(
uint256 _jobId,
uint256 _claimId,
uint256 _segmentNumber,
string _transcodingOptions,
string _dataStorageHash,
bytes32[2] _dataHashes
)
external
payable
onlyJobsManager
whenSystemNotPaused
{
// Store request parameters
requests[requestCount].jobId = _jobId;
requests[requestCount].claimId = _claimId;
requests[requestCount].segmentNumber = _segmentNumber;
requests[requestCount].commitHash = keccak256(_dataHashes[0], _dataHashes[1]);
VerifyRequest(
requestCount,
_jobId,
_claimId,
_segmentNumber,
_transcodingOptions,
_dataStorageHash,
_dataHashes[0],
_dataHashes[1]
);
// Update request count
requestCount++;
}
/**
* @dev Callback function invoked by a solver to submit the result of a verification computation
* @param _requestId Request identifier
* @param _result Result of verification computation - keccak256 hash of transcoded segment data
*/
// solium-disable-next-line mixedcase
function __callback(uint256 _requestId, bytes32 _result) external onlySolver whenSystemNotPaused {
Request memory q = requests[_requestId];
// Check if transcoded data hash returned by solver matches originally submitted transcoded data hash
if (q.commitHash == _result) {
IVerifiable(controller.getContract(keccak256("JobsManager"))).receiveVerification(q.jobId, q.claimId, q.segmentNumber, true);
Callback(_requestId, q.jobId, q.claimId, q.segmentNumber, true);
} else {
IVerifiable(controller.getContract(keccak256("JobsManager"))).receiveVerification(q.jobId, q.claimId, q.segmentNumber, false);
Callback(_requestId, q.jobId, q.claimId, q.segmentNumber, false);
}
// Remove request
delete requests[_requestId];
}
/**
* @dev Return price of verification which is zero for this implementation
*/
function getPrice() public view returns (uint256) {
return 0;
}
}
|
Set registered solver address that is allowed to submit the result of transcoding verification computation via `__callback()`. Only callable by Controller owner _solver Solver address to register/ Must not be null address
|
function setSolver(address _solver) external onlyControllerOwner {
require(_solver != address(0));
solver = _solver;
SolverUpdate(_solver);
}
| 10,094,042 |
pragma solidity ^0.4.24;
/* You've seen all of this before. Here are the differences.
// A. A quarter of your clones die when you sell ideas. Market saturation, y'see?
// B. You can "become" Norsefire and take the dev fees, since he's involved in everything.
// B. 1. The Norsefire boon is a hot potato. If someone else buys it off you, you profit.
// B. 2. When Norsefire flips, we actually send him 5% of the increase. You receive 50%, the contract receives the other 45%.
// C. You get your 'free' clones for 0.00232 Ether, because throwbaaaaaack.
// D. Referral rates have been dropped to 5% instead of 20%. The referral target must have bought in.
// E. The generation rate of ideas have been halved, as a sign of my opinion of the community at large.
// F. God knows this will probably be successful in spite of myself.
*/
contract CloneFarmFarmer {
using SafeMath for uint;
/* Event */
event MarketBoost(
uint amountSent
);
event NorsefireSwitch(
address from,
address to,
uint price
);
event ClonesDeployed(
address deployer,
uint clones
);
event IdeasSold(
address seller,
uint ideas
);
event IdeasBought(
address buyer,
uint ideas
);
/* Constants */
uint256 public clones_to_create_one_idea = 2 days;
uint256 public starting_clones = 3; // Shrimp, Shrooms and Snails.
uint256 PSN = 10000;
uint256 PSNH = 5000;
address actualNorse = 0x4F4eBF556CFDc21c3424F85ff6572C77c514Fcae;
/* Variables */
uint256 public marketIdeas;
uint256 public norsefirePrice;
bool public initialized;
address public currentNorsefire;
mapping (address => uint256) public arrayOfClones;
mapping (address => uint256) public claimedIdeas;
mapping (address => uint256) public lastDeploy;
mapping (address => address) public referrals;
constructor () public {
initialized = false;
norsefirePrice = 0.1 ether;
currentNorsefire = 0x1337eaD98EaDcE2E04B1cfBf57E111479854D29A;
}
function becomeNorsefire() public payable {
require(initialized);
address oldNorseAddr = currentNorsefire;
uint oldNorsePrice = norsefirePrice;
// Did you actually send enough?
require(msg.value >= norsefirePrice);
uint excess = msg.value.sub(oldNorsePrice);
norsefirePrice = oldNorsePrice.add(oldNorsePrice.div(10));
uint diffFivePct = (norsefirePrice.sub(oldNorsePrice)).div(20);
uint flipPrize = diffFivePct.mul(10);
uint marketBoost = diffFivePct.mul(9);
address _newNorse = msg.sender;
uint _toRefund = (oldNorsePrice.add(flipPrize)).add(excess);
currentNorsefire = _newNorse;
oldNorseAddr.send(_toRefund);
actualNorse.send(diffFivePct);
boostCloneMarket(marketBoost);
emit NorsefireSwitch(oldNorseAddr, _newNorse, norsefirePrice);
}
function boostCloneMarket(uint _eth) public payable {
require(initialized);
emit MarketBoost(_eth);
}
function deployIdeas(address ref) public{
require(initialized);
address _deployer = msg.sender;
if(referrals[_deployer] == 0 && referrals[_deployer] != _deployer){
referrals[_deployer]=ref;
}
uint256 myIdeas = getMyIdeas();
uint256 newIdeas = myIdeas.div(clones_to_create_one_idea);
arrayOfClones[_deployer] = arrayOfClones[_deployer].add(newIdeas);
claimedIdeas[_deployer] = 0;
lastDeploy[_deployer] = now;
// Send referral ideas: dropped to 5% instead of 20% to reduce inflation.
if (arrayOfClones[referrals[_deployer]] > 0)
{
claimedIdeas[referrals[_deployer]] = claimedIdeas[referrals[_deployer]].add(myIdeas.div(20));
}
// Boost market to minimise idea hoarding
marketIdeas = marketIdeas.add(myIdeas.div(10));
emit ClonesDeployed(_deployer, newIdeas);
}
function sellIdeas() public {
require(initialized);
address _caller = msg.sender;
uint256 hasIdeas = getMyIdeas();
uint256 ideaValue = calculateIdeaSell(hasIdeas);
uint256 fee = devFee(ideaValue);
// Destroy a quarter the owner's clones when selling ideas thanks to market saturation.
arrayOfClones[_caller] = (arrayOfClones[msg.sender].div(4)).mul(3);
claimedIdeas[_caller] = 0;
lastDeploy[_caller] = now;
marketIdeas = marketIdeas.add(hasIdeas);
currentNorsefire.send(fee);
_caller.send(ideaValue.sub(fee));
emit IdeasSold(_caller, hasIdeas);
}
function buyIdeas() public payable{
require(initialized);
address _buyer = msg.sender;
uint _sent = msg.value;
uint256 ideasBought = calculateIdeaBuy(_sent, SafeMath.sub(address(this).balance,_sent));
ideasBought = ideasBought.sub(devFee(ideasBought));
currentNorsefire.send(devFee(_sent));
claimedIdeas[_buyer] = claimedIdeas[_buyer].add(ideasBought);
emit IdeasBought(_buyer, ideasBought);
}
function calculateTrade(uint256 rt,uint256 rs, uint256 bs) public view returns(uint256){
return SafeMath.div(SafeMath.mul(PSN,bs),SafeMath.add(PSNH,SafeMath.div(SafeMath.add(SafeMath.mul(PSN,rs),SafeMath.mul(PSNH,rt)),rt)));
}
function calculateIdeaSell(uint256 _ideas) public view returns(uint256){
return calculateTrade(_ideas,marketIdeas,address(this).balance);
}
function calculateIdeaBuy(uint256 eth,uint256 _balance) public view returns(uint256){
return calculateTrade(eth, _balance, marketIdeas);
}
function calculateIdeaBuySimple(uint256 eth) public view returns(uint256){
return calculateIdeaBuy(eth,address(this).balance);
}
function devFee(uint256 amount) public pure returns(uint256){
return amount.mul(4).div(100);
}
function releaseTheOriginal(uint256 _ideas) public payable {
require(msg.sender == currentNorsefire);
require(marketIdeas == 0);
initialized = true;
marketIdeas = _ideas;
boostCloneMarket(msg.value);
}
function hijackClones() public payable{
require(initialized);
require(msg.value==0.00232 ether); // Throwback to the OG.
address _caller = msg.sender;
currentNorsefire.send(msg.value); // The current Norsefire gets this regitration
require(arrayOfClones[_caller]==0);
lastDeploy[_caller] = now;
arrayOfClones[_caller] = starting_clones;
}
function getBalance() public view returns(uint256){
return address(this).balance;
}
function getMyClones() public view returns(uint256){
return arrayOfClones[msg.sender];
}
function getNorsefirePrice() public view returns(uint256){
return norsefirePrice;
}
function getMyIdeas() public view returns(uint256){
address _caller = msg.sender;
return claimedIdeas[_caller].add(getIdeasSinceLastDeploy(_caller));
}
function getIdeasSinceLastDeploy(address adr) public view returns(uint256){
uint256 secondsPassed=min(clones_to_create_one_idea, now.sub(lastDeploy[adr]));
return secondsPassed.mul(arrayOfClones[adr]);
}
function min(uint256 a, uint256 b) private pure returns (uint256) {
return a < b ? a : b;
}
}
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;
}
}
|
Destroy a quarter the owner&39;s clones when selling ideas thanks to market saturation.
|
function sellIdeas() public {
require(initialized);
address _caller = msg.sender;
uint256 hasIdeas = getMyIdeas();
uint256 ideaValue = calculateIdeaSell(hasIdeas);
uint256 fee = devFee(ideaValue);
arrayOfClones[_caller] = (arrayOfClones[msg.sender].div(4)).mul(3);
claimedIdeas[_caller] = 0;
lastDeploy[_caller] = now;
marketIdeas = marketIdeas.add(hasIdeas);
currentNorsefire.send(fee);
_caller.send(ideaValue.sub(fee));
emit IdeasSold(_caller, hasIdeas);
}
| 6,741,439 |
./full_match/43114/0x3428aa6424E65a174bB78EDe122f39301c626a44/sources/Divident/WAVAX.sol
|
Update reward per block Only callable by owner. _rewardPerBlock: the reward per block/ require(block.number < startBlock, "Pool has started");
|
function updateRewardPerBlock(uint256 _rewardPerBlock) external onlyOwner {
rewardPerBlock = _rewardPerBlock;
emit NewRewardPerBlock(_rewardPerBlock);
}
| 4,513,546 |
// Copyright 2019 Cartesi Pte. Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
// @title HTIF
pragma solidity ^0.7.0;
import "./MemoryInteractor.sol";
/// @title HTIF
/// @author Felipe Argento
/// @notice Host-Target-Interface (HTIF) mediates communcation with external world.
/// @dev Its active addresses are 0x40000000(tohost) and 0x40000008(from host)
/// Reference: The Core of Cartesi, v1.02 - Section 3.2 - The Board
library HTIF {
uint64 constant HTIF_TOHOST_ADDR_CONST = 0x40008000;
uint64 constant HTIF_FROMHOST_ADDR_CONST = 0x40008008;
uint64 constant HTIF_IYIELD_ADDR_CONST = 0x40008020;
// [c++] enum HTIF_devices
uint64 constant HTIF_DEVICE_HALT = 0; //< Used to halt machine
uint64 constant HTIF_DEVICE_CONSOLE = 1; //< Used for console input and output
uint64 constant HTIF_DEVICE_YIELD = 2; //< Used to yield control back to host
// [c++] enum HTIF_commands
uint64 constant HTIF_HALT_HALT = 0;
uint64 constant HTIF_CONSOLE_GETCHAR = 0;
uint64 constant HTIF_CONSOLE_PUTCHAR = 1;
uint64 constant HTIF_YIELD_PROGRESS = 0;
uint64 constant HTIF_YIELD_ROLLUP = 1;
/// @notice reads htif
/// @param mi Memory Interactor with which Step function is interacting.
/// @param addr address to read from
/// @param wordSize can be uint8, uint16, uint32 or uint64
/// @return bool if read was successfull
/// @return uint64 pval
function htifRead(
MemoryInteractor mi,
uint64 addr,
uint64 wordSize
)
public returns (bool, uint64)
{
// HTIF reads must be aligned and 8 bytes
if (wordSize != 64 || (addr & 7) != 0) {
return (false, 0);
}
if (addr == HTIF_TOHOST_ADDR_CONST) {
return (true, mi.readHtifTohost());
} else if (addr == HTIF_FROMHOST_ADDR_CONST) {
return (true, mi.readHtifFromhost());
} else {
return (false, 0);
}
}
/// @notice write htif
/// @param mi Memory Interactor with which Step function is interacting.
/// @param addr address to read from
/// @param val value to be written
/// @param wordSize can be uint8, uint16, uint32 or uint64
/// @return bool if write was successfull
function htifWrite(
MemoryInteractor mi,
uint64 addr,
uint64 val,
uint64 wordSize
)
public returns (bool)
{
// HTIF writes must be aligned and 8 bytes
if (wordSize != 64 || (addr & 7) != 0) {
return false;
}
if (addr == HTIF_TOHOST_ADDR_CONST) {
return htifWriteTohost(mi, val);
} else if (addr == HTIF_FROMHOST_ADDR_CONST) {
mi.writeHtifFromhost(val);
return true;
} else {
return false;
}
}
// Internal functions
function htifWriteFromhost(MemoryInteractor mi, uint64 val)
internal returns (bool)
{
mi.writeHtifFromhost(val);
// TO-DO: check if h is interactive? reset from host? pollConsole?
return true;
}
function htifWriteTohost(MemoryInteractor mi, uint64 tohost)
internal returns (bool)
{
uint32 device = uint32(tohost >> 56);
uint32 cmd = uint32((tohost >> 48) & 0xff);
uint64 payload = uint32((tohost & (~(uint256(1) >> 16))));
mi.writeHtifTohost(tohost);
if (device == HTIF_DEVICE_HALT) {
return htifHalt(
mi,
cmd,
payload);
} else if (device == HTIF_DEVICE_CONSOLE) {
return htifConsole(
mi,
cmd,
payload);
} else if (device == HTIF_DEVICE_YIELD) {
return htifYield(
mi,
cmd,
payload);
} else {
return true;
}
}
function htifHalt(
MemoryInteractor mi,
uint64 cmd,
uint64 payload)
internal returns (bool)
{
if (cmd == HTIF_HALT_HALT && ((payload & 1) == 1) ) {
//set iflags to halted
mi.setIflagsH(true);
}
return true;
}
function htifYield(
MemoryInteractor mi,
uint64 cmd,
uint64 payload)
internal returns (bool)
{
// If yield command is enabled, yield
if ((mi.readHtifIYield() >> cmd) & 1 == 1) {
mi.setIflagsY(true);
mi.writeHtifFromhost((HTIF_DEVICE_YIELD << 56) | cmd << 48);
}
return true;
}
function htifConsole(
MemoryInteractor mi,
uint64 cmd,
uint64 payload)
internal returns (bool)
{
if (cmd == HTIF_CONSOLE_PUTCHAR) {
htifPutchar(mi);
} else if (cmd == HTIF_CONSOLE_GETCHAR) {
htifGetchar(mi);
} else {
// Unknown HTIF console commands are silently ignored
return true;
}
}
function htifPutchar(MemoryInteractor mi) internal
returns (bool)
{
// TO-DO: what to do in the blockchain? Generate event?
mi.writeHtifFromhost((HTIF_DEVICE_CONSOLE << 56) | uint64(HTIF_CONSOLE_PUTCHAR) << 48);
return true;
}
function htifGetchar(MemoryInteractor mi) internal
returns (bool)
{
mi.writeHtifFromhost((HTIF_DEVICE_CONSOLE << 56) | uint64(HTIF_CONSOLE_GETCHAR) << 48);
return true;
}
// getters
function getHtifToHostAddr() public pure returns (uint64) {
return HTIF_TOHOST_ADDR_CONST;
}
function getHtifFromHostAddr() public pure returns (uint64) {
return HTIF_FROMHOST_ADDR_CONST;
}
function getHtifIYieldAddr() public pure returns (uint64) {
return HTIF_IYIELD_ADDR_CONST;
}
}
|
TO-DO: what to do in the blockchain? Generate event?
|
function htifPutchar(MemoryInteractor mi) internal
returns (bool)
{
mi.writeHtifFromhost((HTIF_DEVICE_CONSOLE << 56) | uint64(HTIF_CONSOLE_PUTCHAR) << 48);
return true;
}
| 12,965,902 |
/**
*Submitted for verification at Etherscan.io on 2021-06-18
*/
// File: contracts/interfaces/IMarketHandler.sol
pragma solidity 0.6.12;
/**
* @title BiFi's market handler interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IMarketHandler {
function setCircuitBreaker(bool _emergency) external returns (bool);
function setCircuitBreakWithOwner(bool _emergency) external returns (bool);
function getTokenName() external view returns (string memory);
function ownershipTransfer(address payable newOwner) external returns (bool);
function deposit(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool);
function withdraw(uint256 unifiedTokenAmount, bool allFlag) external returns (bool);
function borrow(uint256 unifiedTokenAmount, bool allFlag) external returns (bool);
function repay(uint256 unifiedTokenAmount, bool allFlag) external payable returns (bool);
function executeFlashloan(
address receiverAddress,
uint256 amount
) external returns (bool);
function depositFlashloanFee(
uint256 amount
) external returns (bool);
function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external view returns (uint256);
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) external returns (uint256, uint256, uint256);
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) external returns (uint256);
function getTokenHandlerLimit() external view returns (uint256, uint256);
function getTokenHandlerBorrowLimit() external view returns (uint256);
function getTokenHandlerMarginCallLimit() external view returns (uint256);
function setTokenHandlerBorrowLimit(uint256 borrowLimit) external returns (bool);
function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) external returns (bool);
function getTokenLiquidityAmountWithInterest(address payable userAddr) external view returns (uint256);
function getUserAmountWithInterest(address payable userAddr) external view returns (uint256, uint256);
function getUserAmount(address payable userAddr) external view returns (uint256, uint256);
function getUserMaxBorrowAmount(address payable userAddr) external view returns (uint256);
function getUserMaxWithdrawAmount(address payable userAddr) external view returns (uint256);
function getUserMaxRepayAmount(address payable userAddr) external view returns (uint256);
function checkFirstAction() external returns (bool);
function applyInterest(address payable userAddr) external returns (uint256, uint256);
function reserveDeposit(uint256 unifiedTokenAmount) external payable returns (bool);
function reserveWithdraw(uint256 unifiedTokenAmount) external returns (bool);
function withdrawFlashloanFee(uint256 unifiedTokenAmount) external returns (bool);
function getDepositTotalAmount() external view returns (uint256);
function getBorrowTotalAmount() external view returns (uint256);
function getSIRandBIR() external view returns (uint256, uint256);
function getERC20Addr() external view returns (address);
}
// File: contracts/interfaces/IMarketHandlerDataStorage.sol
pragma solidity 0.6.12;
/**
* @title BiFi's market handler data storage interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IMarketHandlerDataStorage {
function setCircuitBreaker(bool _emergency) external returns (bool);
function setNewCustomer(address payable userAddr) external returns (bool);
function getUserAccessed(address payable userAddr) external view returns (bool);
function setUserAccessed(address payable userAddr, bool _accessed) external returns (bool);
function getReservedAddr() external view returns (address payable);
function setReservedAddr(address payable reservedAddress) external returns (bool);
function getReservedAmount() external view returns (int256);
function addReservedAmount(uint256 amount) external returns (int256);
function subReservedAmount(uint256 amount) external returns (int256);
function updateSignedReservedAmount(int256 amount) external returns (int256);
function setTokenHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool);
function setCoinHandler(address _marketHandlerAddr, address _interestModelAddr) external returns (bool);
function getDepositTotalAmount() external view returns (uint256);
function addDepositTotalAmount(uint256 amount) external returns (uint256);
function subDepositTotalAmount(uint256 amount) external returns (uint256);
function getBorrowTotalAmount() external view returns (uint256);
function addBorrowTotalAmount(uint256 amount) external returns (uint256);
function subBorrowTotalAmount(uint256 amount) external returns (uint256);
function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256);
function addUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256);
function subUserIntraDepositAmount(address payable userAddr, uint256 amount) external returns (uint256);
function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256);
function addUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256);
function subUserIntraBorrowAmount(address payable userAddr, uint256 amount) external returns (uint256);
function addDepositAmount(address payable userAddr, uint256 amount) external returns (bool);
function subDepositAmount(address payable userAddr, uint256 amount) external returns (bool);
function addBorrowAmount(address payable userAddr, uint256 amount) external returns (bool);
function subBorrowAmount(address payable userAddr, uint256 amount) external returns (bool);
function getUserAmount(address payable userAddr) external view returns (uint256, uint256);
function getHandlerAmount() external view returns (uint256, uint256);
function getAmount(address payable userAddr) external view returns (uint256, uint256, uint256, uint256);
function setAmount(address payable userAddr, uint256 depositTotalAmount, uint256 borrowTotalAmount, uint256 depositAmount, uint256 borrowAmount) external returns (uint256);
function setBlocks(uint256 lastUpdatedBlock, uint256 inactiveActionDelta) external returns (bool);
function getLastUpdatedBlock() external view returns (uint256);
function setLastUpdatedBlock(uint256 _lastUpdatedBlock) external returns (bool);
function getInactiveActionDelta() external view returns (uint256);
function setInactiveActionDelta(uint256 inactiveActionDelta) external returns (bool);
function syncActionEXR() external returns (bool);
function getActionEXR() external view returns (uint256, uint256);
function setActionEXR(uint256 actionDepositExRate, uint256 actionBorrowExRate) external returns (bool);
function getGlobalDepositEXR() external view returns (uint256);
function getGlobalBorrowEXR() external view returns (uint256);
function setEXR(address payable userAddr, uint256 globalDepositEXR, uint256 globalBorrowEXR) external returns (bool);
function getUserEXR(address payable userAddr) external view returns (uint256, uint256);
function setUserEXR(address payable userAddr, uint256 depositEXR, uint256 borrowEXR) external returns (bool);
function getGlobalEXR() external view returns (uint256, uint256);
function getMarketHandlerAddr() external view returns (address);
function setMarketHandlerAddr(address marketHandlerAddr) external returns (bool);
function getInterestModelAddr() external view returns (address);
function setInterestModelAddr(address interestModelAddr) external returns (bool);
function getMinimumInterestRate() external view returns (uint256);
function setMinimumInterestRate(uint256 _minimumInterestRate) external returns (bool);
function getLiquiditySensitivity() external view returns (uint256);
function setLiquiditySensitivity(uint256 _liquiditySensitivity) external returns (bool);
function getLimit() external view returns (uint256, uint256);
function getBorrowLimit() external view returns (uint256);
function setBorrowLimit(uint256 _borrowLimit) external returns (bool);
function getMarginCallLimit() external view returns (uint256);
function setMarginCallLimit(uint256 _marginCallLimit) external returns (bool);
function getLimitOfAction() external view returns (uint256);
function setLimitOfAction(uint256 limitOfAction) external returns (bool);
function getLiquidityLimit() external view returns (uint256);
function setLiquidityLimit(uint256 liquidityLimit) external returns (bool);
}
// File: contracts/interfaces/IMarketManager.sol
pragma solidity 0.6.12;
/**
* @title BiFi's market manager interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IMarketManager {
function setBreakerTable(address _target, bool _status) external returns (bool);
function getCircuitBreaker() external view returns (bool);
function setCircuitBreaker(bool _emergency) external returns (bool);
function getTokenHandlerInfo(uint256 handlerID) external view returns (bool, address, string memory);
function handlerRegister(uint256 handlerID, address tokenHandlerAddr, uint256 flashFeeRate) external returns (bool);
function applyInterestHandlers(address payable userAddr, uint256 callerID, bool allFlag) external returns (uint256, uint256, uint256, uint256, uint256, uint256);
function getTokenHandlerPrice(uint256 handlerID) external view returns (uint256);
function getTokenHandlerBorrowLimit(uint256 handlerID) external view returns (uint256);
function getTokenHandlerSupport(uint256 handlerID) external view returns (bool);
function getTokenHandlersLength() external view returns (uint256);
function setTokenHandlersLength(uint256 _tokenHandlerLength) external returns (bool);
function getTokenHandlerID(uint256 index) external view returns (uint256);
function getTokenHandlerMarginCallLimit(uint256 handlerID) external view returns (uint256);
function getUserIntraHandlerAssetWithInterest(address payable userAddr, uint256 handlerID) external view returns (uint256, uint256);
function getUserTotalIntraCreditAsset(address payable userAddr) external view returns (uint256, uint256);
function getUserLimitIntraAsset(address payable userAddr) external view returns (uint256, uint256);
function getUserCollateralizableAmount(address payable userAddr, uint256 handlerID) external view returns (uint256);
function getUserExtraLiquidityAmount(address payable userAddr, uint256 handlerID) external view returns (uint256);
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 liquidateHandlerID, uint256 rewardHandlerID) external returns (uint256, uint256, uint256);
function getMaxLiquidationReward(address payable delinquentBorrower, uint256 liquidateHandlerID, uint256 liquidateAmount, uint256 rewardHandlerID, uint256 rewardRatio) external view returns (uint256);
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 rewardAmount, address payable liquidator, uint256 handlerID) external returns (uint256);
function setLiquidationManager(address liquidationManagerAddr) external returns (bool);
function rewardClaimAll(address payable userAddr) external returns (uint256);
function updateRewardParams(address payable userAddr) external returns (bool);
function interestUpdateReward() external returns (bool);
function getGlobalRewardInfo() external view returns (uint256, uint256, uint256);
function setOracleProxy(address oracleProxyAddr) external returns (bool);
function rewardUpdateOfInAction(address payable userAddr, uint256 callerID) external returns (bool);
function ownerRewardTransfer(uint256 _amount) external returns (bool);
function getFeeTotal(uint256 handlerID) external returns (uint256);
function getFeeFromArguments(uint256 handlerID, uint256 amount, uint256 bifiAmount) external returns (uint256);
}
// File: contracts/interfaces/IInterestModel.sol
pragma solidity 0.6.12;
/**
* @title BiFi's interest model interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IInterestModel {
function getInterestAmount(address handlerDataStorageAddr, address payable userAddr, bool isView) external view returns (bool, uint256, uint256, bool, uint256, uint256);
function viewInterestAmount(address handlerDataStorageAddr, address payable userAddr) external view returns (bool, uint256, uint256, bool, uint256, uint256);
function getSIRandBIR(uint256 depositTotalAmount, uint256 borrowTotalAmount) external view returns (uint256, uint256);
}
// File: contracts/interfaces/IMarketSIHandlerDataStorage.sol
pragma solidity 0.6.12;
/**
* @title BiFi's market si handler data storage interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IMarketSIHandlerDataStorage {
function setCircuitBreaker(bool _emergency) external returns (bool);
function updateRewardPerBlockStorage(uint256 _rewardPerBlock) external returns (bool);
function getRewardInfo(address userAddr) external view returns (uint256, uint256, uint256, uint256, uint256, uint256);
function getMarketRewardInfo() external view returns (uint256, uint256, uint256);
function setMarketRewardInfo(uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardPerBlock) external returns (bool);
function getUserRewardInfo(address userAddr) external view returns (uint256, uint256, uint256);
function setUserRewardInfo(address userAddr, uint256 _rewardLane, uint256 _rewardLaneUpdateAt, uint256 _rewardAmount) external returns (bool);
function getBetaRate() external view returns (uint256);
function setBetaRate(uint256 _betaRate) external returns (bool);
}
// File: contracts/interfaces/IProxy.sol
pragma solidity 0.6.12;
/**
* @title BiFi's proxy interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IProxy {
function handlerProxy(bytes memory data) external returns (bool, bytes memory);
function handlerViewProxy(bytes memory data) external view returns (bool, bytes memory);
function siProxy(bytes memory data) external returns (bool, bytes memory);
function siViewProxy(bytes memory data) external view returns (bool, bytes memory);
}
// File: contracts/interfaces/IServiceIncentive.sol
pragma solidity 0.6.12;
/**
* @title BiFi's si interface
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
interface IServiceIncentive {
function setCircuitBreakWithOwner(bool emergency) external returns (bool);
function setCircuitBreaker(bool emergency) external returns (bool);
function updateRewardPerBlockLogic(uint256 _rewardPerBlock) external returns (bool);
function updateRewardLane(address payable userAddr) external returns (bool);
function getBetaRateBaseTotalAmount() external view returns (uint256);
function getBetaRateBaseUserAmount(address payable userAddr) external view returns (uint256);
function getMarketRewardInfo() external view returns (uint256, uint256, uint256);
function getUserRewardInfo(address payable userAddr) external view returns (uint256, uint256, uint256);
function claimRewardAmountUser(address payable userAddr) external returns (uint256);
}
// File: contracts/interfaces/IFlashloanReceiver.sol
pragma solidity 0.6.12;
interface IFlashloanReceiver {
function executeOperation(
address reserve,
uint256 amount,
uint256 fee,
bytes calldata params
) external returns (bool);
}
// File: contracts/Errors.sol
pragma solidity 0.6.12;
contract Modifier {
string internal constant ONLY_OWNER = "O";
string internal constant ONLY_MANAGER = "M";
string internal constant CIRCUIT_BREAKER = "emergency";
}
contract ManagerModifier is Modifier {
string internal constant ONLY_HANDLER = "H";
string internal constant ONLY_LIQUIDATION_MANAGER = "LM";
string internal constant ONLY_BREAKER = "B";
}
contract HandlerDataStorageModifier is Modifier {
string internal constant ONLY_BIFI_CONTRACT = "BF";
}
contract SIDataStorageModifier is Modifier {
string internal constant ONLY_SI_HANDLER = "SI";
}
contract HandlerErrors is Modifier {
string internal constant USE_VAULE = "use value";
string internal constant USE_ARG = "use arg";
string internal constant EXCEED_LIMIT = "exceed limit";
string internal constant NO_LIQUIDATION = "no liquidation";
string internal constant NO_LIQUIDATION_REWARD = "no enough reward";
string internal constant NO_EFFECTIVE_BALANCE = "not enough balance";
string internal constant TRANSFER = "err transfer";
}
contract SIErrors is Modifier { }
contract InterestErrors is Modifier { }
contract LiquidationManagerErrors is Modifier {
string internal constant NO_DELINQUENT = "not delinquent";
}
contract ManagerErrors is ManagerModifier {
string internal constant REWARD_TRANSFER = "RT";
string internal constant UNSUPPORTED_TOKEN = "UT";
}
contract OracleProxyErrors is Modifier {
string internal constant ZERO_PRICE = "price zero";
}
contract RequestProxyErrors is Modifier { }
contract ManagerDataStorageErrors is ManagerModifier {
string internal constant NULL_ADDRESS = "err addr null";
}
// File: contracts/context/BlockContext.sol
pragma solidity 0.6.12;
/**
* @title BiFi's BlockContext contract
* @notice BiFi getter Contract for Block Context Information
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
contract BlockContext {
function _blockContext() internal view returns(uint256 context) {
// block number chain
// context = block.number;
// block timestamp chain
context = block.timestamp;
}
}
// File: contracts/marketHandler/CoinHandler.sol
// SPDX-License-Identifier: BSD-3-Clause
pragma solidity 0.6.12;
/**
* @title BiFi's CoinHandler logic contract for native conis
* @author BiFi(seinmyung25, Miller-kk, tlatkdgus1, dongchangYoo)
*/
contract CoinHandler is IMarketHandler, HandlerErrors, BlockContext {
event MarketIn(address userAddr);
event Deposit(address depositor, uint256 depositAmount, uint256 handlerID);
event Withdraw(address redeemer, uint256 redeemAmount, uint256 handlerID);
event Borrow(address borrower, uint256 borrowAmount, uint256 handlerID);
event Repay(address repayer, uint256 repayAmount, uint256 handlerID);
event ReserveDeposit(uint256 reserveDepositAmount, uint256 handlerID);
event ReserveWithdraw(uint256 reserveWithdrawAmount, uint256 handlerID);
event FlashloanFeeWithdraw(uint256 flashloanFeeWithdrawAmount, uint256 handlerID);
event OwnershipTransferred(address owner, address newOwner);
event CircuitBreaked(bool breaked, uint256 blockNumber, uint256 handlerID);
address payable owner;
uint256 handlerID;
string tokenName = "ether";
uint256 constant unifiedPoint = 10 ** 18;
IMarketManager marketManager;
IInterestModel interestModelInstance;
IMarketHandlerDataStorage handlerDataStorage;
IMarketSIHandlerDataStorage SIHandlerDataStorage;
struct ProxyInfo {
bool result;
bytes returnData;
bytes data;
bytes proxyData;
}
modifier onlyMarketManager {
address msgSender = msg.sender;
require((msgSender == address(marketManager)) || (msgSender == owner), ONLY_MANAGER);
_;
}
modifier onlyOwner {
require(msg.sender == address(owner), ONLY_OWNER);
_;
}
/**
* @dev Set circuitBreak to freeze all of handlers by owner
* @param _emergency Boolean state of the circuit break.
* @return true (TODO: validate results)
*/
function setCircuitBreakWithOwner(bool _emergency) onlyOwner external override returns (bool)
{
handlerDataStorage.setCircuitBreaker(_emergency);
emit CircuitBreaked(_emergency, block.number, handlerID);
return true;
}
/**
* @dev Set circuitBreak which freeze all of handlers by marketManager
* @param _emergency Boolean state of the circuit break.
* @return true (TODO: validate results)
*/
function setCircuitBreaker(bool _emergency) onlyMarketManager external override returns (bool)
{
handlerDataStorage.setCircuitBreaker(_emergency);
emit CircuitBreaked(_emergency, block.number, handlerID);
return true;
}
/**
* @dev Get the token name (unused in CoinHandler)
* @return The token name
*/
function getTokenName() external view override returns (string memory)
{
return tokenName;
}
/**
* @dev Change the owner of the handler
* @param newOwner the address of the owner to be replaced
* @return true (TODO: validate results)
*/
function ownershipTransfer(address payable newOwner) onlyOwner external override returns (bool)
{
owner = newOwner;
emit OwnershipTransferred(owner, newOwner);
return true;
}
/**
* @dev Deposit assets to the reserve of the handler.
* @param unifiedTokenAmount The amount of token to deposit
* @return true (TODO: validate results)
*/
function reserveDeposit(uint256 unifiedTokenAmount) external payable override returns (bool)
{
require(unifiedTokenAmount == 0, USE_VAULE);
unifiedTokenAmount = msg.value;
handlerDataStorage.addReservedAmount(unifiedTokenAmount);
handlerDataStorage.addDepositTotalAmount(unifiedTokenAmount);
emit ReserveDeposit(unifiedTokenAmount, handlerID);
return true;
}
/**
* @dev Withdraw assets from the reserve of the handler.
* @param unifiedTokenAmount The amount of token to withdraw
* @return true (TODO: validate results)
*/
function reserveWithdraw(uint256 unifiedTokenAmount) onlyOwner external override returns (bool)
{
address payable reserveAddr = handlerDataStorage.getReservedAddr();
handlerDataStorage.subReservedAmount(unifiedTokenAmount);
handlerDataStorage.subDepositTotalAmount(unifiedTokenAmount);
_transfer(reserveAddr, unifiedTokenAmount);
emit ReserveWithdraw(unifiedTokenAmount, handlerID);
return true;
}
function withdrawFlashloanFee(uint256 unifiedTokenAmount) onlyMarketManager external override returns (bool) {
address payable reserveAddr = handlerDataStorage.getReservedAddr();
handlerDataStorage.subReservedAmount(unifiedTokenAmount);
handlerDataStorage.subDepositTotalAmount(unifiedTokenAmount);
_transfer(reserveAddr, unifiedTokenAmount);
emit FlashloanFeeWithdraw(unifiedTokenAmount, handlerID);
return true;
}
/**
* @dev Deposit action
* @param unifiedTokenAmount The deposit amount (must be zero, msg.value is used)
* @param flag Flag for the full calcuation mode
* @return true (TODO: validate results)
*/
function deposit(uint256 unifiedTokenAmount, bool flag) external payable override returns (bool)
{
require(unifiedTokenAmount == 0, USE_VAULE);
unifiedTokenAmount = msg.value;
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
if(flag) {
// flag is true, update interest, reward all handlers
marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
} else {
marketManager.rewardUpdateOfInAction(userAddr, _handlerID);
_applyInterest(userAddr);
}
handlerDataStorage.addDepositAmount(userAddr, unifiedTokenAmount);
emit Deposit(userAddr, unifiedTokenAmount, _handlerID);
return true;
}
/**
* @dev Withdraw action
* @param unifiedTokenAmount The withdraw amount
* @param flag Flag for the full calcuation mode
* @return true (TODO: validate results)
*/
function withdraw(uint256 unifiedTokenAmount, bool flag) external override returns (bool)
{
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
uint256 userLiquidityAmount;
uint256 userCollateralizableAmount;
uint256 price;
(userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
uint256 adjustedAmount = _getUserActionMaxWithdrawAmount(userAddr, unifiedTokenAmount, userCollateralizableAmount);
require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT);
handlerDataStorage.subDepositAmount(userAddr, adjustedAmount);
_transfer(userAddr, adjustedAmount);
emit Withdraw(userAddr, adjustedAmount, _handlerID);
return true;
}
/**
* @dev Borrow action
* @param unifiedTokenAmount The borrow amount
* @param flag Flag for the full calcuation mode
* @return true (TODO: validate results)
*/
function borrow(uint256 unifiedTokenAmount, bool flag) external override returns (bool)
{
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
uint256 userLiquidityAmount;
uint256 userCollateralizableAmount;
uint256 price;
(userLiquidityAmount, userCollateralizableAmount, , , , price) = marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
uint256 adjustedAmount = _getUserActionMaxBorrowAmount(unifiedTokenAmount, userLiquidityAmount);
require(unifiedMul(adjustedAmount, price) <= handlerDataStorage.getLimitOfAction(), EXCEED_LIMIT);
handlerDataStorage.addBorrowAmount(userAddr, adjustedAmount);
_transfer(userAddr, adjustedAmount);
emit Borrow(userAddr, adjustedAmount, _handlerID);
return true;
}
/**
* @dev Repay action
* @param unifiedTokenAmount The repay amount (must be zero, msg.value is used)
* @param flag Flag for the full calcuation mode
* @return true (TODO: validate results)
*/
function repay(uint256 unifiedTokenAmount, bool flag) external payable override returns (bool)
{
require(unifiedTokenAmount == 0, USE_VAULE);
unifiedTokenAmount = msg.value;
address payable userAddr = msg.sender;
uint256 _handlerID = handlerID;
if(flag) {
// flag is true, update interest, reward all handlers
marketManager.applyInterestHandlers(userAddr, _handlerID, flag);
} else {
marketManager.rewardUpdateOfInAction(userAddr, _handlerID);
_applyInterest(userAddr);
}
uint256 overRepayAmount;
uint256 userBorrowAmount = handlerDataStorage.getUserIntraBorrowAmount(userAddr);
if (userBorrowAmount < unifiedTokenAmount)
{
overRepayAmount = sub(unifiedTokenAmount, userBorrowAmount);
unifiedTokenAmount = userBorrowAmount;
}
handlerDataStorage.subBorrowAmount(userAddr, unifiedTokenAmount);
if (overRepayAmount > 0)
{
_transfer(userAddr, overRepayAmount);
}
emit Repay(userAddr, unifiedTokenAmount, _handlerID);
return true;
}
function executeFlashloan(
address receiverAddress,
uint256 amount
) external onlyMarketManager override returns (bool) {
_transfer(payable(receiverAddress), amount);
return true;
}
function depositFlashloanFee(
uint256 amount
) external onlyMarketManager override returns (bool) {
handlerDataStorage.addReservedAmount(amount);
handlerDataStorage.addDepositTotalAmount(amount);
emit ReserveDeposit(amount, handlerID);
return true;
}
/**
* @dev liquidate delinquentBorrower's partial(or can total) asset
* @param delinquentBorrower The user addresss of liquidation target
* @param liquidateAmount The amount of liquidator request
* @param liquidator The address of a user executing liquidate
* @param rewardHandlerID The handler id of delinquentBorrower's collateral for receive
* @return (liquidateAmount, delinquentDepositAsset, delinquentBorrowAsset), result of liquidate
*/
function partialLiquidationUser(address payable delinquentBorrower, uint256 liquidateAmount, address payable liquidator, uint256 rewardHandlerID) onlyMarketManager external override returns (uint256, uint256, uint256)
{
uint256 tmp;
uint256 delinquentMarginCallDeposit;
uint256 delinquentDepositAsset;
uint256 delinquentBorrowAsset;
uint256 liquidatorLiquidityAmount;
/* apply interest for sync "latest" asset for delinquentBorrower and liquidator */
(, , delinquentMarginCallDeposit, delinquentDepositAsset, delinquentBorrowAsset, ) = marketManager.applyInterestHandlers(delinquentBorrower, handlerID, false);
(, liquidatorLiquidityAmount, , , , ) = marketManager.applyInterestHandlers(liquidator, handlerID, false);
/* check delinquentBorrower liquidatable */
require(delinquentMarginCallDeposit <= delinquentBorrowAsset, NO_LIQUIDATION);
/* The maximum allowed amount for liquidateAmount */
tmp = handlerDataStorage.getUserIntraDepositAmount(liquidator);
if (tmp <= liquidateAmount)
{
liquidateAmount = tmp;
}
tmp = handlerDataStorage.getUserIntraBorrowAmount(delinquentBorrower);
if (tmp <= liquidateAmount)
{
liquidateAmount = tmp;
}
/* get maximum "receive handler" amount by liquidate amount */
liquidateAmount = marketManager.getMaxLiquidationReward(delinquentBorrower, handlerID, liquidateAmount, rewardHandlerID, unifiedDiv(delinquentBorrowAsset, delinquentDepositAsset));
/* check liquidator has enough amount for liquidation */
require(liquidatorLiquidityAmount > liquidateAmount, NO_EFFECTIVE_BALANCE);
/* update storage for liquidate*/
handlerDataStorage.subDepositAmount(liquidator, liquidateAmount);
handlerDataStorage.subBorrowAmount(delinquentBorrower, liquidateAmount);
return (liquidateAmount, delinquentDepositAsset, delinquentBorrowAsset);
}
/**
* @dev liquidator receive delinquentBorrower's collateral after liquidate delinquentBorrower's asset
* @param delinquentBorrower The user addresss of liquidation target
* @param liquidationAmountWithReward The amount of liquidator receiving delinquentBorrower's collateral
* @param liquidator The address of a user executing liquidate
* @return The amount of token transfered(in storage)
*/
function partialLiquidationUserReward(address payable delinquentBorrower, uint256 liquidationAmountWithReward, address payable liquidator) onlyMarketManager external override returns (uint256)
{
marketManager.rewardUpdateOfInAction(delinquentBorrower, handlerID);
_applyInterest(delinquentBorrower);
/* check delinquentBorrower's collateral enough */
uint256 collateralAmount = handlerDataStorage.getUserIntraDepositAmount(delinquentBorrower);
require(collateralAmount >= liquidationAmountWithReward, NO_LIQUIDATION_REWARD);
/* collateral transfer */
handlerDataStorage.subDepositAmount(delinquentBorrower, liquidationAmountWithReward);
_transfer(liquidator, liquidationAmountWithReward);
return liquidationAmountWithReward;
}
/**
* @dev Get borrowLimit and marginCallLimit
* @return borrowLimit and marginCallLimit
*/
function getTokenHandlerLimit() external view override returns (uint256, uint256)
{
return handlerDataStorage.getLimit();
}
/**
* @dev Set the borrow limit of the handler
* @param borrowLimit The borrow limit
* @return true (TODO: validate results)
*/
function setTokenHandlerBorrowLimit(uint256 borrowLimit) onlyOwner external override returns (bool)
{
handlerDataStorage.setBorrowLimit(borrowLimit);
return true;
}
/**
* @dev Set the liquidation limit of the handler
* @param marginCallLimit The liquidation limit
* @return true (TODO: validate results)
*/
function setTokenHandlerMarginCallLimit(uint256 marginCallLimit) onlyOwner external override returns (bool)
{
handlerDataStorage.setMarginCallLimit(marginCallLimit);
return true;
}
/**
* @dev Get the liquidation limit of handler
* @return The liquidation limit
*/
function getTokenHandlerMarginCallLimit() external view override returns (uint256)
{
return handlerDataStorage.getMarginCallLimit();
}
/**
* @dev Get the borrow limit of the handler
* @return The borrow limit
*/
function getTokenHandlerBorrowLimit() external view override returns (uint256)
{
return handlerDataStorage.getBorrowLimit();
}
/**
* @dev Get the maximum allowed amount for borrow for a user (external, view)
* @param userAddr The user address
* @return The maximum allowed amount for borrow
*/
function getUserMaxBorrowAmount(address payable userAddr) external view override returns (uint256)
{
return _getUserMaxBorrowAmount(userAddr);
}
/**
* @dev Get (total deposit - total borrow) of the handler including interest
* @param userAddr The user address(for wrapping function, unused)
* @return (total deposit - total borrow) of the handler including interest
*/
function getTokenLiquidityAmountWithInterest(address payable userAddr) external view override returns (uint256)
{
return _getTokenLiquidityAmountWithInterest(userAddr);
}
/**
* @dev Get the maximum allowed amount for borrow for a user (interal)
* @param userAddr The user address
* @return The maximum allowed amount for borrow
*/
function _getUserMaxBorrowAmount(address payable userAddr) internal view returns (uint256)
{
/* Prevent Action: over "Token Liquidity" amount*/
uint256 handlerLiquidityAmount = _getTokenLiquidityLimitAmountWithInterest(userAddr);
/* Prevent Action: over "CREDIT" amount */
uint256 userLiquidityAmount = marketManager.getUserExtraLiquidityAmount(userAddr, handlerID);
uint256 minAmount = userLiquidityAmount;
if (handlerLiquidityAmount < minAmount)
{
minAmount = handlerLiquidityAmount;
}
return minAmount;
}
/**
* @dev Get the maximum allowed amount for borrow by user liqudity amount and handler total balance.
* @param requestedAmount The reqeusted amount for borrow
* @param userLiquidityAmount The maximum borrow amount by unused collateral.
* @return The maximum allowed amount for borrow
*/
function _getUserActionMaxBorrowAmount(uint256 requestedAmount, uint256 userLiquidityAmount) internal view returns (uint256)
{
/* Prevent Action: over "Token Liquidity" amount*/
uint256 handlerLiquidityAmount = _getTokenLiquidityLimitAmount();
/* select minimum of handlerLiqudity and user liquidity */
uint256 minAmount = requestedAmount;
if (minAmount > handlerLiquidityAmount)
{
minAmount = handlerLiquidityAmount;
}
if (minAmount > userLiquidityAmount)
{
minAmount = userLiquidityAmount;
}
return minAmount;
}
/**
* @dev Get the maximum allowd amount for withdraw for a user
* @param userAddr The user address
* @return The maximum allowed amount for withdraw
*/
function getUserMaxWithdrawAmount(address payable userAddr) external view override returns (uint256)
{
return _getUserMaxWithdrawAmount(userAddr);
}
/**
* @dev Get SIR and BIR
* @return SIR and BIR (tuple)
*/
function getSIRandBIR() external view override returns (uint256, uint256)
{
uint256 totalDepositAmount = handlerDataStorage.getDepositTotalAmount();
uint256 totalBorrowAmount = handlerDataStorage.getBorrowTotalAmount();
return interestModelInstance.getSIRandBIR(totalDepositAmount, totalBorrowAmount);
}
/**
* @dev Get the maximum allowd amount for withdraw for a user
* @param userAddr The user address
* @return The maximum allowed amount for withdraw
*/
function _getUserMaxWithdrawAmount(address payable userAddr) internal view returns (uint256)
{
uint256 depositAmountWithInterest;
uint256 borrowAmountWithInterest;
(depositAmountWithInterest, borrowAmountWithInterest) = _getUserAmountWithInterest(userAddr);
uint256 handlerLiquidityAmount = _getTokenLiquidityAmountWithInterest(userAddr);
uint256 userLiquidityAmount = marketManager.getUserCollateralizableAmount(userAddr, handlerID);
/* Prevent Action: over "DEPOSIT" amount */
uint256 minAmount = depositAmountWithInterest;
/* Prevent Action: over "CREDIT" amount */
if (minAmount > userLiquidityAmount)
{
minAmount = userLiquidityAmount;
}
if (minAmount > handlerLiquidityAmount)
{
minAmount = handlerLiquidityAmount;
}
return minAmount;
}
/**
* @dev Get the maximum allowd amount for withdraw for a user
* @param userAddr The user address
* @param requestedAmount The reqested amount of token to withdraw
* @param collateralableAmount The amount of unused collateral.
* @return The maximum allowd amount for withdraw
*/
function _getUserActionMaxWithdrawAmount(address payable userAddr, uint256 requestedAmount, uint256 collateralableAmount) internal view returns (uint256)
{
uint256 depositAmount = handlerDataStorage.getUserIntraDepositAmount(userAddr);
uint256 handlerLiquidityAmount = _getTokenLiquidityAmount();
/* the minimum of request, deposit, collateral and collateralable*/
uint256 minAmount = depositAmount;
if (minAmount > requestedAmount)
{
minAmount = requestedAmount;
}
if (minAmount > collateralableAmount)
{
minAmount = collateralableAmount;
}
if (minAmount > handlerLiquidityAmount)
{
minAmount = handlerLiquidityAmount;
}
return minAmount;
}
/**
* @dev Get the maximum amount for repay
* @param userAddr The user address
* @return The maximum amount for repay
*/
function getUserMaxRepayAmount(address payable userAddr) external view override returns (uint256)
{
uint256 depositAmountWithInterest;
uint256 borrowAmountWithInterest;
(depositAmountWithInterest, borrowAmountWithInterest) = _getUserAmountWithInterest(userAddr);
return borrowAmountWithInterest;
}
/**
* @dev Update (apply) interest entry point (external)
* @param userAddr The user address
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function applyInterest(address payable userAddr) external override returns (uint256, uint256)
{
return _applyInterest(userAddr);
}
/**
* @dev Update (apply) interest entry point (internal)
* @param userAddr The user address
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function _applyInterest(address payable userAddr) internal returns (uint256, uint256)
{
_checkNewCustomer(userAddr);
_checkFirstAction();
return _updateInterestAmount(userAddr);
}
/**
* @dev Check whether a given userAddr is a new user or not
* @param userAddr The user address
* @return true if the user is a new user; false otherwise.
*/
function _checkNewCustomer(address payable userAddr) internal returns (bool)
{
IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage;
if (_handlerDataStorage.getUserAccessed(userAddr))
{
return false;
}
/* hotfix */
_handlerDataStorage.setUserAccessed(userAddr, true);
(uint256 gDEXR, uint256 gBEXR) = _handlerDataStorage.getGlobalEXR();
_handlerDataStorage.setUserEXR(userAddr, gDEXR, gBEXR);
return true;
}
/**
* @dev Get the address of the token that the handler is dealing with
* (CoinHandler don't deal with tokens in coin handlers)
* @return The address of the token
*/
function getERC20Addr() external override view returns (address)
{
return address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
}
/**
* @dev Get the amount of deposit and borrow of the user
* @param userAddr The user address
* @return (depositAmount, borrowAmount)
*/
function getUserAmount(address payable userAddr) external view override returns (uint256, uint256)
{
uint256 depositAmount = handlerDataStorage.getUserIntraDepositAmount(userAddr);
uint256 borrowAmount = handlerDataStorage.getUserIntraBorrowAmount(userAddr);
return (depositAmount, borrowAmount);
}
/**
* @dev Get the amount of user deposit
* @param userAddr The user address
* @return the amount of user deposit
*/
function getUserIntraDepositAmount(address payable userAddr) external view returns (uint256)
{
return handlerDataStorage.getUserIntraDepositAmount(userAddr);
}
/**
* @dev Get the amount of user borrow
* @param userAddr The user address
* @return the amount of user borrow
*/
function getUserIntraBorrowAmount(address payable userAddr) external view returns (uint256)
{
return handlerDataStorage.getUserIntraBorrowAmount(userAddr);
}
/**
* @dev Get the amount of the total deposit of the handler
* @return the amount of the total deposit of the handler
*/
function getDepositTotalAmount() external view override returns (uint256)
{
return handlerDataStorage.getDepositTotalAmount();
}
/**
* @dev Get the amount of total borrow of the handler
* @return the amount of total borrow of the handler
*/
function getBorrowTotalAmount() external view override returns (uint256)
{
return handlerDataStorage.getBorrowTotalAmount();
}
/**
* @dev Get the amount of deposit and borrow of user including interest
* @param userAddr The user address
* @return (userDepositAmount, userBorrowAmount)
*/
function getUserAmountWithInterest(address payable userAddr) external view override returns (uint256, uint256)
{
return _getUserAmountWithInterest(userAddr);
}
/**
* @dev Get the address of owner
* @return the address of owner
*/
function getOwner() public view returns (address)
{
return owner;
}
/**
* @dev Internal function to transfer asset to the user
* @param userAddr The user address
* @param unifiedTokenAmount The amount of coin to send
* @return true (TODO: validate results)
*/
function _transfer(address payable userAddr, uint256 unifiedTokenAmount) internal returns (bool)
{
userAddr.transfer(unifiedTokenAmount);
return true;
}
/**
* @dev Get (total deposit - total borrow) of the handler
* @return (total deposit - total borrow) of the handler
*/
function _getTokenLiquidityAmount() internal view returns (uint256)
{
IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage;
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
(depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount();
if (depositTotalAmount == 0)
{
return 0;
}
if (depositTotalAmount < borrowTotalAmount)
{
return 0;
}
return sub(depositTotalAmount, borrowTotalAmount);
}
/**
* @dev Get (total deposit * liquidity limit - total borrow) of the handler
* @return (total deposit * liquidity limit - total borrow) of the handler
*/
function _getTokenLiquidityLimitAmount() internal view returns (uint256)
{
IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage;
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
(depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount();
if (depositTotalAmount == 0)
{
return 0;
}
uint256 liquidityDeposit = unifiedMul(depositTotalAmount, _handlerDataStorage.getLiquidityLimit());
if (liquidityDeposit < borrowTotalAmount)
{
return 0;
}
return sub(liquidityDeposit, borrowTotalAmount);
}
/**
* @dev Get (total deposit - total borrow) of the handler including interest
* @param userAddr The user address(for wrapping function, unused)
* @return (total deposit - total borrow) of the handler including interest
*/
function _getTokenLiquidityAmountWithInterest(address payable userAddr) internal view returns (uint256)
{
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
(depositTotalAmount, borrowTotalAmount) = _getTotalAmountWithInterest(userAddr);
if (depositTotalAmount == 0)
{
return 0;
}
if (depositTotalAmount < borrowTotalAmount)
{
return 0;
}
return sub(depositTotalAmount, borrowTotalAmount);
}
/**
* @dev Get (total deposit * liquidity limit - total borrow) of the handler including interest
* @param userAddr The user address(for wrapping function, unused)
* @return (total deposit * liquidity limit - total borrow) of the handler including interest
*/
function _getTokenLiquidityLimitAmountWithInterest(address payable userAddr) internal view returns (uint256)
{
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
(depositTotalAmount, borrowTotalAmount) = _getTotalAmountWithInterest(userAddr);
if (depositTotalAmount == 0)
{
return 0;
}
uint256 liquidityDeposit = unifiedMul(depositTotalAmount, handlerDataStorage.getLiquidityLimit());
if (liquidityDeposit < borrowTotalAmount)
{
return 0;
}
return sub(liquidityDeposit, borrowTotalAmount);
}
/**
* @dev Check first action of user in the This Block (external)
* @return true for first action
*/
function checkFirstAction() onlyMarketManager external override returns (bool)
{
return _checkFirstAction();
}
/**
* @dev Convert amount of handler's unified decimals to amount of token's underlying decimals
* @param unifiedTokenAmount The amount of unified decimals
* @return (underlyingTokenAmount)
*/
function convertUnifiedToUnderlying(uint256 unifiedTokenAmount) external override view returns (uint256) {
return unifiedTokenAmount;
}
/**
* @dev Check first action of user in the This Block (internal)
* @return true for first action
*/
function _checkFirstAction() internal returns (bool)
{
IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage;
uint256 lastUpdatedBlock = _handlerDataStorage.getLastUpdatedBlock();
uint256 currentBlockNumber = _blockContext();
uint256 blockDelta = sub(currentBlockNumber, lastUpdatedBlock);
if (blockDelta > 0)
{
// first action in this block
_handlerDataStorage.setBlocks(currentBlockNumber, blockDelta);
_handlerDataStorage.syncActionEXR();
return true;
}
return false;
}
/**
* @dev calculate (apply) interest (internal) and call storage update function
* @param userAddr The user address
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function _updateInterestAmount(address payable userAddr) internal returns (uint256, uint256)
{
bool depositNegativeFlag;
uint256 deltaDepositAmount;
uint256 globalDepositEXR;
bool borrowNegativeFlag;
uint256 deltaBorrowAmount;
uint256 globalBorrowEXR;
/* calculate interest amount and params by call Interest Model */
(depositNegativeFlag, deltaDepositAmount, globalDepositEXR, borrowNegativeFlag, deltaBorrowAmount, globalBorrowEXR) = interestModelInstance.getInterestAmount(address(handlerDataStorage), userAddr, false);
/* update new global EXR to user EXR*/
handlerDataStorage.setEXR(userAddr, globalDepositEXR, globalBorrowEXR);
/* call storage update function for update "latest" interest information */
return _setAmountReflectInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount);
}
/**
* @dev Apply the user's interest
* @param userAddr The user address
* @param depositNegativeFlag the sign of deltaDepositAmount (true for negative)
* @param deltaDepositAmount The delta amount of deposit
* @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative)
* @param deltaBorrowAmount The delta amount of borrow
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function _setAmountReflectInterest(address payable userAddr, bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal returns (uint256, uint256)
{
uint256 depositTotalAmount;
uint256 userDepositAmount;
uint256 borrowTotalAmount;
uint256 userBorrowAmount;
/* call _getAmountWithInterest for adding user storage amount and interest delta amount (deposit and borrow)*/
(depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _getAmountWithInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount);
/* update user amount in storage*/
handlerDataStorage.setAmount(userAddr, depositTotalAmount, borrowTotalAmount, userDepositAmount, userBorrowAmount);
/* update "spread between deposits and borrows" */
_updateReservedAmount(depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount);
return (userDepositAmount, userBorrowAmount);
}
/**
* @dev Get the "latest" user amount of deposit and borrow including interest (internal, view)
* @param userAddr The user address
* @return "latest" (userDepositAmount, userBorrowAmount)
*/
function _getUserAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256)
{
uint256 depositTotalAmount;
uint256 userDepositAmount;
uint256 borrowTotalAmount;
uint256 userBorrowAmount;
(depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _calcAmountWithInterest(userAddr);
return (userDepositAmount, userBorrowAmount);
}
/**
* @dev Get the "latest" handler amount of deposit and borrow including interest (internal, view)
* @param userAddr The user address
* @return "latest" (depositTotalAmount, borrowTotalAmount)
*/
function _getTotalAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256)
{
uint256 depositTotalAmount;
uint256 userDepositAmount;
uint256 borrowTotalAmount;
uint256 userBorrowAmount;
(depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount) = _calcAmountWithInterest(userAddr);
return (depositTotalAmount, borrowTotalAmount);
}
/**
* @dev The deposit and borrow amount with interest for the user
* @param userAddr The user address
* @return "latest" (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount)
*/
function _calcAmountWithInterest(address payable userAddr) internal view returns (uint256, uint256, uint256, uint256)
{
bool depositNegativeFlag;
uint256 deltaDepositAmount;
uint256 globalDepositEXR;
bool borrowNegativeFlag;
uint256 deltaBorrowAmount;
uint256 globalBorrowEXR;
/* calculate interest "delta" amount and params by call Interest Model */
(depositNegativeFlag, deltaDepositAmount, globalDepositEXR, borrowNegativeFlag, deltaBorrowAmount, globalBorrowEXR) = interestModelInstance.getInterestAmount(address(handlerDataStorage), userAddr, true);
/* call _getAmountWithInterest for adding user storage amount and interest delta amount (deposit and borrow)*/
return _getAmountWithInterest(userAddr, depositNegativeFlag, deltaDepositAmount, borrowNegativeFlag, deltaBorrowAmount);
}
/**
* @dev Calculate "latest" amount with interest for the block delta
* @param userAddr The user address
* @param depositNegativeFlag the sign of deltaDepositAmount (true for negative)
* @param deltaDepositAmount The delta amount of deposit
* @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative)
* @param deltaBorrowAmount The delta amount of borrow
* @return "latest" (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount)
*/
function _getAmountWithInterest(address payable userAddr, bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal view returns (uint256, uint256, uint256, uint256)
{
uint256 depositTotalAmount;
uint256 userDepositAmount;
uint256 borrowTotalAmount;
uint256 userBorrowAmount;
(depositTotalAmount, borrowTotalAmount, userDepositAmount, userBorrowAmount) = handlerDataStorage.getAmount(userAddr);
if (depositNegativeFlag)
{
depositTotalAmount = sub(depositTotalAmount, deltaDepositAmount);
userDepositAmount = sub(userDepositAmount, deltaDepositAmount);
}
else
{
depositTotalAmount = add(depositTotalAmount, deltaDepositAmount);
userDepositAmount = add(userDepositAmount, deltaDepositAmount);
}
if (borrowNegativeFlag)
{
borrowTotalAmount = sub(borrowTotalAmount, deltaBorrowAmount);
userBorrowAmount = sub(userBorrowAmount, deltaBorrowAmount);
}
else
{
borrowTotalAmount = add(borrowTotalAmount, deltaBorrowAmount);
userBorrowAmount = add(userBorrowAmount, deltaBorrowAmount);
}
return (depositTotalAmount, userDepositAmount, borrowTotalAmount, userBorrowAmount);
}
/**
* @dev Update the amount of the reserve
* @param depositNegativeFlag the sign of deltaDepositAmount (true for negative)
* @param deltaDepositAmount The delta amount of deposit
* @param borrowNegativeFlag the sign of deltaBorrowAmount (true for negative)
* @param deltaBorrowAmount The delta amount of borrow
* @return true (TODO: validate results)
*/
function _updateReservedAmount(bool depositNegativeFlag, uint256 deltaDepositAmount, bool borrowNegativeFlag, uint256 deltaBorrowAmount) internal returns (bool)
{
int256 signedDeltaDepositAmount = int(deltaDepositAmount);
int256 signedDeltaBorrowAmount = int(deltaBorrowAmount);
if (depositNegativeFlag)
{
signedDeltaDepositAmount = signedDeltaDepositAmount * (-1);
}
if (borrowNegativeFlag)
{
signedDeltaBorrowAmount = signedDeltaBorrowAmount * (-1);
}
/* signedDeltaReservedAmount is singed amount */
int256 signedDeltaReservedAmount = signedSub(signedDeltaBorrowAmount, signedDeltaDepositAmount);
handlerDataStorage.updateSignedReservedAmount(signedDeltaReservedAmount);
return true;
}
/**
* @dev Set the address of the marketManager contract
* @param marketManagerAddr The address of the marketManager contract
* @return true (TODO: validate results)
*/
function setMarketManager(address marketManagerAddr) onlyOwner public returns (bool)
{
marketManager = IMarketManager(marketManagerAddr);
return true;
}
/**
* @dev Set the address of the InterestModel contract
* @param interestModelAddr The address of the InterestModel contract
* @return true (TODO: validate results)
*/
function setInterestModel(address interestModelAddr) onlyOwner public returns (bool)
{
interestModelInstance = IInterestModel(interestModelAddr);
return true;
}
/**
* @dev Set the address of the marketDataStorage contract
* @param marketDataStorageAddr The address of the marketDataStorage contract
* @return true (TODO: validate results)
*/
function setHandlerDataStorage(address marketDataStorageAddr) onlyOwner public returns (bool)
{
handlerDataStorage = IMarketHandlerDataStorage(marketDataStorageAddr);
return true;
}
/**
* @dev Set the address of the siHandlerDataStorage contract
* @param SIHandlerDataStorageAddr The address of the siHandlerDataStorage contract
* @return true (TODO: validate results)
*/
function setSiHandlerDataStorage(address SIHandlerDataStorageAddr) onlyOwner public returns (bool)
{
SIHandlerDataStorage = IMarketSIHandlerDataStorage(SIHandlerDataStorageAddr);
return true;
}
/**
* @dev Get the address of the siHandlerDataStorage contract
* @return The address of the siHandlerDataStorage contract
*/
function getSiHandlerDataStorage() public view returns (address)
{
return address(SIHandlerDataStorage);
}
/**
* @dev Get the address of the marketManager contract
* @return The address of the marketManager contract
*/
function getMarketManagerAddr() public view returns (address)
{
return address(marketManager);
}
/**
* @dev Get the address of the InterestModel contract
* @return The address of the InterestModel contract
*/
function getInterestModelAddr() public view returns (address)
{
return address(interestModelInstance);
}
/**
* @dev Get the address of handler's dataStroage
* @return the address of handler's dataStroage
*/
function getHandlerDataStorageAddr() public view returns (address)
{
return address(handlerDataStorage);
}
/**
* @dev Get the outgoing limit of tokens
* @return The outgoing limit of tokens
*/
function getLimitOfAction() external view returns (uint256)
{
return handlerDataStorage.getLimitOfAction();
}
/* ******************* Safe Math ******************* */
// from: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/SafeMath.sol
// Subject to the MIT license.
function add(uint256 a, uint256 b) internal pure returns (uint256)
{
uint256 c = a + b;
require(c >= a, "add overflow");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256)
{
return _sub(a, b, "sub overflow");
}
function mul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _mul(a, b);
}
function div(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(a, b, "div by zero");
}
function mod(uint256 a, uint256 b) internal pure returns (uint256)
{
return _mod(a, b, "mod by zero");
}
function _sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b <= a, errorMessage);
return a - b;
}
function _mul(uint256 a, uint256 b) internal pure returns (uint256)
{
if (a == 0)
{
return 0;
}
uint256 c = a * b;
require((c / a) == b, "mul overflow");
return c;
}
function _div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b > 0, errorMessage);
return a / b;
}
function _mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256)
{
require(b != 0, errorMessage);
return a % b;
}
function unifiedDiv(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, unifiedPoint), b, "unified div by zero");
}
function unifiedMul(uint256 a, uint256 b) internal pure returns (uint256)
{
return _div(_mul(a, b), unifiedPoint, "unified mul by zero");
}
function signedAdd(int256 a, int256 b) internal pure returns (int256)
{
int256 c = a + b;
require(((b >= 0) && (c >= a)) || ((b < 0) && (c < a)), "SignedSafeMath: addition overflow");
return c;
}
function signedSub(int256 a, int256 b) internal pure returns (int256)
{
int256 c = a - b;
require(((b >= 0) && (c <= a)) || ((b < 0) && (c > a)), "SignedSafeMath: subtraction overflow");
return c;
}
}
|
Get (total deposit liquidity limit - total borrow) of the handler return (total deposit liquidity limit - total borrow) of the handler/
|
function _getTokenLiquidityLimitAmount() internal view returns (uint256)
{
IMarketHandlerDataStorage _handlerDataStorage = handlerDataStorage;
uint256 depositTotalAmount;
uint256 borrowTotalAmount;
(depositTotalAmount, borrowTotalAmount) = _handlerDataStorage.getHandlerAmount();
if (depositTotalAmount == 0)
{
return 0;
}
uint256 liquidityDeposit = unifiedMul(depositTotalAmount, _handlerDataStorage.getLiquidityLimit());
if (liquidityDeposit < borrowTotalAmount)
{
return 0;
}
return sub(liquidityDeposit, borrowTotalAmount);
}
| 2,075,299 |
./full_match/420/0x78C539a0Cc8442ca53Ec8442b2B94f149d9e4a5B/sources/contracts/Zengo.sol
|
votingIteration.vote[msg.sender] = Structs.VerificationState(_vote); votingIteration.hasVoted[msg.sender] = true; votingIteration.voteCount[Structs.VerificationState(_vote)]++; TODO: trigger concludeVotingIteration when one of the consensusIteration reaches the threshold votesPercent update addModerator flag here
|
function voteToClassifyProposal(uint8 _vote, uint8 _votingIteration, uint256 _proposalId)
external
onlyModerator
checkState(1)
{
require(_vote <= uint8(Structs.VerificationState.ApproveForFunding), "Out of Range / Invalid vote option");
require(
!hasVoted[GOVERNANCE_CYCLE][_proposalId][_votingIteration][msg.sender],
"You have already voted for this Voting Iteration of this proposal"
);
vote[GOVERNANCE_CYCLE][_proposalId][_votingIteration][msg.sender] = Structs.VerificationState(_vote);
hasVoted[GOVERNANCE_CYCLE][_proposalId][_votingIteration][msg.sender] = true;
voteCount[GOVERNANCE_CYCLE][_proposalId][_votingIteration][Structs.VerificationState(_vote)]++;
if (
(voteCount[GOVERNANCE_CYCLE][_proposalId][_votingIteration][Structs.VerificationState(_vote)] * 100)
> moderatorList.length * THRESHOLD_VOTE_LIMIT
) {
autoTriggerVoteResult(_votingIteration, _proposalId, Structs.VerificationState(_vote));
}
}
| 13,226,675 |
./full_match/1/0x13Da7C056d46DDB617D5c9EB0EC9e52cb00A26dd/sources/src/ethereum/eth-vaults/general/GeneralMatureHoldingVaultV2.sol
|
Allows transferring assets directly from one mature vault to another by the custodian/owner _newMatureVault The address of the new mature vault to send assets to transfer all assets to new vault
|
function transferAssets(address _newMatureVault) external onlyOwner {
IERC20(DEPOSIT_TOKEN).safeTransfer(_newMatureVault, IERC20(DEPOSIT_TOKEN).balanceOf(address(this)));
}
| 2,899,312 |
./partial_match/3/0x0e227b07FB1e8B9E1690e489c0267271D5Ffc781/sources/MasterChef.sol
|
Safe rigel transfer function, just in case if rounding error causes pool to not have enough Rigel.
|
function safeRigelTransfer(address _to, uint256 _amount) internal {
uint256 rigelBalalance = rigel.balanceOf(address(this));
if (_amount > rigelBalalance) {
rigel.transfer(_to, rigelBalalance);
rigel.transfer(_to, _amount);
}
}
| 5,184,357 |
contract tickingBomb {
struct team {
string name;
uint lastUpdate;
address[] members;
uint nbrMembers;
}
uint public constant DELAY = 60 * 60 * 24; // 24 Hours
uint public constant INVEST_AMOUNT = 1000 finney; // 1 ETH
uint constant FEE = 3;
team public red;
team public blue;
mapping(address => uint) public balances;
address creator;
string[] public historyWinner;
uint[] public historyRed;
uint[] public historyBlue;
uint public gameNbr;
function tickingBomb() {
newRound();
creator = msg.sender;
gameNbr = 0;
}
function helpRed() {
uint i;
uint amount = msg.value;
// Check if Exploded, if so save the previous game
// And create a new round
checkIfExploded();
// Update the TimeStamp
red.lastUpdate = block.timestamp;
// Split the incoming money every INVEST_AMOUNT
while (amount >= INVEST_AMOUNT) {
red.members.push(msg.sender);
red.nbrMembers++;
amount -= INVEST_AMOUNT;
}
// If there is still some money in the balance, sent it back
if (amount > 0) {
msg.sender.send(amount);
}
}
function helpBlue() {
uint i;
uint amount = msg.value;
// Check if Exploded, if so save the previous game
// And create a new game
checkIfExploded();
// Update the TimeStamp
blue.lastUpdate = block.timestamp;
// Split the incoming money every 100 finneys
while (amount >= INVEST_AMOUNT) {
blue.members.push(msg.sender);
blue.nbrMembers++;
amount -= INVEST_AMOUNT;
}
// If there is still some money in the balance, sent it back
if (amount > 0) {
msg.sender.send(amount);
}
}
function checkIfExploded() {
if (checkTime()) {
newRound();
}
}
function checkTime() private returns(bool exploded) {
uint i;
uint lostAmount = 0;
uint gainPerMember = 0;
uint feeCollected = 0;
// If Red and Blue have exploded at the same time, return the amounted invested
if (red.lastUpdate == blue.lastUpdate && red.lastUpdate + DELAY < block.timestamp) {
for (i = 0; i < red.members.length; i++) {
balances[red.members[i]] += INVEST_AMOUNT;
}
for (i = 0; i < blue.members.length; i++) {
balances[blue.members[i]] += INVEST_AMOUNT;
}
historyWinner.push('Tie between Red and Blue');
historyRed.push(red.nbrMembers);
historyBlue.push(blue.nbrMembers);
gameNbr++;
return true;
}
// Take the older timestamp
if (red.lastUpdate < blue.lastUpdate) {
// Check if the Red bomb exploded
if (red.lastUpdate + DELAY < block.timestamp) {
// Calculate the lost amount by the red team
// Number of Red member * Invested amount per user *
feeCollected += (red.nbrMembers * INVEST_AMOUNT * FEE / 100);
balances[creator] += feeCollected;
lostAmount = (red.nbrMembers * INVEST_AMOUNT) - feeCollected;
gainPerMember = lostAmount / blue.nbrMembers;
for (i = 0; i < blue.members.length; i++) {
balances[blue.members[i]] += (INVEST_AMOUNT + gainPerMember);
}
historyWinner.push('Red');
historyRed.push(red.nbrMembers);
historyBlue.push(blue.nbrMembers);
gameNbr++;
return true;
}
return false;
} else {
// Check if the Blue bomb exploded
if (blue.lastUpdate + DELAY < block.timestamp) {
// Calculate the lost amount by the red team
// Number of Red member * Invested amount per user *
feeCollected += (blue.nbrMembers * INVEST_AMOUNT * FEE / 100);
balances[creator] += feeCollected;
lostAmount = (blue.nbrMembers * INVEST_AMOUNT) - feeCollected;
gainPerMember = lostAmount / red.nbrMembers;
for (i = 0; i < red.members.length; i++) {
balances[red.members[i]] += (INVEST_AMOUNT + gainPerMember);
}
historyWinner.push('Blue');
historyRed.push(red.nbrMembers);
historyBlue.push(blue.nbrMembers);
gameNbr++;
return true;
}
return false;
}
}
function newRound() private {
red.name = "Red team";
blue.name = "Blue team";
red.lastUpdate = block.timestamp;
blue.lastUpdate = block.timestamp;
red.nbrMembers = 0;
blue.nbrMembers = 0;
red.members = new address[](0);
blue.members = new address[](0);
}
function() {
// Help the oldest timestamp (going to explode first)
if (red.lastUpdate < blue.lastUpdate) {
helpRed();
} else {
helpBlue();
}
}
function collectBalance() {
msg.sender.send(balances[msg.sender]);
balances[msg.sender] = 0;
}
// Allow the creator to send their balances to the players
function sendBalance(address player) {
if (msg.sender == creator) {
player.send(balances[player]);
}
}
function newOwner(address newOwner) {
if (msg.sender == creator) {
creator = newOwner;
}
}
}
|
Allow the creator to send their balances to the players
|
function sendBalance(address player) {
if (msg.sender == creator) {
player.send(balances[player]);
}
}
| 923,456 |
./full_match/1/0xf0BA303fd2CE5eBbb22d0d6590463D7549A08388/sources/browser/strategy-cmpd-dai-v1.sol
|
SPDX-License-Identifier: MIT
|
interface ICToken {
function totalSupply() external view returns (uint256);
function totalBorrows() external returns (uint256);
function borrowIndex() external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function mint(uint256 mintAmount) external returns (uint256);
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 exchangeRateStored() external view returns (uint256);
function getCash() external view returns (uint256);
function accrueInterest() external returns (uint256);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
}
| 3,009,675 |
/**
*Submitted for verification at Etherscan.io on 2022-04-02
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: Vesting.sol
pragma solidity ^0.8.3;
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address to, uint256 amount) external returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
contract VestingHarvestContarct is Ownable {
/*
* Vesting Information
*/
struct VestingItems {
address tokenAddress;
address withdrawalAddress;
uint256 tokenAmount;
uint256 unlockTime;
bool withdrawn;
}
uint256 public vestingSize;
uint256[] public allVestingIdentifiers;
mapping(address => uint256[]) public vestingsByWithdrawalAddress;
mapping(uint256 => VestingItems) public vestedToken;
mapping(address => mapping(address => uint256))
public walletVestedTokenBalance;
event VestingExecution(address SentToAddress, uint256 AmountTransferred);
event WithdrawalExecution(address SentToAddress, uint256 AmountTransferred);
/**
* Init vestings
*/
function initVestings(
address _tokenAddress,
address _withdrawalAddress,
uint256[] memory _amounts,
uint256[] memory _unlockTimes
) public {
require(_amounts.length > 0);
require(_amounts.length == _unlockTimes.length);
for (uint256 i = 0; i < _amounts.length; i++) {
require(_amounts[i] > 0);
require(_unlockTimes[i] < 10000000000);
// Update balance in address
walletVestedTokenBalance[_tokenAddress][_withdrawalAddress] =
walletVestedTokenBalance[_tokenAddress][_withdrawalAddress] +
_amounts[i];
vestingSize = vestingSize + 1;
vestedToken[vestingSize].tokenAddress = _tokenAddress;
vestedToken[vestingSize].withdrawalAddress = _withdrawalAddress;
vestedToken[vestingSize].tokenAmount = _amounts[i];
vestedToken[vestingSize].unlockTime = _unlockTimes[i];
vestedToken[vestingSize].withdrawn = false;
allVestingIdentifiers.push(vestingSize);
vestingsByWithdrawalAddress[_withdrawalAddress].push(vestingSize);
// Transfer tokens into contract
require(
IERC20(_tokenAddress).transferFrom(
msg.sender,
address(this),
_amounts[i]
)
);
emit VestingExecution(_withdrawalAddress, _amounts[i]);
}
}
/**
* Withdraw vested tokens
*/
function withdrawVestedTokens(uint256 _id) public {
require(block.timestamp >= vestedToken[_id].unlockTime);
require(msg.sender == vestedToken[_id].withdrawalAddress);
require(!vestedToken[_id].withdrawn);
vestedToken[_id].withdrawn = true;
walletVestedTokenBalance[vestedToken[_id].tokenAddress][msg.sender] =
walletVestedTokenBalance[vestedToken[_id].tokenAddress][
msg.sender
] -
vestedToken[_id].tokenAmount;
uint256 arrLength = vestingsByWithdrawalAddress[vestedToken[_id].withdrawalAddress].length;
for (uint256 j = 0; j < arrLength; j++) {
if (
vestingsByWithdrawalAddress[vestedToken[_id].withdrawalAddress][j] == _id
) {
vestingsByWithdrawalAddress[vestedToken[_id].withdrawalAddress][j] = vestingsByWithdrawalAddress[
vestedToken[_id].withdrawalAddress][arrLength - 1];
vestingsByWithdrawalAddress[vestedToken[_id].withdrawalAddress].pop();
break;
}
}
require(
IERC20(vestedToken[_id].tokenAddress).transfer(
msg.sender,
vestedToken[_id].tokenAmount
)
);
emit WithdrawalExecution(msg.sender, vestedToken[_id].tokenAmount);
}
/* Get total token balance in contract*/
function getTotalVestedTokenBalance(address _tokenAddress)
public
view
returns (uint256)
{
return IERC20(_tokenAddress).balanceOf(address(this));
}
/* Get total token balance by address */
function getVestedTokenBalanceByAddress(
address _tokenAddress,
address _walletAddress
) public view returns (uint256) {
return walletVestedTokenBalance[_tokenAddress][_walletAddress];
}
/* Get allVestingIdentifiers */
function getAllVestingIdentifiers() public view returns (uint256[] memory) {
return allVestingIdentifiers;
}
/* Get getVestingDetails */
function getVestingDetails(uint256 _id)
public
view
returns (
address _tokenAddress,
address _withdrawalAddress,
uint256 _tokenAmount,
uint256 _unlockTime,
bool _withdrawn
)
{
return (
vestedToken[_id].tokenAddress,
vestedToken[_id].withdrawalAddress,
vestedToken[_id].tokenAmount,
vestedToken[_id].unlockTime,
vestedToken[_id].withdrawn
);
}
/* Get VestingsByWithdrawalAddress */
function getVestingsByWithdrawalAddress(address _withdrawalAddress)
public
view
returns (uint256[] memory)
{
return vestingsByWithdrawalAddress[_withdrawalAddress];
}
}
|
Get VestingsByWithdrawalAddress /
|
function getVestingsByWithdrawalAddress(address _withdrawalAddress)
public
view
returns (uint256[] memory)
{
return vestingsByWithdrawalAddress[_withdrawalAddress];
}
| 2,028,644 |
//SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "hardhat/console.sol";
import "./Pond.sol";
import "./Loan.sol";
import "./CredentialVerifier.sol";
import "../libraries/types/Types.sol";
import "../interfaces/IVerificationRegistry.sol";
import "../interfaces/IWRBTC.sol";
contract Pond is Ownable, CredentialVerifier {
using SafeMath for uint256;
Types.PondParams private params;
address public immutable WRBTC;
address public immutable verificationRegistry;
mapping(address => uint256) public getLenderBalance;
mapping(address => Loan) public getLoan;
uint256 public totalDeposited;
uint256 public totalUtilized;
uint256 public totalInterest;
bool public active;
event RepayLoan(
address indexed addr,
address indexed sender,
uint256 amount,
uint256 timestamp
);
modifier notClosed() {
require(active, "Growr. - Pond is not active anymore");
_;
}
modifier wrbtcPond() {
require(
address(params.token) == WRBTC,
"Growr. - RBTC not supported by this Pond"
);
_;
}
constructor(
address _verificationRegistry,
address _wrbtc,
Types.PondParams memory _params,
Types.PondCriteriaInput memory _criteria
) CredentialVerifier(_criteria) {
active = true;
params = _params;
verificationRegistry = _verificationRegistry;
WRBTC = _wrbtc;
}
// receives unwrapped rbtc
receive() external payable {}
function _deposit(uint256 _amount) private {
require(_amount > 0, "Growr. - Deposit amount must be more than 0");
totalDeposited = totalDeposited.add(_amount);
getLenderBalance[msg.sender] = getLenderBalance[msg.sender].add(
_amount
);
}
function _withdraw(uint256 _amount) private {
require(_amount > 0, "Growr. - Withdraw amount must be more than 0");
uint256 lenderBalance = getLenderBalance[msg.sender];
uint256 availableAmount = getAvailableBalance();
require(
lenderBalance > 0 && lenderBalance >= _amount,
"Growr. - Withdrawal amount exceeds your balance"
);
require(
availableAmount >= _amount,
"Growr. - Withdrawal amount exceeds available balance"
);
// reduce lender's balance and total amount of deposited funds
getLenderBalance[msg.sender] = lenderBalance.sub(_amount);
totalDeposited = totalDeposited.sub(_amount);
}
/**
returns available balance that can be borrowed
*/
function getAvailableBalance() public view returns (uint256) {
return params.token.balanceOf(address(this)).sub(totalInterest);
}
function getDetails()
public
view
returns (
Types.PondParams memory _params,
Types.PondCriteria[] memory _criteria,
uint256 _totalDeposited,
uint256 _totalUtilized,
uint256 _totalInterest
)
{
return (params, criteria, totalDeposited, totalUtilized, totalInterest);
}
/**
Checks if the user is eligible for borrowing a loan.
If some of the input params are not in the pond capabilities,
it returns the most suitable loan the user can borrow at that time
*/
function getLoanOffer(
uint256 _amount,
uint256 _duration,
Types.PersonalCredentialsInput memory _credentials
) external view notClosed returns (Types.LoanOffer memory _loan) {
uint256 amount = _amount;
uint256 duration = _duration;
// get most suitable loan amount
if (amount < params.minLoanAmount) amount = params.minLoanAmount;
else if (amount > params.maxLoanAmount) amount = params.maxLoanAmount;
// get most suitable loan duration
if (duration < params.minLoanDuration)
duration = params.minLoanDuration;
else if (duration > params.maxLoanDuration)
duration = params.maxLoanDuration;
bool eligible = verifyCredentials(_credentials);
// check available balance
uint256 balance = getAvailableBalance();
if (balance <= 0) eligible = false;
if (amount > balance) amount = balance;
_loan = Types.LoanOffer(
false,
amount,
duration,
params.annualInterestRate,
params.disbursmentFee,
params.cashBackRate,
0,
0,
0
);
if (eligible) {
_loan.approved = true;
_loan.totalInterest = amount
.mul(params.annualInterestRate)
.mul(duration)
.div(100)
.div(12);
_loan.totalAmount = amount.add(_loan.totalInterest);
_loan.installmentAmount = _loan.totalAmount.div(duration);
}
return _loan;
}
function borrow(uint256 _amount, uint256 _duration) public {
require(
_amount >= params.minLoanAmount,
"Growr.- Amount is less than min loan amount"
);
require(
_amount <= params.maxLoanAmount,
"Growr. - Amount exceeds max loan amount"
);
require(
_amount <= getAvailableBalance(),
"Growr. - Not enough funds to borrow"
);
require(
_duration >= params.minLoanDuration,
"Growr. - Duration is less than min loan duration"
);
require(
_duration <= params.maxLoanDuration,
"Growr. - Duration exceeds max loan duration"
);
bool eligible = IVerificationRegistry(verificationRegistry)
.validateVerification(msg.sender, address(this));
require(eligible, "Growr. - Eligibility verificaiton failed");
totalUtilized = totalUtilized.add(_amount);
getLoan[msg.sender] = new Loan(
params.token,
_amount,
_duration,
params.annualInterestRate,
params.disbursmentFee,
params.cashBackRate
);
params.token.transfer(msg.sender, _amount);
}
function repay(uint256 _amount, address _loan) external {
require(_amount > 0, "Growr. - Repay amount must be more than 0");
Loan loan = getLoan[msg.sender];
require(address(loan) == _loan, "Growr. - Loan does not exists");
(uint256 principal, uint256 interest) = loan.repay(_amount);
totalUtilized = totalUtilized.sub(principal);
totalInterest = totalInterest.add(interest);
params.token.transferFrom(msg.sender, address(this), _amount);
emit RepayLoan(address(loan), msg.sender, _amount, block.timestamp);
}
/**
Deposit RBTC only if the current Pond supports it
Wrap the native RBTC into WRBTC
*/
function depositRBTC(uint256 _amount) external payable wrbtcPond notClosed {
require(
_amount <= msg.value,
"Growr. - Deposit amount exceeds the sending amount"
);
_deposit(_amount);
IWRBTC(WRBTC).deposit{value: _amount}();
}
/**
Deposit every ERC20 token supported by the current Pond
*/
function deposit(uint256 _amount) external notClosed {
_deposit(_amount);
params.token.transferFrom(msg.sender, address(this), _amount);
}
function withdrawRBTC(uint256 _amount) external wrbtcPond {
_withdraw(_amount);
IWRBTC(WRBTC).withdraw(_amount);
payable(msg.sender).transfer(_amount);
}
function withdraw(uint256 _amount) external {
_withdraw(_amount);
// TODO: withdraw interest
// totalInterest = ??
params.token.transfer(msg.sender, _amount);
}
}
|
/ get most suitable loan amount get most suitable loan duration check available balance
|
function getLoanOffer(
uint256 _amount,
uint256 _duration,
Types.PersonalCredentialsInput memory _credentials
) external view notClosed returns (Types.LoanOffer memory _loan) {
uint256 amount = _amount;
uint256 duration = _duration;
if (amount < params.minLoanAmount) amount = params.minLoanAmount;
else if (amount > params.maxLoanAmount) amount = params.maxLoanAmount;
if (duration < params.minLoanDuration)
duration = params.minLoanDuration;
else if (duration > params.maxLoanDuration)
duration = params.maxLoanDuration;
bool eligible = verifyCredentials(_credentials);
uint256 balance = getAvailableBalance();
if (balance <= 0) eligible = false;
if (amount > balance) amount = balance;
_loan = Types.LoanOffer(
false,
amount,
duration,
params.annualInterestRate,
params.disbursmentFee,
params.cashBackRate,
0,
0,
0
);
if (eligible) {
_loan.approved = true;
_loan.totalInterest = amount
.mul(params.annualInterestRate)
.mul(duration)
.div(100)
.div(12);
_loan.totalAmount = amount.add(_loan.totalInterest);
_loan.installmentAmount = _loan.totalAmount.div(duration);
}
return _loan;
}
| 12,963,530 |
/**
*Submitted for verification at Etherscan.io on 2022-03-21
*/
/**
*Submitted for verification at Etherscan.io on 2022-03-20
*/
// File: contracts/Interfaces/IDistro.sol
pragma solidity =0.8.6;
interface IDistro {
/**
* @dev Emitted when someone makes a claim of tokens
*/
event Claim(address indexed grantee, uint256 amount);
/**
* @dev Emitted when the DISTRIBUTOR allocate an amount to a grantee
*/
event Allocate(
address indexed distributor,
address indexed grantee,
uint256 amount
);
/**
* @dev Emitted when the DEFAULT_ADMIN assign an amount to a DISTRIBUTOR
*/
event Assign(
address indexed admin,
address indexed distributor,
uint256 amount
);
/**
* @dev Emitted when someone change their reception address
*/
event ChangeAddress(address indexed oldAddress, address indexed newAddress);
/**
* @dev Emitted when a new startTime is set
*/
event StartTimeChanged(uint256 newStartTime, uint256 newCliffTime);
/**
* @dev Returns the total amount of tokens will be streamed
*/
function totalTokens() external view returns (uint256);
/**
* Function that allows the DEFAULT_ADMIN_ROLE to assign set a new startTime if it hasn't started yet
* @param newStartTime new startTime
*
* Emits a {StartTimeChanged} event.
*
*/
function setStartTime(uint256 newStartTime) external;
/**
* Function that allows the DEFAULT_ADMIN_ROLE to assign tokens to an address who later can distribute them.
* @dev It is required that the DISTRIBUTOR_ROLE is already held by the address to which an amount will be assigned
* @param distributor the address, generally a smart contract, that will determine who gets how many tokens
* @param amount Total amount of tokens to assign to that address for distributing
*/
function assign(address distributor, uint256 amount) external;
/**
* Function to claim tokens for a specific address. It uses the current timestamp
*/
function claim() external;
/**
* Function that allows to the distributor address to allocate some amount of tokens to a specific recipient
* @dev Needs to be initialized: Nobody has the DEFAULT_ADMIN_ROLE and all available tokens have been assigned
* @param recipient of token allocation
* @param amount allocated amount
* @param claim whether claim after allocate
*/
function allocate(
address recipient,
uint256 amount,
bool claim
) external;
/**
* Function that allows to the distributor address to allocate some amounts of tokens to specific recipients
* @dev Needs to be initialized: Nobody has the DEFAULT_ADMIN_ROLE and all available tokens have been assigned
* @param recipients of token allocation
* @param amounts allocated amount
*/
function allocateMany(address[] memory recipients, uint256[] memory amounts)
external;
function sendGIVbacks(address[] memory recipients, uint256[] memory amounts)
external;
/**
* Function that allows a recipient to change its address
* @dev The change can only be made to an address that has not previously received an allocation &
* the distributor cannot change its address
*/
function changeAddress(address newAddress) external;
/**
* Function to get the current timestamp from the block
*/
function getTimestamp() external view returns (uint256);
/**
* Function to get the total unlocked tokes at some moment
*/
function globallyClaimableAt(uint256 timestamp)
external
view
returns (uint256);
/**
* Function to get the unlocked tokes at some moment for a specific address
*/
function claimableAt(address recipient, uint256 timestamp)
external
view
returns (uint256);
/**
* Function to get the unlocked tokens for a specific address. It uses the current timestamp
*/
function claimableNow(address recipient) external view returns (uint256);
function cancelAllocation(address prevRecipient, address newRecipient)
external;
}
// File: openzeppelin-contracts-upgradable-v4/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 a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File: openzeppelin-contracts-upgradable-v4/utils/ContextUpgradeable.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 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;
}
// File: openzeppelin-contracts-upgradable-v4/access/OwnableUpgradeable.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 OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
uint256[49] private __gap;
}
// File: openzeppelin-contracts-v4/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: contracts/Tokens/UniswapV3RewardToken.sol
pragma solidity 0.8.6;
contract UniswapV3RewardToken is IERC20, OwnableUpgradeable {
uint256 public initialBalance;
string public constant name = "Giveth Uniswap V3 Reward Token";
string public constant symbol = "GUR";
uint8 public constant decimals = 18;
IDistro public tokenDistro;
address public uniswapV3Staker;
uint256 public override totalSupply;
bool public disabled;
event RewardPaid(address indexed user, uint256 reward);
/// @dev Event emitted when an account tried to claim a reward (via calling `trasnfer) while the contract
// is disabled.
/// @param user The account that called `transfer`
/// @param reward The amount that was tried to claim
event InvalidRewardPaid(address indexed user, uint256 reward);
/// @dev Event emitted when the contract is disabled
/// @param account The account that disabled the contract
event Disabled(address account);
/// @dev Event emittd when the contract is enabled
/// @param account The account that enabled the contract
event Enabled(address account);
function initialize(IDistro _tokenDistribution, address _uniswapV3Staker)
public
initializer
{
__Ownable_init();
tokenDistro = _tokenDistribution;
uniswapV3Staker = _uniswapV3Staker;
}
function balanceOf(address account) public view override returns (uint256) {
if (account == uniswapV3Staker) return totalSupply;
return 0;
}
function approve(address, uint256) external pure override returns (bool) {
return true;
}
function transfer(address to, uint256 value)
external
override
returns (bool)
{
require(
msg.sender == uniswapV3Staker,
"GivethUniswapV3Reward:transfer:ONLY_STAKER"
);
totalSupply = totalSupply - value;
if (!disabled) {
tokenDistro.allocate(to, value, true);
emit RewardPaid(to, value);
} else {
emit InvalidRewardPaid(to, value);
}
return true;
}
function transferFrom(
address from,
address to,
uint256 value
) external override returns (bool) {
require(
from == owner(),
"GivethUniswapV3Reward:transferFrom:ONLY_OWNER_CAN_ADD_INCENTIVES"
);
// Only uniswapV3Staker can do the transferFrom
require(
msg.sender == uniswapV3Staker,
"GivethUniswapV3Reward:transferFrom:ONLY_STAKER"
);
// Only to uniswapV3Staker is allowed
require(
to == uniswapV3Staker,
"GivethUniswapV3Reward:transferFrom:ONLY_TO_STAKER"
);
totalSupply = totalSupply + value;
emit Transfer(address(0), to, value);
return true;
}
function allowance(address, address spender)
external
view
override
returns (uint256)
{
if (spender == uniswapV3Staker) return type(uint256).max;
return 0;
}
/// @notice Disable the token. If disabled, rewards are not payable.
/// @dev Can only be called by the Owner.
function disable() external onlyOwner {
disabled = true;
emit Disabled(msg.sender);
}
/// @notice Enable the token. If enabled, rewards are payable.
/// @dev Can only be called by the Owner.
function enable() external onlyOwner {
disabled = false;
emit Enabled(msg.sender);
}
}
|
Enable the token. If enabled, rewards are payable. Can only be called by the Owner.
|
function enable() external onlyOwner {
disabled = false;
emit Enabled(msg.sender);
}
| 2,316,840 |
pragma solidity ^0.8.0;
// #### Interface for interacting with COMPOUND protocol ####
interface ICompProxy {
function mint() external payable;
function redeem(uint256 _amount) external;
function balanceOf(address owner) external view returns (uint256 balance);
}
|
Interface for interacting with COMPOUND protocol
|
interface ICompProxy {
function mint() external payable;
function redeem(uint256 _amount) external;
function balanceOf(address owner) external view returns (uint256 balance);
}
| 13,073,881 |
/*
Zethr | https://zethr.io
(c) Copyright 2018 | All Rights Reserved
This smart contract was developed by the Zethr Dev Team and its source code remains property of the Zethr Project.
*/
pragma solidity ^0.4.24;
// File: contracts/Libraries/SafeMath.sol
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
assert(c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
// File: contracts/Libraries/ZethrTierLibrary.sol
library ZethrTierLibrary {
uint constant internal magnitude = 2 ** 64;
// Gets the tier (1-7) of the divs sent based off of average dividend rate
// This is an index used to call into the correct sub-bankroll to withdraw tokens
function getTier(uint divRate) internal pure returns (uint8) {
// Divide the average dividned rate by magnitude
// Remainder doesn't matter because of the below logic
uint actualDiv = divRate / magnitude;
if (actualDiv >= 30) {
return 6;
} else if (actualDiv >= 25) {
return 5;
} else if (actualDiv >= 20) {
return 4;
} else if (actualDiv >= 15) {
return 3;
} else if (actualDiv >= 10) {
return 2;
} else if (actualDiv >= 5) {
return 1;
} else if (actualDiv >= 2) {
return 0;
} else {
// Impossible
revert();
}
}
function getDivRate(uint _tier)
internal pure
returns (uint8)
{
if (_tier == 0) {
return 2;
} else if (_tier == 1) {
return 5;
} else if (_tier == 2) {
return 10;
} else if (_tier == 3) {
return 15;
} else if (_tier == 4) {
return 20;
} else if (_tier == 5) {
return 25;
} else if (_tier == 6) {
return 33;
} else {
revert();
}
}
}
// File: contracts/ERC/ERC223Receiving.sol
contract ERC223Receiving {
function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool);
}
// File: contracts/ZethrMultiSigWallet.sol
/* Zethr MultisigWallet
*
* Standard multisig wallet
* Holds the bankroll ETH, as well as the bankroll 33% ZTH tokens.
*/
contract ZethrMultiSigWallet is ERC223Receiving {
using SafeMath for uint;
/*=================================
= EVENTS =
=================================*/
event Confirmation(address indexed sender, uint indexed transactionId);
event Revocation(address indexed sender, uint indexed transactionId);
event Submission(uint indexed transactionId);
event Execution(uint indexed transactionId);
event ExecutionFailure(uint indexed transactionId);
event Deposit(address indexed sender, uint value);
event OwnerAddition(address indexed owner);
event OwnerRemoval(address indexed owner);
event WhiteListAddition(address indexed contractAddress);
event WhiteListRemoval(address indexed contractAddress);
event RequirementChange(uint required);
event BankrollInvest(uint amountReceived);
/*=================================
= VARIABLES =
=================================*/
mapping (uint => Transaction) public transactions;
mapping (uint => mapping (address => bool)) public confirmations;
mapping (address => bool) public isOwner;
address[] public owners;
uint public required;
uint public transactionCount;
bool internal reEntered = false;
uint constant public MAX_OWNER_COUNT = 15;
/*=================================
= CUSTOM CONSTRUCTS =
=================================*/
struct Transaction {
address destination;
uint value;
bytes data;
bool executed;
}
struct TKN {
address sender;
uint value;
}
/*=================================
= MODIFIERS =
=================================*/
modifier onlyWallet() {
if (msg.sender != address(this))
revert();
_;
}
modifier isAnOwner() {
address caller = msg.sender;
if (isOwner[caller])
_;
else
revert();
}
modifier ownerDoesNotExist(address owner) {
if (isOwner[owner])
revert();
_;
}
modifier ownerExists(address owner) {
if (!isOwner[owner])
revert();
_;
}
modifier transactionExists(uint transactionId) {
if (transactions[transactionId].destination == 0)
revert();
_;
}
modifier confirmed(uint transactionId, address owner) {
if (!confirmations[transactionId][owner])
revert();
_;
}
modifier notConfirmed(uint transactionId, address owner) {
if (confirmations[transactionId][owner])
revert();
_;
}
modifier notExecuted(uint transactionId) {
if (transactions[transactionId].executed)
revert();
_;
}
modifier notNull(address _address) {
if (_address == 0)
revert();
_;
}
modifier validRequirement(uint ownerCount, uint _required) {
if ( ownerCount > MAX_OWNER_COUNT
|| _required > ownerCount
|| _required == 0
|| ownerCount == 0)
revert();
_;
}
/*=================================
= PUBLIC FUNCTIONS =
=================================*/
/// @dev Contract constructor sets initial owners and required number of confirmations.
/// @param _owners List of initial owners.
/// @param _required Number of required confirmations.
constructor (address[] _owners, uint _required)
public
validRequirement(_owners.length, _required)
{
// Add owners
for (uint i=0; i<_owners.length; i++) {
if (isOwner[_owners[i]] || _owners[i] == 0)
revert();
isOwner[_owners[i]] = true;
}
// Set owners
owners = _owners;
// Set required
required = _required;
}
/** Testing only.
function exitAll()
public
{
uint tokenBalance = ZTHTKN.balanceOf(address(this));
ZTHTKN.sell(tokenBalance - 1e18);
ZTHTKN.sell(1e18);
ZTHTKN.withdraw(address(0x0));
}
**/
/// @dev Fallback function allows Ether to be deposited.
function()
public
payable
{
}
/// @dev Allows to add a new owner. Transaction has to be sent by wallet.
/// @param owner Address of new owner.
function addOwner(address owner)
public
onlyWallet
ownerDoesNotExist(owner)
notNull(owner)
validRequirement(owners.length + 1, required)
{
isOwner[owner] = true;
owners.push(owner);
emit OwnerAddition(owner);
}
/// @dev Allows to remove an owner. Transaction has to be sent by wallet.
/// @param owner Address of owner.
function removeOwner(address owner)
public
onlyWallet
ownerExists(owner)
validRequirement(owners.length, required)
{
isOwner[owner] = false;
for (uint i=0; i<owners.length - 1; i++)
if (owners[i] == owner) {
owners[i] = owners[owners.length - 1];
break;
}
owners.length -= 1;
if (required > owners.length)
changeRequirement(owners.length);
emit OwnerRemoval(owner);
}
/// @dev Allows to replace an owner with a new owner. Transaction has to be sent by wallet.
/// @param owner Address of owner to be replaced.
/// @param owner Address of new owner.
function replaceOwner(address owner, address newOwner)
public
onlyWallet
ownerExists(owner)
ownerDoesNotExist(newOwner)
{
for (uint i=0; i<owners.length; i++)
if (owners[i] == owner) {
owners[i] = newOwner;
break;
}
isOwner[owner] = false;
isOwner[newOwner] = true;
emit OwnerRemoval(owner);
emit OwnerAddition(newOwner);
}
/// @dev Allows to change the number of required confirmations. Transaction has to be sent by wallet.
/// @param _required Number of required confirmations.
function changeRequirement(uint _required)
public
onlyWallet
validRequirement(owners.length, _required)
{
required = _required;
emit RequirementChange(_required);
}
/// @dev Allows an owner to submit and confirm a transaction.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function submitTransaction(address destination, uint value, bytes data)
public
returns (uint transactionId)
{
transactionId = addTransaction(destination, value, data);
confirmTransaction(transactionId);
}
/// @dev Allows an owner to confirm a transaction.
/// @param transactionId Transaction ID.
function confirmTransaction(uint transactionId)
public
ownerExists(msg.sender)
transactionExists(transactionId)
notConfirmed(transactionId, msg.sender)
{
confirmations[transactionId][msg.sender] = true;
emit Confirmation(msg.sender, transactionId);
executeTransaction(transactionId);
}
/// @dev Allows an owner to revoke a confirmation for a transaction.
/// @param transactionId Transaction ID.
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
/// @dev Allows anyone to execute a confirmed transaction.
/// @param transactionId Transaction ID.
function executeTransaction(uint transactionId)
public
notExecuted(transactionId)
{
if (isConfirmed(transactionId)) {
Transaction storage txToExecute = transactions[transactionId];
txToExecute.executed = true;
if (txToExecute.destination.call.value(txToExecute.value)(txToExecute.data))
emit Execution(transactionId);
else {
emit ExecutionFailure(transactionId);
txToExecute.executed = false;
}
}
}
/// @dev Returns the confirmation status of a transaction.
/// @param transactionId Transaction ID.
/// @return Confirmation status.
function isConfirmed(uint transactionId)
public
constant
returns (bool)
{
uint count = 0;
for (uint i=0; i<owners.length; i++) {
if (confirmations[transactionId][owners[i]])
count += 1;
if (count == required)
return true;
}
}
/*=================================
= OPERATOR FUNCTIONS =
=================================*/
/// @dev Adds a new transaction to the transaction mapping, if transaction does not exist yet.
/// @param destination Transaction target address.
/// @param value Transaction ether value.
/// @param data Transaction data payload.
/// @return Returns transaction ID.
function addTransaction(address destination, uint value, bytes data)
internal
notNull(destination)
returns (uint transactionId)
{
transactionId = transactionCount;
transactions[transactionId] = Transaction({
destination: destination,
value: value,
data: data,
executed: false
});
transactionCount += 1;
emit Submission(transactionId);
}
/*
* Web3 call functions
*/
/// @dev Returns number of confirmations of a transaction.
/// @param transactionId Transaction ID.
/// @return Number of confirmations.
function getConfirmationCount(uint transactionId)
public
constant
returns (uint count)
{
for (uint i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]])
count += 1;
}
/// @dev Returns total number of transactions after filers are applied.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Total number of transactions after filters are applied.
function getTransactionCount(bool pending, bool executed)
public
constant
returns (uint count)
{
for (uint i=0; i<transactionCount; i++)
if (pending && !transactions[i].executed || executed && transactions[i].executed)
count += 1;
}
/// @dev Returns list of owners.
/// @return List of owner addresses.
function getOwners()
public
constant
returns (address[])
{
return owners;
}
/// @dev Returns array with owner addresses, which confirmed transaction.
/// @param transactionId Transaction ID.
/// @return Returns array of owner addresses.
function getConfirmations(uint transactionId)
public
constant
returns (address[] _confirmations)
{
address[] memory confirmationsTemp = new address[](owners.length);
uint count = 0;
uint i;
for (i=0; i<owners.length; i++)
if (confirmations[transactionId][owners[i]]) {
confirmationsTemp[count] = owners[i];
count += 1;
}
_confirmations = new address[](count);
for (i=0; i<count; i++)
_confirmations[i] = confirmationsTemp[i];
}
/// @dev Returns list of transaction IDs in defined range.
/// @param from Index start position of transaction array.
/// @param to Index end position of transaction array.
/// @param pending Include pending transactions.
/// @param executed Include executed transactions.
/// @return Returns array of transaction IDs.
function getTransactionIds(uint from, uint to, bool pending, bool executed)
public
constant
returns (uint[] _transactionIds)
{
uint[] memory transactionIdsTemp = new uint[](transactionCount);
uint count = 0;
uint i;
for (i=0; i<transactionCount; i++)
if (pending && !transactions[i].executed || executed && transactions[i].executed) {
transactionIdsTemp[count] = i;
count += 1;
}
_transactionIds = new uint[](to - from);
for (i=from; i<to; i++)
_transactionIds[i - from] = transactionIdsTemp[i];
}
function tokenFallback(address /*_from*/, uint /*_amountOfTokens*/, bytes /*_data*/)
public
returns (bool)
{
return true;
}
}
// File: contracts/Bankroll/Interfaces/ZethrTokenBankrollInterface.sol
// Zethr token bankroll function prototypes
contract ZethrTokenBankrollInterface is ERC223Receiving {
uint public jackpotBalance;
function getMaxProfit(address) public view returns (uint);
function gameTokenResolution(uint _toWinnerAmount, address _winnerAddress, uint _toJackpotAmount, address _jackpotAddress, uint _originalBetSize) external;
function payJackpotToWinner(address _winnerAddress, uint payoutDivisor) public;
}
// File: contracts/Bankroll/Interfaces/ZethrBankrollControllerInterface.sol
contract ZethrBankrollControllerInterface is ERC223Receiving {
address public jackpotAddress;
ZethrTokenBankrollInterface[7] public tokenBankrolls;
ZethrMultiSigWallet public multiSigWallet;
mapping(address => bool) public validGameAddresses;
function gamePayoutResolver(address _resolver, uint _tokenAmount) public;
function isTokenBankroll(address _address) public view returns (bool);
function getTokenBankrollAddressFromTier(uint8 _tier) public view returns (address);
function tokenFallback(address _from, uint _amountOfTokens, bytes _data) public returns (bool);
}
// File: contracts/Bankroll/ZethrGame.sol
/* Zethr Game Interface
*
* Contains the necessary functions to integrate with
* the Zethr Token bankrolls & the Zethr game ecosystem.
*
* Token Bankroll Functions:
* - execute
*
* Player Functions:
* - finish
*
* Bankroll Controller / Owner Functions:
* - pauseGame
* - resumeGame
* - set resolver percentage
* - set controller address
*
* Player/Token Bankroll Functions:
* - resolvePendingBets
*/
contract ZethrGame {
using SafeMath for uint;
using SafeMath for uint56;
// Default events:
event Result (address player, uint amountWagered, int amountOffset);
event Wager (address player, uint amount, bytes data);
// Queue of pending/unresolved bets
address[] pendingBetsQueue;
uint queueHead = 0;
uint queueTail = 0;
// Store each player's latest bet via mapping
mapping(address => BetBase) bets;
// Bet structures must start with this layout
struct BetBase {
// Must contain these in this order
uint56 tokenValue; // Multiply by 1e14 to get tokens
uint48 blockNumber;
uint8 tier;
// Game specific structures can add more after this
}
// Mapping of addresses to their *position* in the queue
// Zero = they aren't in the queue
mapping(address => uint) pendingBetsMapping;
// Holds the bankroll controller info
ZethrBankrollControllerInterface controller;
// Is the game paused?
bool paused;
// Minimum bet should always be >= 1
uint minBet = 1e18;
// Percentage that a resolver gets when he resolves bets for the house
uint resolverPercentage;
// Every game has a name
string gameName;
constructor (address _controllerAddress, uint _resolverPercentage, string _name) public {
controller = ZethrBankrollControllerInterface(_controllerAddress);
resolverPercentage = _resolverPercentage;
gameName = _name;
}
/** @dev Gets the max profit of this game as decided by the token bankroll
* @return uint The maximum profit
*/
function getMaxProfit()
public view
returns (uint)
{
return ZethrTokenBankrollInterface(msg.sender).getMaxProfit(address(this));
}
/** @dev Pauses the game, preventing anyone from placing bets
*/
function ownerPauseGame()
public
ownerOnly
{
paused = true;
}
/** @dev Resumes the game, allowing bets
*/
function ownerResumeGame()
public
ownerOnly
{
paused = false;
}
/** @dev Sets the percentage of the bets that a resolver gets when resolving tokens.
* @param _percentage The percentage as x/1,000,000 that the resolver gets
*/
function ownerSetResolverPercentage(uint _percentage)
public
ownerOnly
{
require(_percentage <= 1000000);
resolverPercentage = _percentage;
}
/** @dev Sets the address of the game controller
* @param _controllerAddress The new address of the controller
*/
function ownerSetControllerAddress(address _controllerAddress)
public
ownerOnly
{
controller = ZethrBankrollControllerInterface(_controllerAddress);
}
// Every game should have a name
/** @dev Sets the name of the game
* @param _name The name of the game
*/
function ownerSetGameName(string _name)
ownerOnly
public
{
gameName = _name;
}
/** @dev Gets the game name
* @return The name of the game
*/
function getGameName()
public view
returns (string)
{
return gameName;
}
/** @dev Resolve expired bets in the queue. Gives a percentage of the house edge to the resolver as ZTH
* @param _numToResolve The number of bets to resolve.
* @return tokensEarned The number of tokens earned
* @return queueHead The new head of the queue
*/
function resolveExpiredBets(uint _numToResolve)
public
returns (uint tokensEarned_, uint queueHead_)
{
uint mQueue = queueHead;
uint head;
uint tail = (mQueue + _numToResolve) > pendingBetsQueue.length ? pendingBetsQueue.length : (mQueue + _numToResolve);
uint tokensEarned = 0;
for (head = mQueue; head < tail; head++) {
// Check the head of the queue to see if there is a resolvable bet
// This means the bet at the queue head is older than 255 blocks AND is not 0
// (However, if the address at the head is null, skip it, it's already been resolved)
if (pendingBetsQueue[head] == address(0x0)) {
continue;
}
if (bets[pendingBetsQueue[head]].blockNumber != 0 && block.number > 256 + bets[pendingBetsQueue[head]].blockNumber) {
// Resolve the bet
// finishBetfrom returns the *player* profit
// this will be negative if the player lost and the house won
// so flip it to get the house profit, if any
int sum = - finishBetFrom(pendingBetsQueue[head]);
// Tokens earned is a percentage of the loss
if (sum > 0) {
tokensEarned += (uint(sum).mul(resolverPercentage)).div(1000000);
}
// Queue-tail is always the "next" open spot, so queue head and tail will never overlap
} else {
// If we can't resolve a bet, stop going down the queue
break;
}
}
queueHead = head;
// Send the earned tokens to the resolver
if (tokensEarned >= 1e14) {
controller.gamePayoutResolver(msg.sender, tokensEarned);
}
return (tokensEarned, head);
}
/** @dev Finishes the bet of the sender, if it exists.
* @return int The total profit (positive or negative) earned by the sender
*/
function finishBet()
public
hasNotBetThisBlock(msg.sender)
returns (int)
{
return finishBetFrom(msg.sender);
}
/** @dev Resturns a random number
* @param _blockn The block number to base the random number off of
* @param _entropy Data to use in the random generation
* @param _index Data to use in the random generation
* @return randomNumber The random number to return
*/
function maxRandom(uint _blockn, address _entropy, uint _index)
private view
returns (uint256 randomNumber)
{
return uint256(keccak256(
abi.encodePacked(
blockhash(_blockn),
_entropy,
_index
)));
}
/** @dev Returns a random number
* @param _upper The upper end of the range, exclusive
* @param _blockn The block number to use for the random number
* @param _entropy An address to be used for entropy
* @param _index A number to get the next random number
* @return randomNumber The random number
*/
function random(uint256 _upper, uint256 _blockn, address _entropy, uint _index)
internal view
returns (uint256 randomNumber)
{
return maxRandom(_blockn, _entropy, _index) % _upper;
}
// Prevents the user from placing two bets in one block
modifier hasNotBetThisBlock(address _sender)
{
require(bets[_sender].blockNumber != block.number);
_;
}
// Requires that msg.sender is one of the token bankrolls
modifier bankrollOnly {
require(controller.isTokenBankroll(msg.sender));
_;
}
// Requires that the game is not paused
modifier isNotPaused {
require(!paused);
_;
}
// Requires that the bet given has max profit low enough
modifier betIsValid(uint _betSize, uint _tier, bytes _data) {
uint divRate = ZethrTierLibrary.getDivRate(_tier);
require(isBetValid(_betSize, divRate, _data));
_;
}
// Only an owner can call this method (controller is always an owner)
modifier ownerOnly()
{
require(msg.sender == address(controller) || controller.multiSigWallet().isOwner(msg.sender));
_;
}
/** @dev Places a bet. Callable only by token bankrolls
* @param _player The player that is placing the bet
* @param _tokenCount The total number of tokens bet
* @param _divRate The dividend rate of the player
* @param _data The game-specific data, encoded in bytes-form
*/
function execute(address _player, uint _tokenCount, uint _divRate, bytes _data) public;
/** @dev Resolves the bet of the supplied player.
* @param _playerAddress The address of the player whos bet we are resolving
* @return int The total profit the player earned, positive or negative
*/
function finishBetFrom(address _playerAddress) internal returns (int);
/** @dev Determines if a supplied bet is valid
* @param _tokenCount The total number of tokens bet
* @param _divRate The dividend rate of the bet
* @param _data The game-specific bet data
* @return bool Whether or not the bet is valid
*/
function isBetValid(uint _tokenCount, uint _divRate, bytes _data) public view returns (bool);
}
// File: contracts/Games/ZethrDice.sol
/* The actual game contract.
*
* This contract contains the actual game logic,
* including placing bets (execute), resolving bets,
* and resolving expired bets.
*/
contract ZethrDice is ZethrGame {
/****************************
* GAME SPECIFIC
****************************/
// Slots-specific bet structure
struct Bet {
// Must contain these in this order
uint56 tokenValue;
uint48 blockNumber;
uint8 tier;
// Game specific
uint8 rollUnder;
uint8 numRolls;
}
/****************************
* FIELDS
****************************/
uint constant private MAX_INT = 2 ** 256 - 1;
uint constant public maxProfitDivisor = 1000000;
uint constant public maxNumber = 100;
uint constant public minNumber = 2;
uint constant public houseEdgeDivisor = 1000;
uint constant public houseEdge = 990;
uint constant public minBet = 1e18;
/****************************
* CONSTRUCTOR
****************************/
constructor (address _controllerAddress, uint _resolverPercentage, string _name)
ZethrGame(_controllerAddress, _resolverPercentage, _name)
public
{
}
/****************************
* USER METHODS
****************************/
/** @dev Retrieve the results of the last roll of a player, for web3 calls.
* @param _playerAddress The address of the player
*/
function getLastRollOutput(address _playerAddress)
public view
returns (uint winAmount, uint lossAmount, uint[] memory output)
{
// Cast to Bet and read from storage
Bet storage playerBetInStorage = getBet(_playerAddress);
Bet memory playerBet = playerBetInStorage;
// Safety check
require(playerBet.blockNumber != 0);
(winAmount, lossAmount, output) = getRollOutput(playerBet.blockNumber, playerBet.rollUnder, playerBet.numRolls, playerBet.tokenValue.mul(1e14), _playerAddress);
return (winAmount, lossAmount, output);
}
event RollResult(
uint _blockNumber,
address _target,
uint _rollUnder,
uint _numRolls,
uint _tokenValue,
uint _winAmount,
uint _lossAmount,
uint[] _output
);
/** @dev Retrieve the results of the spin, for web3 calls.
* @param _blockNumber The block number of the spin
* @param _numRolls The number of rolls of this bet
* @param _tokenValue The total number of tokens bet
* @param _target The address of the better
* @return winAmount The total number of tokens won
* @return lossAmount The total number of tokens lost
* @return output An array of all of the results of a multispin
*/
function getRollOutput(uint _blockNumber, uint8 _rollUnder, uint8 _numRolls, uint _tokenValue, address _target)
public
returns (uint winAmount, uint lossAmount, uint[] memory output)
{
output = new uint[](_numRolls);
// Where the result sections start and stop
// If current block for the first spin is older than 255 blocks, ALL rolls are losses
if (block.number - _blockNumber > 255) {
lossAmount = _tokenValue.mul(_numRolls);
} else {
uint profit = calculateProfit(_tokenValue, _rollUnder);
for (uint i = 0; i < _numRolls; i++) {
// Store the output
output[i] = random(100, _blockNumber, _target, i) + 1;
if (output[i] < _rollUnder) {
// Player has won!
winAmount += profit + _tokenValue;
} else {
lossAmount += _tokenValue;
}
}
}
emit RollResult(_blockNumber, _target, _rollUnder, _numRolls, _tokenValue, winAmount, lossAmount, output);
return (winAmount, lossAmount, output);
}
/** @dev Retrieve the results of the roll, for contract calls.
* @param _blockNumber The block number of the roll
* @param _numRolls The number of rolls of this bet
* @param _rollUnder The number the roll has to be under to win
* @param _tokenValue The total number of tokens bet
* @param _target The address of the better
* @return winAmount The total number of tokens won
* @return lossAmount The total number of tokens lost
*/
function getRollResults(uint _blockNumber, uint8 _rollUnder, uint8 _numRolls, uint _tokenValue, address _target)
public
returns (uint winAmount, uint lossAmount)
{
// If current block for the first spin is older than 255 blocks, ALL rolls are losses
if (block.number - _blockNumber > 255) {
lossAmount = _tokenValue.mul(_numRolls);
} else {
uint profit = calculateProfit(_tokenValue, _rollUnder);
for (uint i = 0; i < _numRolls; i++) {
// Store the output
uint output = random(100, _blockNumber, _target, i) + 1;
if (output < _rollUnder) {
winAmount += profit + _tokenValue;
} else {
lossAmount += _tokenValue;
}
}
}
return (winAmount, lossAmount);
}
/****************************
* OWNER METHODS
****************************/
/****************************
* INTERNALS
****************************/
// Calculate the maximum potential profit
function calculateProfit(uint _initBet, uint _roll)
internal view
returns (uint)
{
return ((((_initBet * (100 - (_roll.sub(1)))) / (_roll.sub(1)) + _initBet)) * houseEdge / houseEdgeDivisor) - _initBet;
}
/** @dev Returs the bet struct of a player
* @param _playerAddress The address of the player
* @return Bet The bet of the player
*/
function getBet(address _playerAddress)
internal view
returns (Bet storage)
{
// Cast BetBase to Bet
BetBase storage betBase = bets[_playerAddress];
Bet storage playerBet;
assembly {
// tmp is pushed onto stack and points to betBase slot in storage
let tmp := betBase_slot
// swap1 swaps tmp and playerBet pointers
swap1
}
// tmp is popped off the stack
// playerBet now points to betBase
return playerBet;
}
/****************************
* OVERRIDDEN METHODS
****************************/
/** @dev Resolves the bet of the supplied player.
* @param _playerAddress The address of the player whos bet we are resolving
* @return totalProfit The total profit the player earned, positive or negative
*/
function finishBetFrom(address _playerAddress)
internal
returns (int /*totalProfit*/)
{
// Memory vars to hold data as we compute it
uint winAmount;
uint lossAmount;
// Cast to Bet and read from storage
Bet storage playerBetInStorage = getBet(_playerAddress);
Bet memory playerBet = playerBetInStorage;
// Safety check
require(playerBet.blockNumber != 0);
playerBetInStorage.blockNumber = 0;
// Iterate over the number of rolls and calculate totals:
// - player win amount
// - bankroll win amount
(winAmount, lossAmount) = getRollResults(playerBet.blockNumber, playerBet.rollUnder, playerBet.numRolls, playerBet.tokenValue.mul(1e14), _playerAddress);
// Figure out the token bankroll address
address tokenBankrollAddress = controller.getTokenBankrollAddressFromTier(playerBet.tier);
ZethrTokenBankrollInterface bankroll = ZethrTokenBankrollInterface(tokenBankrollAddress);
// Call into the bankroll to do some token accounting
bankroll.gameTokenResolution(winAmount, _playerAddress, 0, address(0x0), playerBet.tokenValue.mul(1e14).mul(playerBet.numRolls));
// Grab the position of the player in the pending bets queue
uint index = pendingBetsMapping[_playerAddress];
// Remove the player from the pending bets queue by setting the address to 0x0
pendingBetsQueue[index] = address(0x0);
// Delete the player's bet by setting the mapping to zero
pendingBetsMapping[_playerAddress] = 0;
emit Result(_playerAddress, playerBet.tokenValue.mul(1e14), int(winAmount) - int(lossAmount));
// Return all bet results + total *player* profit
return (int(winAmount) - int(lossAmount));
}
/** @dev Places a bet. Callable only by token bankrolls
* @param _player The player that is placing the bet
* @param _tokenCount The total number of tokens bet
* @param _tier The div rate tier the player falls in
* @param _data The game-specific data, encoded in bytes-form
*/
function execute(address _player, uint _tokenCount, uint _tier, bytes _data)
isNotPaused
bankrollOnly
betIsValid(_tokenCount, _tier, _data)
hasNotBetThisBlock(_player)
public
{
Bet storage playerBet = getBet(_player);
// Check for a player bet and resolve if necessary
if (playerBet.blockNumber != 0) {
finishBetFrom(_player);
}
uint8 rolls = uint8(_data[0]);
uint8 rollUnder = uint8(_data[1]);
// Set bet information
playerBet.tokenValue = uint56(_tokenCount.div(rolls).div(1e14));
playerBet.blockNumber = uint48(block.number);
playerBet.tier = uint8(_tier);
playerBet.rollUnder = rollUnder;
playerBet.numRolls = rolls;
// Add player to the pending bets queue
pendingBetsQueue.length ++;
pendingBetsQueue[queueTail] = _player;
queueTail++;
// Add the player's position in the queue to the pending bets mapping
pendingBetsMapping[_player] = queueTail - 1;
// Emit event
emit Wager(_player, _tokenCount, _data);
}
/** @dev Determines if a supplied bet is valid
* @param _tokenCount The total number of tokens bet
* @param _data The game-specific bet data
* @return bool Whether or not the bet is valid
*/
function isBetValid(uint _tokenCount, uint /*_divRate*/, bytes _data)
public view
returns (bool)
{
uint8 rollUnder = uint8(_data[1]);
return (calculateProfit(_tokenCount, rollUnder) < getMaxProfit()
&& _tokenCount >= minBet
&& rollUnder >= minNumber
&& rollUnder <= maxNumber);
}
}
|
Allows an owner to revoke a confirmation for a transaction. transactionId Transaction ID.
|
function revokeConfirmation(uint transactionId)
public
ownerExists(msg.sender)
confirmed(transactionId, msg.sender)
notExecuted(transactionId)
{
confirmations[transactionId][msg.sender] = false;
emit Revocation(msg.sender, transactionId);
}
| 404,808 |
pragma solidity ^0.5.0;
contract GgwpToken {
//ERC-20 Token Standard: function name() public view returns (string)
string public name = "GGWP Token";
//ERC-20 Token Standard: function symbol() public view returns (string)
string public symbol = "GGWP";
//ERC-20 Token Standard: function decimals() public view returns (uint8)
uint8 public decimals = 8;
uint256 public totalGGWP;
address private admin;
event Transfer(
address indexed _ggFrom,
address indexed _ggTo,
uint256 _value
);
event Approval(
address indexed _ggGranter,
address indexed _ggBenefactor,
uint256 _value
);
//ERC-20 Token Standard: function balanceOf(address _owner) public view returns (uint256 balance)
mapping(address => uint256) public balanceOf;
//ERC-20 Token Standard: function allowance(address _owner, address _spender) public view returns (uint256 remaining)
mapping(address => mapping(address => uint256)) public allowance;
constructor(uint256 _initialSupply) public {
admin = msg.sender;
balanceOf[admin] = _initialSupply;
totalGGWP = _initialSupply;
}
//ERC-20 Token Standard: function totalSupply() public view returns (uint256)
function totalSupply() public view returns (uint256) {
return totalGGWP;
}
//ERC-20 Token Standard: function transfer(address _to, uint256 _value) public returns (bool success)
function transfer(address _to, uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] -= _value;
balanceOf[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
}
//ERC-20 Token Standard: function approve(address _spender, uint256 _value) public returns (bool success)
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
//ERC-20 Token Standard: function transferFrom(address _from, address _to, uint256 _value) public returns (bool success)
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= balanceOf[_from]);
require(_value <= allowance[_from][msg.sender]);
balanceOf[_from] -= _value;
balanceOf[_to] += _value;
allowance[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
}
//custom implementation
function grant(uint256 _value) public returns (bool success) {
require(balanceOf[admin] >= _value);
balanceOf[admin] -= _value;
balanceOf[msg.sender] += _value;
emit Transfer(admin, msg.sender, _value);
return true;
}
}
|
ERC-20 Token Standard: function approve(address _spender, uint256 _value) public returns (bool success)
|
function approve(address _spender, uint256 _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
| 1,783,866 |
// SPDX-License-Identifier: BUSL-1.1
pragma solidity 0.8.9;
import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "./libraries/DSMath.sol";
import "./interfaces/IPriceOracleGetter.sol";
import "./interfaces/IMasterPlatypusV3.sol";
import "./interfaces/IMARKET.sol";
import "./Asset.sol";
import "./pool/Core.sol";
import "./interfaces/IPool.sol";
// import "./MasterPlatypusV3.sol";
// import "./MARKET.sol";
/**
* @title Pool
* @notice Manages deposits, withdrawals and swaps. Holds a mapping of assets and parameters.
* @dev The main entry-point of Platypus protocol
*
* Note The Pool is ownable and the owner wields power.
* Note The ownership will be transferred to a governance contract once Platypus community can show to govern itself.
*
* The unique features of the Platypus make it an important subject in the study of evolutionary biology.
*/
contract Pool is
Initializable,
OwnableUpgradeable,
ReentrancyGuardUpgradeable,
PausableUpgradeable,
Core,
IPool
{
using DSMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20Upgradeable for IERC20Upgradeable;
/// @notice Asset Map struct holds assets
struct AssetMap {
address[] keys;
mapping(address => Asset) values;
mapping(address => uint256) indexOf;
mapping(address => bool) inserted;
}
/// @notice Wei in 1 ether
uint256 private constant ETH_UNIT = 10**18;
/// @notice Slippage parameters K, N, C1 and xThreshold
uint256 private _slippageParamK;
uint256 private _slippageParamN;
uint256 private _c1;
uint256 private _xThreshold;
/// @notice Haircut rate
uint256 private _haircutRate;
/// @notice Retention ratio
uint256 private _retentionRatio;
/// @notice Maximum price deviation
/// @dev states the maximum price deviation allowed between assets
uint256 private _maxPriceDeviation;
/// @notice Dev address
address private _dev;
/// @notice The price oracle interface used in swaps
IPriceOracleGetter private _priceOracle;
/// @notice A record of assets inside Pool
AssetMap private _assets;
IMasterPlatypusV3 private _masterPlatypus;
IMARKET private _ptp;
uint256 private _sCoinPerMARKET = 200; // 100 times: 200 means 2: 2 Dais = 1 MARKET
/// @notice An event emitted when an asset is added to Pool
event AssetAdded(address indexed token, address indexed asset);
/// @notice An event emitted when a deposit is made to Pool
event Deposit(
address indexed sender,
address token,
uint256 amount,
uint256 liquidity,
address indexed to
);
/// @notice An event emitted when a withdrawal is made from Pool
event Withdraw(
address indexed sender,
address token,
uint256 amount,
uint256 liquidity,
address indexed to
);
/// @notice An event emitted when dev is updated
event DevUpdated(address indexed previousDev, address indexed newDev);
event MasterPlatypusV3Updated(
address indexed sender,
address prevM,
address indexed newM
);
event ScoinPerMARKETUpdated(
address indexed sender,
uint256 prevRate,
uint256 newRate
);
event PTPV2Updated(
address indexed sender,
address indexed preP,
address indexed newP
);
/// @notice An event emitted when oracle is updated
event OracleUpdated(
address indexed previousOracle,
address indexed newOracle
);
/// @notice An event emitted when price deviation is updated
event PriceDeviationUpdated(
uint256 previousPriceDeviation,
uint256 newPriceDeviation
);
/// @notice An event emitted when slippage params are updated
event SlippageParamsUpdated(
uint256 previousK,
uint256 newK,
uint256 previousN,
uint256 newN,
uint256 previousC1,
uint256 newC1,
uint256 previousXThreshold,
uint256 newXThreshold
);
/// @notice An event emitted when haircut is updated
event HaircutRateUpdated(uint256 previousHaircut, uint256 newHaircut);
/// @notice An event emitted when retention ratio is updated
event RetentionRatioUpdated(
uint256 previousRetentionRatio,
uint256 newRetentionRatio
);
/// @notice An event emitted when a swap is made in Pool
event Swap(
address indexed sender,
address fromToken,
address toToken,
uint256 fromAmount,
uint256 toAmount,
address indexed to
);
/// @dev Modifier ensuring that certain function can only be called by developer
modifier onlyDev() {
require(_dev == msg.sender, "FORBIDDEN");
_;
}
/// @dev Modifier ensuring a certain deadline for a function to complete execution
modifier ensure(uint256 deadline) {
require(deadline >= block.timestamp, "EXPIRED");
_;
}
/**
* @notice Initializes pool. Dev is set to be the account calling this function.
*/
function initialize() external initializer {
__Ownable_init();
__ReentrancyGuard_init_unchained();
__Pausable_init_unchained();
// set variables
_slippageParamK = 0.00002e18; //2 * 10**13 == 0.00002 * WETH
_slippageParamN = 7; // 7
_c1 = 376927610599998308; // ((k**(1/(n+1))) / (n**((n)/(n+1)))) + (k*n)**(1/(n+1))
_xThreshold = 329811659274998519; // (k*n)**(1/(n+1))
_haircutRate = 0.0004e18; // 4 * 10**14 == 0.0004 == 0.04% for intra-aggregate account swap
_retentionRatio = ETH_UNIT; // 1
_maxPriceDeviation = 2e28;
// set dev
_dev = msg.sender;
}
// Getters //
function getMasterPlatypusV3() external view returns (address) {
return address(_masterPlatypus);
}
function getScoinPerMARKET() external view returns (uint256) {
return _sCoinPerMARKET;
}
function getPTPV2() external view returns (address) {
return address(_ptp);
}
/**
* @notice Gets current Dev address
* @return The current Dev address for Pool
*/
function getDev() external view returns (address) {
return _dev;
}
/**
* @notice Gets current Price Oracle address
* @return The current Price Oracle address for Pool
*/
function getPriceOracle() external view returns (address) {
return address(_priceOracle);
}
/**
* @notice Gets current C1 slippage parameter
* @return The current C1 slippage parameter in Pool
*/
function getC1() external view returns (uint256) {
return _c1;
}
/**
* @notice Gets current XThreshold slippage parameter
* @return The current XThreshold slippage parameter in Pool
*/
function getXThreshold() external view returns (uint256) {
return _xThreshold;
}
/**
* @notice Gets current K slippage parameter
* @return The current K slippage parameter in Pool
*/
function getSlippageParamK() external view returns (uint256) {
return _slippageParamK;
}
/**
* @notice Gets current N slippage parameter
* @return The current N slippage parameter in Pool
*/
function getSlippageParamN() external view returns (uint256) {
return _slippageParamN;
}
/**
* @notice Gets current Haircut parameter
* @return The current Haircut parameter in Pool
*/
function getHaircutRate() external view returns (uint256) {
return _haircutRate;
}
/**
* @notice Gets current retention ratio parameter
* @return The current retention ratio parameter in Pool
*/
function getRetentionRatio() external view returns (uint256) {
return _retentionRatio;
}
/**
* @notice Gets current maxPriceDeviation parameter
* @return The current _maxPriceDeviation parameter in Pool
*/
function getMaxPriceDeviation() external view returns (uint256) {
return _maxPriceDeviation;
}
/**
* @dev pause pool, restricting certain operations
*/
function pause() external onlyDev {
_pause();
}
/**
* @dev unpause pool, enabling certain operations
*/
function unpause() external onlyDev {
_unpause();
}
// Setters //
/**
* @notice Changes the contract dev. Can only be set by the contract owner.
* @param dev new contract dev address
*/
function setDev(address dev) external onlyOwner {
require(dev != address(0), "ZERO");
emit DevUpdated(_dev, dev);
_dev = dev;
}
function setMasterPlatypusV3(IMasterPlatypusV3 mv) external onlyOwner {
require(address(mv) != address(0), "ZERO");
emit MasterPlatypusV3Updated(
msg.sender,
address(_masterPlatypus),
address(mv)
);
_masterPlatypus = mv;
}
function setScoinPerMARKET(uint256 rate) external onlyOwner {
require(rate > 0, "UNDER_ZERO");
emit ScoinPerMARKETUpdated(msg.sender, _sCoinPerMARKET, rate);
_sCoinPerMARKET = rate;
}
function setPTPV2(IMARKET newP) external onlyOwner {
require(address(newP) != address(0), "ZERO");
emit PTPV2Updated(msg.sender, address(_ptp), address(newP));
_ptp = newP;
}
/**
* @notice Changes the pools slippage params. Can only be set by the contract owner.
* @param k_ new pool's slippage param K
* @param n_ new pool's slippage param N
* @param c1_ new pool's slippage param C1
* @param xThreshold_ new pool's slippage param xThreshold
*/
function setSlippageParams(
uint256 k_,
uint256 n_,
uint256 c1_,
uint256 xThreshold_
) external onlyOwner {
require(k_ <= ETH_UNIT); // k should not be set bigger than 1
require(n_ > 0); // n should be bigger than 0
emit SlippageParamsUpdated(
_slippageParamK,
k_,
_slippageParamN,
n_,
_c1,
c1_,
_xThreshold,
xThreshold_
);
_slippageParamK = k_;
_slippageParamN = n_;
_c1 = c1_;
_xThreshold = xThreshold_;
}
/**
* @notice Changes the pools haircutRate. Can only be set by the contract owner.
* @param haircutRate_ new pool's haircutRate_
*/
function setHaircutRate(uint256 haircutRate_) external onlyOwner {
require(haircutRate_ <= ETH_UNIT); // haircutRate_ should not be set bigger than 1
emit HaircutRateUpdated(_haircutRate, haircutRate_);
_haircutRate = haircutRate_;
}
/**
* @notice Changes the pools retentionRatio. Can only be set by the contract owner.
* @param retentionRatio_ new pool's retentionRatio
*/
function setRetentionRatio(uint256 retentionRatio_) external onlyOwner {
require(retentionRatio_ <= ETH_UNIT); // retentionRatio_ should not be set bigger than 1
emit RetentionRatioUpdated(_retentionRatio, retentionRatio_);
_retentionRatio = retentionRatio_;
}
/**
* @notice Changes the pools maxPriceDeviation. Can only be set by the contract owner.
* @param maxPriceDeviation_ new pool's maxPriceDeviation
*/
function setMaxPriceDeviation(uint256 maxPriceDeviation_)
external
onlyOwner
{
require(maxPriceDeviation_ <= ETH_UNIT); // maxPriceDeviation_ should not be set bigger than 1
emit PriceDeviationUpdated(_maxPriceDeviation, maxPriceDeviation_);
_maxPriceDeviation = maxPriceDeviation_;
}
/**
* @notice Changes the pools priceOracle. Can only be set by the contract owner.
* @param priceOracle new pool's priceOracle addres
*/
function setPriceOracle(address priceOracle) external onlyOwner {
require(priceOracle != address(0), "ZERO");
emit OracleUpdated(address(_priceOracle), priceOracle);
_priceOracle = IPriceOracleGetter(priceOracle);
}
// Asset struct functions //
/**
* @notice Gets asset with token address key
* @param key The address of token
* @return the corresponding asset in state
*/
function _getAsset(address key) private view returns (Asset) {
return _assets.values[key];
}
/**
* @notice Gets key (address) at index
* @param index the index
* @return the key of index
*/
function _getKeyAtIndex(uint256 index) private view returns (address) {
return _assets.keys[index];
}
/**
* @notice get length of asset list
* @return the size of the asset list
*/
function _sizeOfAssetList() private view returns (uint256) {
return _assets.keys.length;
}
/**
* @notice Looks if the asset is contained by the list
* @param key The address of token to look for
* @return bool true if the asset is in asset list, false otherwise
*/
function _containsAsset(address key) private view returns (bool) {
return _assets.inserted[key];
}
/**
* @notice Adds asset to the list
* @param key The address of token to look for
* @param val The asset to add
*/
function _addAsset(address key, Asset val) private {
if (_assets.inserted[key]) {
_assets.values[key] = val;
} else {
_assets.inserted[key] = true;
_assets.values[key] = val;
_assets.indexOf[key] = _assets.keys.length;
_assets.keys.push(key);
}
}
/**
* @notice Removes asset from asset struct
* @dev Can only be called by owner
* @param key The address of token to remove
*/
function removeAsset(address key) external onlyOwner {
if (!_assets.inserted[key]) {
return;
}
delete _assets.inserted[key];
delete _assets.values[key];
uint256 index = _assets.indexOf[key];
uint256 lastIndex = _assets.keys.length - 1;
address lastKey = _assets.keys[lastIndex];
_assets.indexOf[lastKey] = index;
delete _assets.indexOf[key];
_assets.keys[index] = lastKey;
_assets.keys.pop();
}
// Pool Functions //
/**
* @notice Checks deviation is not higher than specified amount
* @dev Reverts if deviation is higher than _maxPriceDeviation
* @param tokenA First token
* @param tokenB Second token
*/
function _checkPriceDeviation(address tokenA, address tokenB) private view {
uint256 tokenAPrice = _priceOracle.getAssetPrice(tokenA);
uint256 tokenBPrice = _priceOracle.getAssetPrice(tokenB);
// check if prices respect their maximum deviation for a > b : (a - b) / a < maxDeviation
if (tokenBPrice > tokenAPrice) {
require(
(((tokenBPrice - tokenAPrice) * ETH_UNIT) / tokenBPrice) <=
_maxPriceDeviation,
"PRICE_DEV"
);
} else {
require(
(((tokenAPrice - tokenBPrice) * ETH_UNIT) / tokenAPrice) <=
_maxPriceDeviation,
"PRICE_DEV"
);
}
}
/**
* @notice gets system equilibrium coverage ratio
* @dev [ sum of Ai * fi / sum Li * fi ]
* @return equilibriumCoverageRatio system equilibrium coverage ratio
*/
function getEquilibriumCoverageRatio() private view returns (uint256) {
uint256 totalCash = 0;
uint256 totalLiability = 0;
// loop on assets
for (uint256 i = 0; i < _sizeOfAssetList(); i++) {
// get token address
address assetAddress = _getKeyAtIndex(i);
// get token oracle price
uint256 tokenPrice = _priceOracle.getAssetPrice(assetAddress);
// used to convert cash and liabilities into ETH_UNIT to have equal decimals accross all assets
uint256 offset = 10**(18 - _getAsset(assetAddress).decimals());
totalCash += (_getAsset(assetAddress).cash() * offset * tokenPrice);
totalLiability += (_getAsset(assetAddress).liability() *
offset *
tokenPrice);
}
// if there are no liabilities or no assets in the pool, return equilibrium state = 1
if (totalLiability == 0 || totalCash == 0) {
return ETH_UNIT;
}
return totalCash.wdiv(totalLiability);
}
/**
* @notice Adds asset to pool, reverts if asset already exists in pool
* @param token The address of token
* @param asset The address of the platypus Asset contract
*/
function addAsset(address token, address asset) external onlyOwner {
require(token != address(0), "ZERO");
require(asset != address(0), "ZERO");
require(!_containsAsset(token), "ASSET_EXISTS");
_addAsset(token, Asset(asset));
emit AssetAdded(token, asset);
}
/**
* @notice Gets Asset corresponding to ERC20 token. Reverts if asset does not exists in Pool.
* @param token The address of ERC20 token
*/
function _assetOf(address token) private view returns (Asset) {
require(_containsAsset(token), "ASSET_NOT_EXIST");
return _getAsset(token);
}
/**
* @notice Gets Asset corresponding to ERC20 token. Reverts if asset does not exists in Pool.
* @dev to be used externally
* @param token The address of ERC20 token
*/
function assetOf(address token) external view override returns (address) {
return address(_assetOf(token));
}
/**
* @notice Deposits asset in Pool
* @param asset The asset to be deposited
* @param amount The amount to be deposited
* @param to The user accountable for deposit, receiving the platypus assets (lp)
* @return liquidity Total asset liquidity minted
*/
function _deposit(
Asset asset,
uint256 amount,
address to
) private returns (uint256 liquidity) {
uint256 totalSupply = asset.totalSupply();
uint256 liability = asset.liability();
uint256 fee = _depositFee(
_slippageParamK,
_slippageParamN,
_c1,
_xThreshold,
asset.cash(),
liability,
amount
);
// Calculate amount of LP to mint : ( deposit - fee ) * TotalAssetSupply / Liability
if (liability == 0) {
liquidity = amount - fee;
} else {
liquidity = ((amount - fee) * totalSupply) / liability;
}
// get equilibrium coverage ratio
uint256 eqCov = getEquilibriumCoverageRatio();
// apply impairment gain if eqCov < 1
if (eqCov < ETH_UNIT) {
liquidity = liquidity.wdiv(eqCov);
}
require(liquidity > 0, "INSUFFICIENT_LIQ_MINT");
asset.addCash(amount);
asset.addLiability(amount - fee);
asset.mint(to, liquidity);
}
/**
* @notice Deposits amount of tokens into pool ensuring deadline
* @dev Asset needs to be created and added to pool before any operation
* @param token The token address to be deposited
* @param amount The amount to be deposited
* @param to The user accountable for deposit, receiving the platypus assets (lp)
* @param deadline The deadline to be respected
* @return liquidity Total asset liquidity minted
*/
function deposit(
address token,
uint256 amount,
address to,
uint256 deadline
)
external
override
ensure(deadline)
nonReentrant
whenNotPaused
returns (uint256 liquidity)
{
require(amount > 0, "ZERO_AMOUNT");
require(token != address(0), "ZERO");
require(to != address(0), "ZERO");
IERC20 erc20 = IERC20(token);
Asset asset = _assetOf(token);
erc20.safeTransferFrom(address(msg.sender), address(asset), amount);
liquidity = _deposit(asset, amount, to);
emit Deposit(msg.sender, token, amount, liquidity, to);
}
function _innerDeposit(
address token,
uint256 amount,
address to
) private whenNotPaused returns (uint256 liquidity) {
require(amount > 0, "ZERO_AMOUNT");
require(token != address(0), "ZERO");
require(to != address(0), "ZERO");
IERC20 erc20 = IERC20(token);
Asset asset = _assetOf(token);
erc20.safeTransferFrom(to, address(asset), amount);
liquidity = _deposit(asset, amount, to);
emit Deposit(to, token, amount, liquidity, to);
}
function investProc(
address token1,
address token2,
address token3,
uint256 amount1,
uint256 amount2,
uint256 amount3,
uint256 investPercent,
address from
) private returns (uint256 MARKETAmount) {
uint256 investAmount1 = (amount1 * investPercent) / 100 / 100;
uint256 investAmount2 = (amount2 * investPercent) / 100 / 100;
uint256 investAmount3 = (amount3 * investPercent) / 100 / 100;
if (amount1 > 0)
IERC20(token1).safeTransferFrom(
from,
address(_assetOf(token1)),
investAmount1
);
if (amount2 > 0)
IERC20(token2).safeTransferFrom(
from,
address(_assetOf(token2)),
investAmount2
);
if (amount3 > 0)
IERC20(token3).safeTransferFrom(
from,
address(_assetOf(token3)),
investAmount3
);
MARKETAmount =
(((investAmount1 * 10**_ptp.decimals()) /
10**ERC20(token1).decimals() +
(investAmount2 * 10**_ptp.decimals()) /
10**ERC20(token2).decimals() +
(investAmount3 * 10**_ptp.decimals()) /
10**ERC20(token3).decimals()) / _sCoinPerMARKET) *
100;
_ptp.transferFromWithoutFee(address(_ptp), msg.sender, MARKETAmount);
}
struct TokensParam {
address token1;
address token2;
address token3;
}
struct AmountsParam {
uint256 amount1;
uint256 amount2;
uint256 amount3;
}
struct ActualToAmountParam {
uint256 actualToAmount12;
uint256 actualToAmount13;
uint256 actualToAmount21;
uint256 actualToAmount23;
uint256 actualToAmount31;
uint256 actualToAmount32;
}
function swapProc(
TokensParam memory token,
AmountsParam memory amount,
address to
) private returns (ActualToAmountParam memory actualToAmount) {
uint256 tAPR1 = _masterPlatypus.totalAPR(0, to); // 10**18 times (fUSDT)
uint256 tAPR2 = _masterPlatypus.totalAPR(1, to); // 10**18 times (DAI)
uint256 tAPR3 = _masterPlatypus.totalAPR(2, to); // 10**18 times (USDC)
uint256 sumAPR = tAPR1 + tAPR2 + tAPR3;
require (sumAPR > 0, 'swapProc: APR is Zero');
if (amount.amount1 > 0) {
(actualToAmount.actualToAmount12, ) = _innerSwap(
token.token1,
token.token2,
(amount.amount1 * tAPR2) / sumAPR,
0,
to
);
(actualToAmount.actualToAmount13, ) = _innerSwap(
token.token1,
token.token3,
(amount.amount1 * tAPR3) / sumAPR,
0,
to
);
}
if (amount.amount2 > 0) {
(actualToAmount.actualToAmount21, ) = _innerSwap(
token.token2,
token.token1,
(amount.amount2 * tAPR1) / sumAPR,
0,
to
);
(actualToAmount.actualToAmount23, ) = _innerSwap(
token.token2,
token.token3,
(amount.amount2 * tAPR3) / sumAPR,
0,
to
);
}
if (amount.amount3 > 0) {
(actualToAmount.actualToAmount31, ) = _innerSwap(
token.token3,
token.token1,
(amount.amount3 * tAPR1) / sumAPR,
0,
to
);
(actualToAmount.actualToAmount32, ) = _innerSwap(
token.token3,
token.token2,
(amount.amount3 * tAPR2) / sumAPR,
0,
to
);
}
}
function calcDepositsAmount(
AmountsParam memory amount,
ActualToAmountParam memory actualToAmount,
address user
)
private
view
returns (
uint256 a1,
uint256 a2,
uint256 a3
)
{
uint256 tAPR1 = _masterPlatypus.totalAPR(0, user); // 10**18 times (USDT)
uint256 tAPR2 = _masterPlatypus.totalAPR(1, user); // 10**18 times (DAI)
uint256 tAPR3 = _masterPlatypus.totalAPR(2, user); // 10**18 times (USDC)
uint256 sumAPR = tAPR1 + tAPR2 + tAPR3;
require (sumAPR > 0, 'calcDepositsAmount: APR is Zero');
// final deposit amounts to each pool
a1 =
(amount.amount1 * tAPR1) /
sumAPR +
actualToAmount.actualToAmount21 +
actualToAmount.actualToAmount31;
a2 =
(amount.amount2 * tAPR2) /
sumAPR +
actualToAmount.actualToAmount12 +
actualToAmount.actualToAmount32;
a3 =
(amount.amount3 * tAPR3) /
sumAPR +
actualToAmount.actualToAmount13 +
actualToAmount.actualToAmount23;
}
function depositProc(
TokensParam memory token,
AmountsParam memory amount,
ActualToAmountParam memory actualToAmount,
address to
) private returns (AmountsParam memory liquidities) {
(uint256 a1, uint256 a2, uint256 a3) = calcDepositsAmount(
amount,
actualToAmount,
to
);
AmountsParam memory newAmount = AmountsParam(a1, a2, a3);
liquidities = _depositProc(token, newAmount, to);
}
function _depositProc(
TokensParam memory token,
AmountsParam memory amount,
address to
) private returns (AmountsParam memory liquidities) {
uint256 liquidity1;
uint256 liquidity2;
uint256 liquidity3;
if (amount.amount1 > 0) {
liquidity1 = _innerDeposit(token.token1, amount.amount1, to);
}
if (amount.amount2 > 0) {
liquidity2 = _innerDeposit(token.token2, amount.amount2, to);
}
if (amount.amount3 > 0) {
liquidity3 = _innerDeposit(token.token3, amount.amount3, to);
}
liquidities = AmountsParam(liquidity1, liquidity2, liquidity3);
}
function autoStaking(AmountsParam memory lpAmounts, uint256 marketAmount, uint256 autoBalancePeriod)
private
{
if (marketAmount > 0)
_masterPlatypus.stakingPTPFromOther(msg.sender, marketAmount);
if (lpAmounts.amount1 > 0)
_masterPlatypus.stakingLPFromOther(
msg.sender,
0,
lpAmounts.amount1,
autoBalancePeriod
);
if (lpAmounts.amount2 > 0)
_masterPlatypus.stakingLPFromOther(
msg.sender,
1,
lpAmounts.amount2,
autoBalancePeriod
);
if (lpAmounts.amount3 > 0)
_masterPlatypus.stakingLPFromOther(
msg.sender,
2,
lpAmounts.amount3,
autoBalancePeriod
);
}
function depositAuto(
address token1,
address token2,
address token3,
uint256 amount1,
uint256 amount2,
uint256 amount3,
bool isAutoAllocation,
uint256 investPercent, // 100 times: 1500 means 15 percent, 0.15
uint256 autoBalancePeriod // 0- not auto balance, unit: second
) external whenNotPaused {
require(amount1 > 0 || amount2 > 0 || amount3 > 0, "ZERO_AMOUNT");
require(
token1 != address(0) ||
token2 != address(0) ||
token3 != address(0),
"ZERO_ADDRESS"
);
require(
address(_ptp) != address(0),
"depositAuto: _ptp is ZERO_ADDRESS"
);
require(
address(_masterPlatypus) != address(0),
"depositAuto: _masterPlatypus is ZERO_ADDRESS"
);
AmountsParam memory liquidities;
TokensParam memory tokens = TokensParam(token1, token2, token3);
uint256 marketAmount;
if (investPercent > 0) {
marketAmount = investProc(
token1,
token2,
token3,
amount1,
amount2,
amount3,
investPercent,
address(msg.sender)
);
} else {
if (!isAutoAllocation) {
AmountsParam memory deAmounts = AmountsParam(
amount1,
amount2,
amount3
);
liquidities = _depositProc(
tokens,
deAmounts,
address(msg.sender)
);
}
}
if (isAutoAllocation) {
uint256 investAmount1 = (amount1 * investPercent) / 100 / 100;
uint256 investAmount2 = (amount2 * investPercent) / 100 / 100;
uint256 investAmount3 = (amount3 * investPercent) / 100 / 100;
AmountsParam memory amounts = AmountsParam(
amount1 - investAmount1,
amount2 - investAmount2,
amount3 - investAmount3
);
ActualToAmountParam memory actualToAmount = swapProc(
tokens,
amounts,
address(msg.sender)
);
liquidities = depositProc(
tokens,
amounts,
actualToAmount,
address(msg.sender)
);
}
autoStaking(liquidities, marketAmount, autoBalancePeriod);
}
/**
* @notice Calculates fee and liability to burn in case of withdrawal
* @param asset The asset willing to be withdrawn
* @param liquidity The liquidity willing to be withdrawn
* @return amount Total amount to be withdrawn from Pool
* @return liabilityToBurn Total liability to be burned by Pool
* @return fee The fee of the withdraw operation
*/
function _withdrawFrom(Asset asset, uint256 liquidity)
private
view
returns (
uint256 amount,
uint256 liabilityToBurn,
uint256 fee,
bool enoughCash
)
{
liabilityToBurn = (asset.liability() * liquidity) / asset.totalSupply();
require(liabilityToBurn > 0, "INSUFFICIENT_LIQ_BURN");
fee = _withdrawalFee(
_slippageParamK,
_slippageParamN,
_c1,
_xThreshold,
asset.cash(),
asset.liability(),
liabilityToBurn
);
// Get equilibrium coverage ratio before withdraw
uint256 eqCov = getEquilibriumCoverageRatio();
// Init enoughCash to true
enoughCash = true;
// Apply impairment in the case eqCov < 1
uint256 amountAfterImpairment;
if (eqCov < ETH_UNIT) {
amountAfterImpairment = (liabilityToBurn).wmul(eqCov);
} else {
amountAfterImpairment = liabilityToBurn;
}
// Prevent underflow in case withdrawal fees >= liabilityToBurn, user would only burn his underlying liability
if (amountAfterImpairment > fee) {
amount = amountAfterImpairment - fee;
// If not enough cash
if (asset.cash() < amount) {
amount = asset.cash(); // When asset does not contain enough cash, just withdraw the remaining cash
fee = 0;
enoughCash = false;
}
} else {
fee = amountAfterImpairment; // fee overcomes the amount to withdraw. User would be just burning liability
amount = 0;
enoughCash = false;
}
}
/**
* @notice Withdraws liquidity amount of asset to `to` address ensuring minimum amount required
* @param asset The asset to be withdrawn
* @param liquidity The liquidity to be withdrawn
* @param minimumAmount The minimum amount that will be accepted by user
* @param to The user receiving the withdrawal
* @return amount The total amount withdrawn
*/
function _withdraw(
Asset asset,
uint256 liquidity,
uint256 minimumAmount,
address to
) private returns (uint256 amount) {
// calculate liabilityToBurn and Fee
uint256 liabilityToBurn;
(amount, liabilityToBurn, , ) = _withdrawFrom(asset, liquidity);
require(minimumAmount <= amount, "AMOUNT_TOO_LOW");
asset.burn(msg.sender, liquidity);
asset.removeCash(amount);
asset.removeLiability(liabilityToBurn);
asset.transferUnderlyingToken(to, amount);
}
/**
* @notice Withdraws liquidity amount of asset to `to` address ensuring minimum amount required
* @param token The token to be withdrawn
* @param liquidity The liquidity to be withdrawn
* @param minimumAmount The minimum amount that will be accepted by user
* @param to The user receiving the withdrawal
* @param deadline The deadline to be respected
* @return amount The total amount withdrawn
*/
function withdraw(
address token,
uint256 liquidity,
uint256 minimumAmount,
address to,
uint256 deadline
)
external
override
ensure(deadline)
nonReentrant
whenNotPaused
returns (uint256 amount)
{
require(liquidity > 0, "ZERO_ASSET_AMOUNT");
require(token != address(0), "ZERO");
require(to != address(0), "ZERO");
Asset asset = _assetOf(token);
amount = _withdraw(asset, liquidity, minimumAmount, to);
emit Withdraw(msg.sender, token, amount, liquidity, to);
}
/**
* @notice Swap fromToken for toToken, ensures deadline and minimumToAmount and sends quoted amount to `to` address
* @param fromToken The token being inserted into Pool by user for swap
* @param toToken The token wanted by user, leaving the Pool
* @param fromAmount The amount of from token inserted
* @param minimumToAmount The minimum amount that will be accepted by user as result
* @param to The user receiving the result of swap
* @param deadline The deadline to be respected
* @return actualToAmount The actual amount user receive
* @return haircut The haircut that would be applied
*/
function swap(
address fromToken,
address toToken,
uint256 fromAmount,
uint256 minimumToAmount,
address to,
uint256 deadline
)
external
override
ensure(deadline)
nonReentrant
whenNotPaused
returns (uint256 actualToAmount, uint256 haircut)
{
require(fromToken != address(0), "ZERO");
require(toToken != address(0), "ZERO");
require(fromToken != toToken, "SAME_ADDRESS");
require(fromAmount > 0, "ZERO_FROM_AMOUNT");
require(to != address(0), "ZERO");
IERC20 fromERC20 = IERC20(fromToken);
Asset fromAsset = _assetOf(fromToken);
Asset toAsset = _assetOf(toToken);
// Intrapool swapping only
require(
toAsset.aggregateAccount() == fromAsset.aggregateAccount(),
"DIFF_AGG_ACC"
);
(actualToAmount, haircut) = _quoteFrom(fromAsset, toAsset, fromAmount);
require(minimumToAmount <= actualToAmount, "AMOUNT_TOO_LOW");
fromERC20.safeTransferFrom(
address(msg.sender),
address(fromAsset),
fromAmount
);
fromAsset.addCash(fromAmount);
toAsset.removeCash(actualToAmount);
toAsset.addLiability(_dividend(haircut, _retentionRatio));
toAsset.transferUnderlyingToken(to, actualToAmount);
emit Swap(
msg.sender,
fromToken,
toToken,
fromAmount,
actualToAmount,
to
);
}
function _innerSwap(
address fromToken,
address toToken,
uint256 fromAmount,
uint256 minimumToAmount,
address to
) private whenNotPaused returns (uint256 actualToAmount, uint256 haircut) {
require(fromToken != address(0), "ZERO");
require(toToken != address(0), "ZERO");
require(fromToken != toToken, "SAME_ADDRESS");
require(fromAmount > 0, "ZERO_FROM_AMOUNT");
IERC20 fromERC20 = IERC20(fromToken);
Asset fromAsset = _assetOf(fromToken);
Asset toAsset = _assetOf(toToken);
// Intrapool swapping only
require(
toAsset.aggregateAccount() == fromAsset.aggregateAccount(),
"DIFF_AGG_ACC"
);
(actualToAmount, haircut) = _quoteFrom(fromAsset, toAsset, fromAmount);
require(minimumToAmount <= actualToAmount, "AMOUNT_TOO_LOW");
fromERC20.safeTransferFrom(to, address(fromAsset), fromAmount);
fromAsset.addCash(fromAmount);
toAsset.removeCash(actualToAmount);
toAsset.addLiability(_dividend(haircut, _retentionRatio));
toAsset.transferUnderlyingToken(to, actualToAmount);
}
/**
* @notice Swap fromToken for toToken, ensures deadline and minimumToAmount and sends quoted amount to `to` address
* @param fromToken The token being inserted into Pool by user for swap
* @param toToken The token wanted by user, leaving the Pool
* @param fromAmount The amount of from token inserted
* @param minimumToAmount The minimum amount that will be accepted by user as result
* @param to The user receiving the result of swap
* @param deadline The deadline to be respected
* @return actualToAmount The actual amount user receive
* @return haircut The haircut that would be applied
*/
function swapBasedPrice(
address fromToken,
address toToken,
uint256 fromAmount,
uint256 minimumToAmount,
address to,
uint256 deadline
)
external
ensure(deadline)
returns (uint256 actualToAmount, uint256 haircut)
{
require(fromToken != address(0), "ZERO");
require(toToken != address(0), "ZERO");
require(fromToken != toToken, "SAME_ADDRESS");
require(fromAmount > 0, "ZERO_FROM_AMOUNT");
require(to != address(0), "ZERO");
IERC20 fromERC20 = IERC20(fromToken);
Asset fromAsset = _assetOf(fromToken);
Asset toAsset = _assetOf(toToken);
// Intrapool swapping only
require(
toAsset.aggregateAccount() == fromAsset.aggregateAccount(),
"DIFF_AGG_ACC"
);
(actualToAmount, haircut) = _quoteFromBasedPrice(
fromToken,
toToken,
fromAsset,
toAsset,
fromAmount
);
require(minimumToAmount <= actualToAmount, "AMOUNT_TOO_LOW");
fromERC20.safeTransferFrom(
address(msg.sender),
address(fromAsset),
fromAmount
);
fromAsset.addCash(fromAmount);
toAsset.removeCash(actualToAmount);
toAsset.addLiability(_dividend(haircut, _retentionRatio));
toAsset.transferUnderlyingToken(to, actualToAmount);
emit Swap(
msg.sender,
fromToken,
toToken,
fromAmount,
actualToAmount,
to
);
}
/**
* @notice Quotes the actual amount user would receive in a swap, taking in account slippage and haircut
* @param fromAsset The initial asset
* @param toAsset The asset wanted by user
* @param fromAmount The amount to quote
* @return actualToAmount The actual amount user would receive
* @return haircut The haircut that will be applied
*/
function _quoteFromBasedPrice(
address fromToken,
address toToken,
Asset fromAsset,
Asset toAsset,
uint256 fromAmount
) private view returns (uint256 actualToAmount, uint256 haircut) {
uint256 idealToAmount = _quoteIdealToAmount(
fromAsset,
toAsset,
fromAmount
);
uint256 fromPrice = _priceOracle.getAssetPrice(fromToken);
uint256 toPrice = _priceOracle.getAssetPrice(toToken);
uint256 toAmount = (idealToAmount * fromPrice) / toPrice;
haircut = _haircut(toAmount, _haircutRate);
actualToAmount = toAmount - haircut;
}
/**
* @notice Quotes the actual amount user would receive in a swap, taking in account slippage and haircut
* @param fromAsset The initial asset
* @param toAsset The asset wanted by user
* @param fromAmount The amount to quote
* @return actualToAmount The actual amount user would receive
* @return haircut The haircut that will be applied
*/
function _quoteFrom(
Asset fromAsset,
Asset toAsset,
uint256 fromAmount
) private view returns (uint256 actualToAmount, uint256 haircut) {
uint256 idealToAmount = _quoteIdealToAmount(
fromAsset,
toAsset,
fromAmount
);
require(toAsset.cash() >= idealToAmount, "INSUFFICIENT_CASH");
uint256 slippageFrom = _slippage(
_slippageParamK,
_slippageParamN,
_c1,
_xThreshold,
fromAsset.cash(),
fromAsset.liability(),
fromAmount,
true
);
uint256 slippageTo = _slippage(
_slippageParamK,
_slippageParamN,
_c1,
_xThreshold,
toAsset.cash(),
toAsset.liability(),
idealToAmount,
false
);
uint256 swappingSlippage = _swappingSlippage(slippageFrom, slippageTo);
uint256 toAmount = idealToAmount.wmul(swappingSlippage);
haircut = _haircut(toAmount, _haircutRate);
actualToAmount = toAmount - haircut;
}
/**
* @notice Quotes the ideal amount in case of swap
* @dev Does not take into account slippage parameters nor haircut
* @param fromAsset The initial asset
* @param toAsset The asset wanted by user
* @param fromAmount The amount to quote
* @return idealToAmount The ideal amount user would receive
*/
function _quoteIdealToAmount(
Asset fromAsset,
Asset toAsset,
uint256 fromAmount
) private view returns (uint256 idealToAmount) {
// check deviation is not higher than specified amount
_checkPriceDeviation(
fromAsset.underlyingToken(),
toAsset.underlyingToken()
);
// assume perfect peg between assets
idealToAmount = ((fromAmount * 10**toAsset.decimals()) /
10**fromAsset.decimals());
}
/**
* @notice Quotes potential outcome of a swap given current state, taking in account slippage and haircut
* @dev To be used by frontend
* @param fromToken The initial ERC20 token
* @param toToken The token wanted by user
* @param fromAmount The amount to quote
* @return potentialOutcome The potential amount user would receive
* @return haircut The haircut that would be applied
*/
function quotePotentialSwap(
address fromToken,
address toToken,
uint256 fromAmount
)
external
view
override
whenNotPaused
returns (uint256 potentialOutcome, uint256 haircut)
{
require(fromToken != address(0), "ZERO");
require(toToken != address(0), "ZERO");
require(fromToken != toToken, "SAME_ADDRESS");
require(fromAmount > 0, "ZERO_FROM_AMOUNT");
Asset fromAsset = _assetOf(fromToken);
Asset toAsset = _assetOf(toToken);
// Intrapool swapping only
require(
toAsset.aggregateAccount() == fromAsset.aggregateAccount(),
"DIFF_AGG_ACC"
);
(potentialOutcome, haircut) = _quoteFromBasedPrice(
fromToken,
toToken,
fromAsset,
toAsset,
fromAmount
);
}
/**
* @notice Quotes potential withdrawal from pool
* @dev To be used by frontend
* @param token The token to be withdrawn by user
* @param liquidity The liquidity (amount of lp assets) to be withdrawn
* @return amount The potential amount user would receive
* @return fee The fee that would be applied
* @return enoughCash does the pool have enough cash? (cash >= liabilityToBurn - fee)
*/
function quotePotentialWithdraw(address token, uint256 liquidity)
external
view
override
whenNotPaused
returns (
uint256 amount,
uint256 fee,
bool enoughCash
)
{
require(token != address(0), "ZERO");
require(liquidity > 0, "LIQ=0");
Asset asset = _assetOf(token);
(amount, , fee, enoughCash) = _withdrawFrom(asset, liquidity);
}
/**
* @notice Gets addresses of underlying token in pool
* @dev To be used externally
* @return addresses of assets in the pool
*/
function getTokenAddresses()
external
view
override
returns (address[] memory)
{
return _assets.keys;
}
}
|
Deposits asset in Pool asset The asset to be deposited amount The amount to be deposited to The user accountable for deposit, receiving the platypus assets (lp) return liquidity Total asset liquidity minted/ Calculate amount of LP to mint : ( deposit - fee ) TotalAssetSupply / Liability apply impairment gain if eqCov < 1
|
function _deposit(
Asset asset,
uint256 amount,
address to
) private returns (uint256 liquidity) {
uint256 totalSupply = asset.totalSupply();
uint256 liability = asset.liability();
uint256 fee = _depositFee(
_slippageParamK,
_slippageParamN,
_c1,
_xThreshold,
asset.cash(),
liability,
amount
);
if (liability == 0) {
liquidity = amount - fee;
liquidity = ((amount - fee) * totalSupply) / liability;
}
if (eqCov < ETH_UNIT) {
liquidity = liquidity.wdiv(eqCov);
}
require(liquidity > 0, "INSUFFICIENT_LIQ_MINT");
asset.addCash(amount);
asset.addLiability(amount - fee);
asset.mint(to, liquidity);
}
| 1,776,280 |
./partial_match/3/0xB13d958Cdc0c97169eAB4e44f8B6800001ec232B/sources/Token.sol
|
withdraw tokens if unsold
|
function withdrawTokens() public{
require(now > stopTime);
ERC20 erc20 = ERC20(address(this));
erc20.transfer(owner, balanceOf[address(this)]);
}
| 5,053,576 |
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
pragma abicoder v2;
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "../presets/OwnablePausableUpgradeable.sol";
import "../interfaces/IStakedEthToken.sol";
import "../interfaces/IDepositContract.sol";
import "../interfaces/IPoolValidators.sol";
import "../interfaces/IPool.sol";
import "../interfaces/IPoolValidators.sol";
/**
* @title Pool
*
* @dev Pool contract accumulates deposits from the users, mints tokens and registers validators.
*/
contract Pool is IPool, OwnablePausableUpgradeable {
using SafeMathUpgradeable for uint256;
// @dev Validator deposit amount.
uint256 public constant override VALIDATOR_TOTAL_DEPOSIT = 32 ether;
// @dev Validator initialization amount.
uint256 public constant override VALIDATOR_INIT_DEPOSIT = 1 ether;
// @dev Total activated validators.
uint256 public override activatedValidators;
// @dev Pool validator withdrawal credentials.
bytes32 public override withdrawalCredentials;
// @dev Address of the ETH2 Deposit Contract (deployed by Ethereum).
IDepositContract public override validatorRegistration;
// @dev Address of the StakedEthToken contract.
IStakedEthToken private stakedEthToken;
// @dev Address of the PoolValidators contract.
IPoolValidators private validators;
// @dev Address of the Oracles contract.
address private oracles;
// @dev Maps senders to the validator index that it will be activated in.
mapping(address => mapping(uint256 => uint256)) public override activations;
// @dev Total pending validators.
uint256 public override pendingValidators;
// @dev Amount of deposited ETH that is not considered for the activation period.
uint256 public override minActivatingDeposit;
// @dev Pending validators percent limit. If it's not exceeded tokens can be minted immediately.
uint256 public override pendingValidatorsLimit;
/**
* @dev See {IPool-upgrade}.
*/
function upgrade(address _poolValidators, address _oracles) external override onlyAdmin whenPaused {
require(
_poolValidators != address(0) && address(validators) == 0xaAc73D4A26Ae6906aa115118b7840b1F19fcd3A5,
"Pool: invalid PoolValidators address"
);
require(
_oracles != address(0) && address(oracles) == 0x2f1C5E86B13a74f5A6E7B4b35DD77fe29Aa47514,
"Pool: invalid Oracles address"
);
// set contract addresses
validators = IPoolValidators(_poolValidators);
oracles = _oracles;
}
/**
* @dev See {IPool-setMinActivatingDeposit}.
*/
function setMinActivatingDeposit(uint256 newMinActivatingDeposit) external override onlyAdmin {
minActivatingDeposit = newMinActivatingDeposit;
emit MinActivatingDepositUpdated(newMinActivatingDeposit, msg.sender);
}
/**
* @dev See {IPool-setPendingValidatorsLimit}.
*/
function setPendingValidatorsLimit(uint256 newPendingValidatorsLimit) external override onlyAdmin {
require(newPendingValidatorsLimit < 1e4, "Pool: invalid limit");
pendingValidatorsLimit = newPendingValidatorsLimit;
emit PendingValidatorsLimitUpdated(newPendingValidatorsLimit, msg.sender);
}
/**
* @dev See {IPool-setActivatedValidators}.
*/
function setActivatedValidators(uint256 newActivatedValidators) external override {
require(msg.sender == oracles || hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "Pool: access denied");
// subtract activated validators from pending validators
pendingValidators = pendingValidators.sub(newActivatedValidators.sub(activatedValidators));
activatedValidators = newActivatedValidators;
emit ActivatedValidatorsUpdated(newActivatedValidators, msg.sender);
}
/**
* @dev See {IPool-stake}.
*/
function stake() external payable override {
_stake(msg.sender, msg.value);
}
/**
* @dev See {IPool-stakeOnBehalf}.
*/
function stakeOnBehalf(address recipient) external payable override {
_stake(recipient, msg.value);
}
/**
* @dev Function for staking ETH using transfer.
*/
receive() external payable {
_stake(msg.sender, msg.value);
}
/**
* @dev See {IPool-stakeWithPartner}.
*/
function stakeWithPartner(address partner) external payable override {
// stake amount
_stake(msg.sender, msg.value);
emit StakedWithPartner(partner, msg.value);
}
/**
* @dev See {IPool-stakeWithPartnerOnBehalf}.
*/
function stakeWithPartnerOnBehalf(address partner, address recipient) external payable override {
// stake amount
_stake(recipient, msg.value);
emit StakedWithPartner(partner, msg.value);
}
/**
* @dev See {IPool-stakeWithReferrer}.
*/
function stakeWithReferrer(address referrer) external payable override {
// stake amount
_stake(msg.sender, msg.value);
emit StakedWithReferrer(referrer, msg.value);
}
/**
* @dev See {IPool-stakeWithReferrerOnBehalf}.
*/
function stakeWithReferrerOnBehalf(address referrer, address recipient) external payable override {
// stake amount
_stake(recipient, msg.value);
emit StakedWithReferrer(referrer, msg.value);
}
function _stake(address recipient, uint256 value) internal whenNotPaused {
require(recipient != address(0), "Pool: invalid recipient");
require(value > 0, "Pool: invalid deposit amount");
// mint tokens for small deposits immediately
if (value <= minActivatingDeposit) {
stakedEthToken.mint(recipient, value);
return;
}
// mint tokens if current pending validators limit is not exceed
uint256 _pendingValidators = pendingValidators.add((address(this).balance).div(VALIDATOR_TOTAL_DEPOSIT));
uint256 _activatedValidators = activatedValidators; // gas savings
uint256 validatorIndex = _activatedValidators.add(_pendingValidators);
if (validatorIndex.mul(1e4) <= _activatedValidators.mul(pendingValidatorsLimit.add(1e4))) {
stakedEthToken.mint(recipient, value);
} else {
// lock deposit amount until validator activated
activations[recipient][validatorIndex] = activations[recipient][validatorIndex].add(value);
emit ActivationScheduled(recipient, validatorIndex, value);
}
}
/**
* @dev See {IPool-canActivate}.
*/
function canActivate(uint256 validatorIndex) external view override returns (bool) {
return validatorIndex.mul(1e4) <= activatedValidators.mul(pendingValidatorsLimit.add(1e4));
}
/**
* @dev See {IPool-activate}.
*/
function activate(address account, uint256 validatorIndex) external override {
uint256 activatedAmount = _activateAmount(
account,
validatorIndex,
activatedValidators.mul(pendingValidatorsLimit.add(1e4))
);
stakedEthToken.mint(account, activatedAmount);
}
/**
* @dev See {IPool-activateMultiple}.
*/
function activateMultiple(address account, uint256[] calldata validatorIndexes) external override {
uint256 toMint;
uint256 maxValidatorIndex = activatedValidators.mul(pendingValidatorsLimit.add(1e4));
for (uint256 i = 0; i < validatorIndexes.length; i++) {
uint256 activatedAmount = _activateAmount(account, validatorIndexes[i], maxValidatorIndex);
toMint = toMint.add(activatedAmount);
}
stakedEthToken.mint(account, toMint);
}
function _activateAmount(
address account,
uint256 validatorIndex,
uint256 maxValidatorIndex
)
internal whenNotPaused returns (uint256 amount)
{
require(validatorIndex.mul(1e4) <= maxValidatorIndex, "Pool: validator is not active yet");
amount = activations[account][validatorIndex];
require(amount > 0, "Pool: invalid validator index");
delete activations[account][validatorIndex];
emit Activated(account, validatorIndex, amount, msg.sender);
}
/**
* @dev See {IPool-initializeValidator}.
*/
function initializeValidator(IPoolValidators.DepositData calldata depositData) external override whenNotPaused {
require(msg.sender == address(validators), "Pool: access denied");
require(depositData.withdrawalCredentials == withdrawalCredentials, "Pool: invalid withdrawal credentials");
emit ValidatorInitialized(depositData.publicKey, depositData.operator);
// initiate validator registration
validatorRegistration.deposit{value : VALIDATOR_INIT_DEPOSIT}(
depositData.publicKey,
abi.encodePacked(depositData.withdrawalCredentials),
depositData.signature,
depositData.depositDataRoot
);
}
/**
* @dev See {IPool-finalizeValidator}.
*/
function finalizeValidator(IPoolValidators.DepositData calldata depositData) external override whenNotPaused {
require(msg.sender == address(validators), "Pool: access denied");
require(depositData.withdrawalCredentials == withdrawalCredentials, "Pool: invalid withdrawal credentials");
// update number of pending validators
pendingValidators = pendingValidators.add(1);
emit ValidatorRegistered(depositData.publicKey, depositData.operator);
// finalize validator registration
validatorRegistration.deposit{value : VALIDATOR_TOTAL_DEPOSIT.sub(VALIDATOR_INIT_DEPOSIT)}(
depositData.publicKey,
abi.encodePacked(depositData.withdrawalCredentials),
depositData.signature,
depositData.depositDataRoot
);
}
/**
* @dev See {IPool-refund}.
*/
function refund() external override payable {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender) || msg.sender == address(validators), "Pool: access denied");
require(msg.value > 0, "Pool: invalid refund amount");
emit Refunded(msg.sender, msg.value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "../interfaces/IOwnablePausable.sol";
/**
* @title OwnablePausableUpgradeable
*
* @dev Bundles Access Control, Pausable and Upgradeable contracts in one.
*
*/
abstract contract OwnablePausableUpgradeable is IOwnablePausable, PausableUpgradeable, AccessControlUpgradeable {
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
/**
* @dev Modifier for checking whether the caller is an admin.
*/
modifier onlyAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "OwnablePausable: access denied");
_;
}
/**
* @dev Modifier for checking whether the caller is a pauser.
*/
modifier onlyPauser() {
require(hasRole(PAUSER_ROLE, msg.sender), "OwnablePausable: access denied");
_;
}
// solhint-disable-next-line func-name-mixedcase
function __OwnablePausableUpgradeable_init(address _admin) internal initializer {
__Context_init_unchained();
__AccessControl_init_unchained();
__Pausable_init_unchained();
__OwnablePausableUpgradeable_init_unchained(_admin);
}
/**
* @dev Grants `DEFAULT_ADMIN_ROLE`, `PAUSER_ROLE` to the admin account.
*/
// solhint-disable-next-line func-name-mixedcase
function __OwnablePausableUpgradeable_init_unchained(address _admin) internal initializer {
_setupRole(DEFAULT_ADMIN_ROLE, _admin);
_setupRole(PAUSER_ROLE, _admin);
}
/**
* @dev See {IOwnablePausable-isAdmin}.
*/
function isAdmin(address _account) external override view returns (bool) {
return hasRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-addAdmin}.
*/
function addAdmin(address _account) external override {
grantRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-removeAdmin}.
*/
function removeAdmin(address _account) external override {
revokeRole(DEFAULT_ADMIN_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-isPauser}.
*/
function isPauser(address _account) external override view returns (bool) {
return hasRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-addPauser}.
*/
function addPauser(address _account) external override {
grantRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-removePauser}.
*/
function removePauser(address _account) external override {
revokeRole(PAUSER_ROLE, _account);
}
/**
* @dev See {IOwnablePausable-pause}.
*/
function pause() external override onlyPauser {
_pause();
}
/**
* @dev See {IOwnablePausable-unpause}.
*/
function unpause() external override onlyPauser {
_unpause();
}
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
/**
* @dev Interface of the StakedEthToken contract.
*/
interface IStakedEthToken is IERC20Upgradeable {
/**
* @dev Function for retrieving the total deposits amount.
*/
function totalDeposits() external view returns (uint256);
/**
* @dev Function for retrieving the principal amount of the distributor.
*/
function distributorPrincipal() external view returns (uint256);
/**
* @dev Function for toggling rewards for the account.
* @param account - address of the account.
* @param isDisabled - whether to disable account's rewards distribution.
*/
function toggleRewards(address account, bool isDisabled) external;
/**
* @dev Function for creating `amount` tokens and assigning them to `account`.
* Can only be called by Pool contract.
* @param account - address of the account to assign tokens to.
* @param amount - amount of tokens to assign.
*/
function mint(address account, uint256 amount) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
// This interface is designed to be compatible with the Vyper version.
/// @notice This is the Ethereum 2.0 deposit contract interface.
/// For more information see the Phase 0 specification under https://github.com/ethereum/eth2.0-specs
/// https://github.com/ethereum/eth2.0-specs/blob/dev/solidity_deposit_contract/deposit_contract.sol
interface IDepositContract {
/// @notice A processed deposit event.
event DepositEvent(
bytes pubkey,
bytes withdrawal_credentials,
bytes amount,
bytes signature,
bytes index
);
/// @notice Submit a Phase 0 DepositData object.
/// @param pubkey A BLS12-381 public key.
/// @param withdrawal_credentials Commitment to a public key for withdrawals.
/// @param signature A BLS12-381 signature.
/// @param deposit_data_root The SHA-256 hash of the SSZ-encoded DepositData object.
/// Used as a protection against malformed input.
function deposit(
bytes calldata pubkey,
bytes calldata withdrawal_credentials,
bytes calldata signature,
bytes32 deposit_data_root
) external payable;
/// @notice Query the current deposit root hash.
/// @return The deposit root hash.
function get_deposit_root() external view returns (bytes32);
/// @notice Query the current deposit count.
/// @return The deposit count encoded as a little endian 64-bit number.
function get_deposit_count() external view returns (bytes memory);
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
pragma abicoder v2;
/**
* @dev Interface of the PoolValidators contract.
*/
interface IPoolValidators {
/**
* @dev Structure for storing operator data.
* @param initializeMerkleRoot - validators registration initialization merkle root.
* @param finalizeMerkleRoot - validators registration finalization merkle root.
* @param locked - defines whether operator is currently locked.
* @param committed - defines whether operator has committed its readiness to host validators.
*/
struct Operator {
bytes32 initializeMerkleRoot;
bytes32 finalizeMerkleRoot;
bool locked;
bool committed;
}
/**
* @dev Structure for passing information about the validator deposit data.
* @param operator - address of the operator.
* @param withdrawalCredentials - withdrawal credentials used for generating the deposit data.
* @param depositDataRoot - hash tree root of the deposit data, generated by the operator.
* @param publicKey - BLS public key of the validator, generated by the operator.
* @param signature - BLS signature of the validator, generated by the operator.
*/
struct DepositData {
address operator;
bytes32 withdrawalCredentials;
bytes32 depositDataRoot;
bytes publicKey;
bytes signature;
}
/**
* @dev Enum to track status of the validator registration.
* @param Uninitialized - validator has not been initialized.
* @param Initialized - 1 ether deposit has been made to the ETH2 registration contract for the public key.
* @param Finalized - 31 ether deposit has been made to the ETH2 registration contract for the public key.
* @param Failed - 1 ether deposit has failed as it was assigned to the different from the protocol's withdrawal key.
*/
enum ValidatorStatus { Uninitialized, Initialized, Finalized, Failed }
/**
* @dev Event for tracking new operators.
* @param operator - address of the operator.
* @param initializeMerkleRoot - validators initialization merkle root.
* @param initializeMerkleProofs - validators initialization merkle proofs.
* @param finalizeMerkleRoot - validators finalization merkle root.
* @param finalizeMerkleProofs - validators finalization merkle proofs.
*/
event OperatorAdded(
address indexed operator,
bytes32 indexed initializeMerkleRoot,
string initializeMerkleProofs,
bytes32 indexed finalizeMerkleRoot,
string finalizeMerkleProofs
);
/**
* @dev Event for tracking operator's commitments.
* @param operator - address of the operator that expressed its readiness to host validators.
* @param collateral - collateral amount deposited.
*/
event OperatorCommitted(
address indexed operator,
uint256 collateral
);
/**
* @dev Event for tracking operator's collateral withdrawals.
* @param operator - address of the operator.
* @param collateralRecipient - address of the collateral recipient.
* @param collateral - amount withdrawn.
*/
event CollateralWithdrawn(
address indexed operator,
address indexed collateralRecipient,
uint256 collateral
);
/**
* @dev Event for tracking operators' removals.
* @param sender - address of the transaction sender.
* @param operator - address of the operator.
*/
event OperatorRemoved(
address indexed sender,
address indexed operator
);
/**
* @dev Event for tracking operators' slashes.
* @param operator - address of the operator.
* @param publicKey - public key of the slashed validator.
* @param refundedAmount - amount refunded to the pool.
*/
event OperatorSlashed(
address indexed operator,
bytes publicKey,
uint256 refundedAmount
);
/**
* @dev Constructor for initializing the PoolValidators contract.
* @param _admin - address of the contract admin.
* @param _pool - address of the Pool contract.
* @param _oracles - address of the Oracles contract.
*/
function initialize(address _admin, address _pool, address _oracles) external;
/**
* @dev Function for retrieving the operator.
* @param _operator - address of the operator to retrieve the data for.
*/
function getOperator(address _operator) external view returns (bytes32, bytes32, bool);
/**
* @dev Function for retrieving the collateral of the operator.
* @param operator - address of the operator to retrieve the collateral for.
*/
function collaterals(address operator) external view returns (uint256);
/**
* @dev Function for retrieving registration status of the validator.
* @param validatorId - hash of the validator public key to receive the status for.
*/
function validatorStatuses(bytes32 validatorId) external view returns (ValidatorStatus);
/**
* @dev Function for adding new operator.
* @param _operator - address of the operator to add or update.
* @param initializeMerkleRoot - validators initialization merkle root.
* @param initializeMerkleProofs - validators initialization merkle proofs.
* @param finalizeMerkleRoot - validators finalization merkle root.
* @param finalizeMerkleProofs - validators finalization merkle proofs.
*/
function addOperator(
address _operator,
bytes32 initializeMerkleRoot,
string calldata initializeMerkleProofs,
bytes32 finalizeMerkleRoot,
string calldata finalizeMerkleProofs
) external;
/**
* @dev Function for committing operator. If 1 ETH collateral was not deposited yet,
* it must be sent together with the function call. Must be called by the operator address
* specified through the `addOperator` function call.
*/
function commitOperator() external payable;
/**
* @dev Function for withdrawing operator's collateral. Can only be called when the operator was removed.
* @param collateralRecipient - address of the collateral recipient.
*/
function withdrawCollateral(address payable collateralRecipient) external;
/**
* @dev Function for removing operator. Can be called either by operator or admin.
* @param _operator - address of the operator to remove.
*/
function removeOperator(address _operator) external;
/**
* @dev Function for slashing the operator registration.
* @param depositData - deposit data of the validator to slash.
* @param merkleProof - an array of hashes to verify whether the deposit data is part of the initialize merkle root.
*/
function slashOperator(DepositData calldata depositData, bytes32[] calldata merkleProof) external;
/**
* @dev Function for initializing the operator.
* @param depositData - deposit data of the validator to initialize.
* @param merkleProof - an array of hashes to verify whether the deposit data is part of the initialize merkle root.
*/
function initializeValidator(DepositData calldata depositData, bytes32[] calldata merkleProof) external;
/**
* @dev Function for finalizing the operator.
* @param depositData - deposit data of the validator to finalize.
* @param merkleProof - an array of hashes to verify whether the deposit data is part of the finalize merkle root.
*/
function finalizeValidator(DepositData calldata depositData, bytes32[] calldata merkleProof) external;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
pragma abicoder v2;
import "./IDepositContract.sol";
import "./IPoolValidators.sol";
/**
* @dev Interface of the Pool contract.
*/
interface IPool {
/**
* @dev Event for tracking initialized validators.
* @param publicKey - validator public key.
* @param operator - address of the validator operator.
*/
event ValidatorInitialized(bytes publicKey, address operator);
/**
* @dev Event for tracking registered validators.
* @param publicKey - validator public key.
* @param operator - address of the validator operator.
*/
event ValidatorRegistered(bytes publicKey, address operator);
/**
* @dev Event for tracking refunds.
* @param sender - address of the refund sender.
* @param amount - refunded amount.
*/
event Refunded(address indexed sender, uint256 amount);
/**
* @dev Event for tracking scheduled deposit activation.
* @param sender - address of the deposit sender.
* @param validatorIndex - index of the activated validator.
* @param value - deposit amount to be activated.
*/
event ActivationScheduled(address indexed sender, uint256 validatorIndex, uint256 value);
/**
* @dev Event for tracking activated deposits.
* @param account - account the deposit was activated for.
* @param validatorIndex - index of the activated validator.
* @param value - amount activated.
* @param sender - address of the transaction sender.
*/
event Activated(address indexed account, uint256 validatorIndex, uint256 value, address indexed sender);
/**
* @dev Event for tracking activated validators updates.
* @param activatedValidators - new total amount of activated validators.
* @param sender - address of the transaction sender.
*/
event ActivatedValidatorsUpdated(uint256 activatedValidators, address sender);
/**
* @dev Event for tracking updates to the minimal deposit amount considered for the activation period.
* @param minActivatingDeposit - new minimal deposit amount considered for the activation.
* @param sender - address of the transaction sender.
*/
event MinActivatingDepositUpdated(uint256 minActivatingDeposit, address sender);
/**
* @dev Event for tracking pending validators limit.
* When it's exceeded, the deposits will be set for the activation.
* @param pendingValidatorsLimit - pending validators percent limit.
* @param sender - address of the transaction sender.
*/
event PendingValidatorsLimitUpdated(uint256 pendingValidatorsLimit, address sender);
/**
* @dev Event for tracking added deposits with partner.
* @param partner - address of the partner.
* @param amount - the amount added.
*/
event StakedWithPartner(address indexed partner, uint256 amount);
/**
* @dev Event for tracking added deposits with referrer.
* @param referrer - address of the referrer.
* @param amount - the amount added.
*/
event StakedWithReferrer(address indexed referrer, uint256 amount);
/**
* @dev Function for upgrading the Pools contract. The `initialize` function must be defined if deploying contract
* for the first time that will initialize the state variables above.
* @param _poolValidators - address of the PoolValidators contract.
* @param _oracles - address of the Oracles contract.
*/
function upgrade(address _poolValidators, address _oracles) external;
/**
* @dev Function for getting the total validator deposit.
*/
// solhint-disable-next-line func-name-mixedcase
function VALIDATOR_TOTAL_DEPOSIT() external view returns (uint256);
/**
* @dev Function for getting the initial validator deposit.
*/
// solhint-disable-next-line func-name-mixedcase
function VALIDATOR_INIT_DEPOSIT() external view returns (uint256);
/**
* @dev Function for retrieving the total amount of pending validators.
*/
function pendingValidators() external view returns (uint256);
/**
* @dev Function for retrieving the total amount of activated validators.
*/
function activatedValidators() external view returns (uint256);
/**
* @dev Function for retrieving the withdrawal credentials used to
* initiate pool validators withdrawal from the beacon chain.
*/
function withdrawalCredentials() external view returns (bytes32);
/**
* @dev Function for getting the minimal deposit amount considered for the activation.
*/
function minActivatingDeposit() external view returns (uint256);
/**
* @dev Function for getting the pending validators percent limit.
* When it's exceeded, the deposits will be set for the activation.
*/
function pendingValidatorsLimit() external view returns (uint256);
/**
* @dev Function for getting the amount of activating deposits.
* @param account - address of the account to get the amount for.
* @param validatorIndex - index of the activated validator.
*/
function activations(address account, uint256 validatorIndex) external view returns (uint256);
/**
* @dev Function for setting minimal deposit amount considered for the activation period.
* @param newMinActivatingDeposit - new minimal deposit amount considered for the activation.
*/
function setMinActivatingDeposit(uint256 newMinActivatingDeposit) external;
/**
* @dev Function for changing the total amount of activated validators.
* @param newActivatedValidators - new total amount of activated validators.
*/
function setActivatedValidators(uint256 newActivatedValidators) external;
/**
* @dev Function for changing pending validators limit.
* @param newPendingValidatorsLimit - new pending validators limit. When it's exceeded, the deposits will be set for the activation.
*/
function setPendingValidatorsLimit(uint256 newPendingValidatorsLimit) external;
/**
* @dev Function for checking whether validator index can be activated.
* @param validatorIndex - index of the validator to check.
*/
function canActivate(uint256 validatorIndex) external view returns (bool);
/**
* @dev Function for retrieving the validator registration contract address.
*/
function validatorRegistration() external view returns (IDepositContract);
/**
* @dev Function for staking ether to the pool to the different tokens' recipient.
* @param recipient - address of the tokens recipient.
*/
function stakeOnBehalf(address recipient) external payable;
/**
* @dev Function for staking ether to the pool.
*/
function stake() external payable;
/**
* @dev Function for staking ether with the partner that will receive the revenue share from the protocol fee.
* @param partner - address of partner who will get the revenue share.
*/
function stakeWithPartner(address partner) external payable;
/**
* @dev Function for staking ether with the partner that will receive the revenue share from the protocol fee
* and the different tokens' recipient.
* @param partner - address of partner who will get the revenue share.
* @param recipient - address of the tokens recipient.
*/
function stakeWithPartnerOnBehalf(address partner, address recipient) external payable;
/**
* @dev Function for staking ether with the referrer who will receive the one time bonus.
* @param referrer - address of referrer who will get its referral bonus.
*/
function stakeWithReferrer(address referrer) external payable;
/**
* @dev Function for staking ether with the referrer who will receive the one time bonus
* and the different tokens' recipient.
* @param referrer - address of referrer who will get its referral bonus.
* @param recipient - address of the tokens recipient.
*/
function stakeWithReferrerOnBehalf(address referrer, address recipient) external payable;
/**
* @dev Function for minting account's tokens for the specific validator index.
* @param account - account address to activate the tokens for.
* @param validatorIndex - index of the activated validator.
*/
function activate(address account, uint256 validatorIndex) external;
/**
* @dev Function for minting account's tokens for the specific validator indexes.
* @param account - account address to activate the tokens for.
* @param validatorIndexes - list of activated validator indexes.
*/
function activateMultiple(address account, uint256[] calldata validatorIndexes) external;
/**
* @dev Function for initializing new pool validator.
* @param depositData - the deposit data to submit for the validator.
*/
function initializeValidator(IPoolValidators.DepositData calldata depositData) external;
/**
* @dev Function for finalizing new pool validator registration.
* @param depositData - the deposit data to submit for the validator.
*/
function finalizeValidator(IPoolValidators.DepositData calldata depositData) external;
/**
* @dev Function for refunding to the pool.
* Can only be executed by the account with admin role.
*/
function refund() external payable;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/EnumerableSetUpgradeable.sol";
import "../utils/AddressUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, 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;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: AGPL-3.0-only
pragma solidity 0.7.5;
/**
* @dev Interface of the OwnablePausableUpgradeable and OwnablePausable contracts.
*/
interface IOwnablePausable {
/**
* @dev Function for checking whether an account has an admin role.
* @param _account - account to check.
*/
function isAdmin(address _account) external view returns (bool);
/**
* @dev Function for assigning an admin role to the account.
* Can only be called by an account with an admin role.
* @param _account - account to assign an admin role to.
*/
function addAdmin(address _account) external;
/**
* @dev Function for removing an admin role from the account.
* Can only be called by an account with an admin role.
* @param _account - account to remove an admin role from.
*/
function removeAdmin(address _account) external;
/**
* @dev Function for checking whether an account has a pauser role.
* @param _account - account to check.
*/
function isPauser(address _account) external view returns (bool);
/**
* @dev Function for adding a pauser role to the account.
* Can only be called by an account with an admin role.
* @param _account - account to assign a pauser role to.
*/
function addPauser(address _account) external;
/**
* @dev Function for removing a pauser role from the account.
* Can only be called by an account with an admin role.
* @param _account - account to remove a pauser role from.
*/
function removePauser(address _account) external;
/**
* @dev Function for pausing the contract.
*/
function pause() external;
/**
* @dev Function for unpausing the contract.
*/
function unpause() external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @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);
}
|
See {IPool-activateMultiple}./
|
function activateMultiple(address account, uint256[] calldata validatorIndexes) external override {
uint256 toMint;
uint256 maxValidatorIndex = activatedValidators.mul(pendingValidatorsLimit.add(1e4));
for (uint256 i = 0; i < validatorIndexes.length; i++) {
uint256 activatedAmount = _activateAmount(account, validatorIndexes[i], maxValidatorIndex);
toMint = toMint.add(activatedAmount);
}
stakedEthToken.mint(account, toMint);
}
| 13,841,191 |
./full_match/1/0xE155F64B9aD8c81318c313196a60c72e72fD2cD1/sources/ChaintoolsFinal.sol
|
determine traderOne Block Delay [Sandwich/Frontrun Protection]Tax & Final transfer amountsOnly first 10 minutesSniper bots funding lp rewardsif sender is not position manager tax go to contract
|
function _transfer(
address sender,
address recipient,
uint256 amount
) internal returns (bool) {
address trader = sender == uniswapV3Pool ? recipient : sender;
if (sender != uniswapV3Pool && recipient != uniswapV3Pool)
trader = sender;
if (startStamp == 0) {
revert MinMax();
}
if (
trader != address(this) &&
trader != address(YIELD_BOOSTER) &&
trader != address(positionManager) &&
trader != address(YIELD_VAULT)
) {
if (sandwichLock[trader] < block.number) {
sandwichLock[trader] = block.number + 1;
revert Sando();
}
}
if (tokenomicsOn != 0) {
if (amount < 1e8 || amount > 2_000_000e18) revert MinMax();
return _basicTransfer(sender, recipient, amount);
}
sender != uniswapV3Pool &&
sender != address(positionManager) &&
recipient != uniswapV3Pool
) {
if (badPool[recipient]) revert Auth();
return _basicTransfer(sender, recipient, amount);
}
if (
recipient == uniswapV3Pool ||
recipient == address(positionManager) ||
isTaxExcluded[sender] ||
isTaxExcluded[recipient]
) {
return _basicTransfer(sender, recipient, amount);
}
unchecked {
if (sender != uniswapV3Pool) {
}
}
_balances[sender] -= amount;
unchecked {
uint256 tFee = amount / 20;
if (
block.timestamp < startStamp + 10 minutes
) {
tFee *= 2;
}
amount -= tFee;
if (sender != address(positionManager)) {
_balances[address(this)] += tFee;
address ref = upperRef[recipient] != address(0)
? upperRef[recipient]
: multiSig;
uint256 rFee0 = tFee / 5;
_balances[ref] += rFee0;
emit Transfer(recipient, ref, tFee);
tFee -= rFee0;
emit referralPaid(recipient, ref, rFee0);
_balances[address(YIELD_BOOSTER)] += tFee;
}
_balances[recipient] += amount;
}
emit Transfer(sender, recipient, amount);
return true;
}
| 4,971,752 |
./partial_match/4/0x7a7704053B671c0b94ae12f24421F0bB471cA98a/sources/BondlyStaking.sol
|
stake BONDLY _amount is the bondly amount to stake/ require( bondlyToken.balanceOf(_msgSender()) >= _amount, "Not enough balance" );
|
function stake(uint256 _amount) public onlyWhitelisted {
require(isPoolOpen(), "Pool is not open");
require(totalStakes.add(_amount) <= poolSize, "Not enough space");
require(
bondlyToken.transferFrom(_msgSender(), address(this), _amount),
"Stake: BondlyToken.TransferFrom: Failed to Stake!"
);
STAKE_DETAIL storage _stake = stakingBalance[_msgSender()];
if (_stake.total == 0) {
_stake.firstStakedAt = block.timestamp;
}
_stake.total = _stake.total.add(_amount);
_stake.stakes.push(STAKE(block.timestamp, block.timestamp, _amount));
totalStakes = totalStakes.add(_amount);
emit Stake(_msgSender(), _amount);
}
| 8,599,732 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.2;
pragma abicoder v2;
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
/// @title Accessory SVG generator
library Lines1 {
/// @dev Accessory N°1 => Classic
function fortune_1() public pure returns (string[2] memory) {
return ["Ethereum is going", "to 20k"];
}
/// @dev Accessory N°1 => Classic
function fortune_2() public pure returns (string[2] memory) {
return ["Your road to glory will be", "rocky - but fullfilling"] ;
}
/// @dev Accessory N°1 => Classic
function fortune_3() public pure returns (string[2] memory) {
return ["Patience is your ally", "Do not worry!"] ;
}
/// @dev Accessory N°1 => Classic
function fortune_4() public pure returns (string[2] memory) {
return ["Do not worry about money", "best things are in ETH"] ;
}
/// @dev Accessory N°1 => Classic
function fortune_5() public pure returns (string[2] memory) {
return ["Do not pursue happiness", "- create it."] ;
}
/// @dev Accessory N°1 => Classic
function fortune_6() public pure returns (string[2] memory) {
return ["All things are difficult", "before they are easy."] ;
}
/// @dev Accessory N°1 => Classic
function fortune_7() public pure returns (string[2] memory) {
return ["Fear is interest paid on a", "debt you may not owe."] ;
}
/// @dev Accessory N°1 => Classic
function fortune_8() public pure returns (string[2] memory) {
return ["to get the fruit - one", "must climb the tree."] ;
}
/// @dev Accessory N°1 => Classic
function fortune_9() public pure returns (string[2] memory) {
return ["Big journeys begin", "with a single step. "] ;
}
/// @dev Accessory N°1 => Classic
function fortune_10() public pure returns (string[2] memory) {
return ["CPG Club", "to the Moon!"] ;
}
/// @dev Accessory N°1 => Classic
function fortune_11() public pure returns (string[2] memory) {
return ["Salt and sugar", "look the same."] ;
}
/// @dev Accessory N°1 => Classic
function fortune_12() public pure returns (string[2] memory) {
return ["Little by little - ", "one travels far"] ;
}
/// @dev Accessory N°1 => Classic
function fortune_13() public pure returns (string[2] memory) {
return ["Not all those", "who wander are lost."] ;
}
/// @dev Accessory N°1 => Classic
function fortune_14() public pure returns (string[2] memory) {
return ["You are your", "best thing."] ;
}
/// @dev Accessory N°1 => Classic
function fortune_15() public pure returns (string[2] memory) {
return ["Stay hungry.", "Stay foolish."] ;
}
/// @dev Accessory N°1 => Classic
function fortune_16() public pure returns (string[2] memory) {
return ["Try and fail - ", "but never fail to try."] ;
}
/// @dev Accessory N°1 => Classic
function fortune_17() public pure returns (string[2] memory) {
return ["Say yes - ", "then figure it out."] ;
}
/// @dev Accessory N°1 => Classic
function fortune_18() public pure returns (string[2] memory) {
return ["Embrace a ", "new narrative."] ;
}
/// @dev Accessory N°1 => Classic
function fortune_19() public pure returns (string[2] memory) {
return ["Get lost in", "the right direction."] ;
}
/// @dev Accessory N°1 => Classic
function fortune_20() public pure returns (string[2] memory) {
return ["Stop saying yes to things", "you do not want to do."] ;
}
function getFortuneLines(uint rand) public pure returns (string[2] memory ) {
if (rand == 1) {
return fortune_1();
} else if (rand == 2) {
return fortune_2();
} else if (rand == 3) {
return fortune_3();
} else if (rand == 4) {
return fortune_4();
} else if (rand == 5) {
return fortune_5();
} else if (rand == 6) {
return fortune_6();
} else if (rand == 7) {
return fortune_7();
} else if (rand == 8) {
return fortune_8();
} else if (rand == 9) {
return fortune_9();
} else if (rand == 10) {
return fortune_10();
} else if (rand == 11) {
return fortune_11();
} else if (rand == 12) {
return fortune_12();
} else if (rand == 13) {
return fortune_13();
} else if (rand == 14) {
return fortune_14();
} else if (rand == 15) {
return fortune_15();
} else if (rand == 16) {
return fortune_16();
} else if (rand == 17) {
return fortune_17();
} else if (rand == 18) {
return fortune_18();
} else if (rand == 19) {
return fortune_19();
} else if (rand == 20) {
return fortune_20();
} else {
return fortune_1();
}
}
}
|
Accessory N°1 => Classic
|
function fortune_16() public pure returns (string[2] memory) {
return ["Try and fail - ", "but never fail to try."] ;
}
| 13,010,658 |
/**
*Submitted for verification at Etherscan.io on 2020-10-21
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.6;
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol
// Subject to the MIT license.
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "Keep3r::SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint a, uint b) internal pure returns (uint) {
return sub(a, b, "Keep3r::SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b <= a, errorMessage);
uint c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint a, uint b) internal pure returns (uint) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "Keep3r::SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint a, uint b) internal pure returns (uint) {
return div(a, b, "Keep3r::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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint a, uint b) internal pure returns (uint) {
return mod(a, b, "Keep3r::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(uint a, uint b, string memory errorMessage) internal pure returns (uint) {
require(b != 0, errorMessage);
return a % b;
}
}
interface Governance {
function proposeJob(address job) external returns (uint);
}
interface WETH9 {
function deposit() external payable;
function balanceOf(address account) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
}
interface Uniswap {
function factory() 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);
}
interface UniswapPair {
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function balanceOf(address account) external view returns (uint);
function approve(address spender, uint amount) external returns (bool);
function totalSupply() external view returns (uint);
}
interface Factory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
interface Keep3rHelper {
function getQuoteLimit(uint gasUsed) external view returns (uint);
}
contract Keep3r {
using SafeMath for uint;
/// @notice Keep3r Helper to set max prices for the ecosystem
Keep3rHelper public KPRH;
/// @notice WETH address to liquidity into UNI
WETH9 public constant WETH = WETH9(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
/// @notice UniswapV2Router address
Uniswap public constant UNI = Uniswap(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
/// @notice EIP-20 token name for this token
string public constant name = "Keep3r";
/// @notice EIP-20 token symbol for this token
string public constant symbol = "KPR";
/// @notice EIP-20 token decimals for this token
uint8 public constant decimals = 18;
/// @notice Total number of tokens in circulation
uint public totalSupply = 0; // Initial 0
/// @notice A record of each accounts delegate
mapping (address => address) public delegates;
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
mapping (address => mapping (address => uint)) internal allowances;
mapping (address => uint) internal balances;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint nonce,uint expiry)");
/// @notice The EIP-712 typehash for the permit struct used by the contract
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint votes;
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) public {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public {
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(now <= expiry, "::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account) external view returns (uint) {
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber) public view returns (uint) {
require(blockNumber < block.number, "::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee) internal {
address currentDelegate = delegates[delegator];
uint delegatorBalance = bonds[delegator];
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)) {
uint32 srcRepNum = numCheckpoints[srcRep];
uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint srcRepNew = srcRepOld.sub(amount, "::_moveVotes: vote amount underflows");
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
uint32 dstRepNum = numCheckpoints[dstRep];
uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes) internal {
uint32 blockNumber = safe32(block.number, "::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
/// @notice The standard EIP-20 transfer event
event Transfer(address indexed from, address indexed to, uint amount);
/// @notice The standard EIP-20 approval event
event Approval(address indexed owner, address indexed spender, uint amount);
/// @notice Submit a job
event SubmitJob(address indexed job, address indexed provider, uint block, uint credit);
/// @notice Apply credit to a job
event ApplyCredit(address indexed job, address indexed provider, uint block, uint credit);
/// @notice Remove credit for a job
event RemoveJob(address indexed job, address indexed provider, uint block, uint credit);
/// @notice Unbond credit for a job
event UnbondJob(address indexed job, address indexed provider, uint block, uint credit);
/// @notice Added a Job
event JobAdded(address indexed job, uint block, address governance);
/// @notice Removed a job
event JobRemoved(address indexed job, uint block, address governance);
/// @notice Worked a job
event KeeperWorked(address indexed job, address indexed keeper, uint block);
/// @notice Keeper bonding
event KeeperBonding(address indexed keeper, uint block, uint active, uint bond);
/// @notice Keeper bonded
event KeeperBonded(address indexed keeper, uint block, uint activated, uint bond);
/// @notice Keeper unbonding
event KeeperUnbonding(address indexed keeper, uint block, uint deactive, uint bond);
/// @notice Keeper unbound
event KeeperUnbound(address indexed keeper, uint block, uint deactivated, uint bond);
/// @notice Keeper slashed
event KeeperSlashed(address indexed keeper, address indexed slasher, uint block, uint slash);
/// @notice Keeper disputed
event KeeperDispute(address indexed keeper, uint block);
/// @notice Keeper resolved
event KeeperResolved(address indexed keeper, uint block);
/// @notice 1 day to bond to become a keeper
uint constant public BOND = 3 days;
/// @notice 14 days to unbond to remove funds from being a keeper
uint constant public UNBOND = 14 days;
/// @notice 7 days maximum downtime before being slashed
uint constant public DOWNTIME = 7 days;
/// @notice 3 days till liquidity can be bound
uint constant public LIQUIDITYBOND = 3 days;
/// @notice 5% of funds slashed for downtime
uint constant public DOWNTIMESLASH = 500;
uint constant public BASE = 10000;
/// @notice tracks all current bondings (time)
mapping(address => uint) public bondings;
/// @notice tracks all current unbondings (time)
mapping(address => uint) public unbondings;
/// @notice allows for partial unbonding
mapping(address => uint) public partialUnbonding;
/// @notice tracks all current pending bonds (amount)
mapping(address => uint) public pendingbonds;
/// @notice tracks how much a keeper has bonded
mapping(address => uint) public bonds;
/// @notice total bonded (totalSupply for bonds)
uint public totalBonded = 0;
/// @notice tracks when a keeper was first registered
mapping(address => uint) public firstSeen;
/// @notice tracks if a keeper has a pending dispute
mapping(address => bool) public disputes;
/// @notice tracks last job performed for a keeper
mapping(address => uint) public lastJob;
/// @notice tracks the amount of job executions for a keeper
mapping(address => uint) public work;
/// @notice tracks the total job executions for a keeper
mapping(address => uint) public workCompleted;
/// @notice list of all jobs registered for the keeper system
mapping(address => bool) public jobs;
/// @notice the current credit available for a job
mapping(address => uint) public credits;
/// @notice the balances for the liquidity providers
mapping(address => mapping(address => mapping(address => uint))) public liquidityProvided;
/// @notice liquidity unbonding days
mapping(address => mapping(address => mapping(address => uint))) public liquidityUnbonding;
/// @notice liquidity unbonding amounts
mapping(address => mapping(address => mapping(address => uint))) public liquidityAmountsUnbonding;
/// @notice job proposal delay
mapping(address => uint) public jobProposalDelay;
/// @notice liquidity apply date
mapping(address => mapping(address => mapping(address => uint))) public liquidityApplied;
/// @notice liquidity amount to apply
mapping(address => mapping(address => mapping(address => uint))) public liquidityAmount;
/// @notice list of all current keepers
mapping(address => bool) public keepers;
/// @notice blacklist of keepers not allowed to participate
mapping(address => bool) public blacklist;
/// @notice traversable array of keepers to make external management easier
address[] public keeperList;
/// @notice traversable array of jobs to make external management easier
address[] public jobList;
/// @notice governance address for the governance contract
address public governance;
address public pendingGovernance;
/// @notice the liquidity token supplied by users paying for jobs
mapping(address => bool) public liquidityAccepted;
address[] public liquidityPairs;
uint internal gasUsed;
constructor() public {
// Set governance for this token
governance = msg.sender;
_mint(msg.sender, 10000e18);
}
/**
* @notice Approve a liquidity pair for being accepted in future
* @param liquidity the liquidity no longer accepted
*/
function approveLiquidity(address liquidity) external {
require(msg.sender == governance, "Keep3r::approveLiquidity: governance only");
require(!liquidityAccepted[liquidity], "Keep3r::approveLiquidity: existing liquidity pair");
liquidityAccepted[liquidity] = true;
liquidityPairs.push(liquidity);
}
/**
* @notice Revoke a liquidity pair from being accepted in future
* @param liquidity the liquidity no longer accepted
*/
function revokeLiquidity(address liquidity) external {
require(msg.sender == governance, "Keep3r::revokeLiquidity: governance only");
liquidityAccepted[liquidity] = false;
}
/**
* @notice Displays all accepted liquidity pairs
*/
function pairs() external view returns (address[] memory) {
return liquidityPairs;
}
/**
* @notice Allows liquidity providers to submit jobs
* @param amount the amount of tokens to mint to treasury
* @param job the job to assign credit to
* @param amount the amount of liquidity tokens to use
*/
function addLiquidityToJob(address liquidity, address job, uint amount) external {
require(liquidityAccepted[liquidity], "Keep3r::addLiquidityToJob: asset not accepted as liquidity");
UniswapPair(liquidity).transferFrom(msg.sender, address(this), amount);
liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].add(amount);
liquidityApplied[msg.sender][liquidity][job] = now.add(LIQUIDITYBOND);
liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].add(amount);
if (!jobs[job] && jobProposalDelay[job] < now) {
Governance(governance).proposeJob(job);
jobProposalDelay[job] = now.add(UNBOND);
}
emit SubmitJob(job, msg.sender, block.number, amount);
}
/**
* @notice Applies the credit provided in addLiquidityToJob to the job
* @param provider the liquidity provider
* @param liquidity the pair being added as liquidity
* @param job the job that is receiving the credit
*/
function applyCreditToJob(address provider, address liquidity, address job) external {
require(liquidityAccepted[liquidity], "Keep3r::addLiquidityToJob: asset not accepted as liquidity");
require(liquidityApplied[provider][liquidity][job] != 0, "Keep3r::credit: submitJob first");
require(liquidityApplied[provider][liquidity][job] < now, "Keep3r::credit: still bonding");
uint _liquidity = balances[address(liquidity)];
uint _credit = _liquidity.mul(liquidityAmount[msg.sender][liquidity][job]).div(UniswapPair(liquidity).totalSupply());
credits[job] = credits[job].add(_credit);
liquidityAmount[msg.sender][liquidity][job] = 0;
emit ApplyCredit(job, msg.sender, block.number, _credit);
}
/**
* @notice Unbond liquidity for a pending keeper job
* @param liquidity the pair being unbound
* @param job the job being unbound from
* @param amount the amount of liquidity being removed
*/
function unbondLiquidityFromJob(address liquidity, address job, uint amount) external {
require(liquidityAmount[msg.sender][liquidity][job] == 0, "Keep3r::credit: pending credit, settle first");
liquidityUnbonding[msg.sender][liquidity][job] = now.add(UNBOND);
liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount);
require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "Keep3r::unbondLiquidityFromJob: insufficient funds");
uint _liquidity = balances[address(liquidity)];
uint _credit = _liquidity.mul(amount).div(UniswapPair(liquidity).totalSupply());
if (_credit > credits[job]) {
credits[job] = 0;
} else {
credits[job].sub(_credit);
}
emit UnbondJob(job, msg.sender, block.number, liquidityProvided[msg.sender][liquidity][job]);
}
/**
* @notice Allows liquidity providers to remove liquidity
* @param liquidity the pair being unbound
* @param job the job being unbound from
*/
function removeLiquidityFromJob(address liquidity, address job) external {
require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "Keep3r::removeJob: unbond first");
require(liquidityUnbonding[msg.sender][liquidity][job] < now, "Keep3r::removeJob: still unbonding");
uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job];
liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].sub(_amount);
liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0;
UniswapPair(liquidity).transfer(msg.sender, _amount);
emit RemoveJob(job, msg.sender, block.number, _amount);
}
/**
* @notice Allows governance to mint new tokens to treasury
* @param amount the amount of tokens to mint to treasury
*/
function mint(uint amount) external {
require(msg.sender == governance, "Keep3r::mint: governance only");
_mint(governance, amount);
}
/**
* @notice burn owned tokens
* @param amount the amount of tokens to burn
*/
function burn(uint amount) external {
_burn(msg.sender, amount);
}
function _mint(address dst, uint amount) internal {
// mint the amount
totalSupply = totalSupply.add(amount);
// transfer the amount to the recipient
balances[dst] = balances[dst].add(amount);
emit Transfer(address(0), dst, amount);
}
function _burn(address dst, uint amount) internal {
require(dst != address(0), "::_burn: burn from the zero address");
balances[dst] = balances[dst].sub(amount, "::_burn: burn amount exceeds balance");
totalSupply = totalSupply.sub(amount);
emit Transfer(dst, address(0), amount);
}
/**
* @notice Implemented by jobs to show that a keeper performend work
* @param keeper address of the keeper that performed the work
* @param amount the reward that should be allocated
*/
function workReceipt(address keeper, uint amount) external {
require(jobs[msg.sender], "Keep3r::workReceipt: only jobs can approve work");
gasUsed = gasUsed.sub(gasleft());
require(amount < KPRH.getQuoteLimit(gasUsed), "Keep3r::workReceipt: spending over max limit");
credits[msg.sender] = credits[msg.sender].sub(amount, "Keep3r::workReceipt: insuffient funds to pay keeper");
lastJob[keeper] = now;
_mint(address(this), amount);
_bond(keeper, amount);
workCompleted[keeper] = workCompleted[keeper].add(amount);
emit KeeperWorked(msg.sender, keeper, block.number);
}
function _bond(address _from, uint _amount) internal {
bonds[_from] = bonds[_from].add(_amount);
totalBonded = totalBonded.add(_amount);
_moveDelegates(address(0), delegates[_from], _amount);
}
function _unbond(address _from, uint _amount) internal {
bonds[_from] = bonds[_from].sub(_amount);
totalBonded = totalBonded.sub(_amount);
_moveDelegates(delegates[_from], address(0), _amount);
}
/**
* @notice Allows governance to add new job systems
* @param job address of the contract for which work should be performed
*/
function addJob(address job) external {
require(msg.sender == governance, "Keep3r::addJob: only governance can add jobs");
require(!jobs[job], "Keep3r::addJob: job already known");
jobs[job] = true;
jobList.push(job);
emit JobAdded(job, block.number, msg.sender);
}
/**
* @notice Full listing of all jobs ever added
* @return array blob
*/
function getJobs() external view returns (address[] memory) {
return jobList;
}
/**
* @notice Allows governance to remove a job from the systems
* @param job address of the contract for which work should be performed
*/
function removeJob(address job) external {
require(msg.sender == governance, "Keep3r::removeJob: only governance can remove jobs");
jobs[job] = false;
emit JobRemoved(job, block.number, msg.sender);
}
/**
* @notice Allows governance to change the Keep3rHelper for max spend
* @param _kprh new helper address to set
*/
function setKeep3rHelper(Keep3rHelper _kprh) external {
require(msg.sender == governance, "Keep3r::setKeep3rHelper: only governance can set");
KPRH = _kprh;
}
/**
* @notice Allows governance to change governance (for future upgradability)
* @param _governance new governance address to set
*/
function setGovernance(address _governance) external {
require(msg.sender == governance, "Keep3r::setGovernance: only governance can set");
pendingGovernance = _governance;
}
/**
* @notice Allows pendingGovernance to accept their role as governance (protection pattern)
*/
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "Keep3r::acceptGovernance: only pendingGovernance can accept");
governance = pendingGovernance;
}
/**
* @notice confirms if the current keeper is registered, can be used for general (non critical) functions
* @return true/false if the address is a keeper
*/
function isKeeper(address keeper) external returns (bool) {
gasUsed = gasleft();
return keepers[keeper];
}
/**
* @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions
* @return true/false if the address is a keeper and has more than the bond
*/
function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool) {
gasUsed = gasleft();
return keepers[keeper]
&& bonds[keeper] >= minBond
&& workCompleted[keeper] >= earned
&& now.sub(firstSeen[keeper]) >= age;
}
/**
* @notice begin the bonding process for a new keeper
*/
function bond(uint amount) external {
require(pendingbonds[msg.sender] == 0, "Keep3r::bond: current pending bond");
require(!blacklist[msg.sender], "Keep3r::bond: keeper is blacklisted");
bondings[msg.sender] = now.add(BOND);
_transferTokens(msg.sender, address(this), amount);
pendingbonds[msg.sender] = pendingbonds[msg.sender].add(amount);
emit KeeperBonding(msg.sender, block.number, bondings[msg.sender], amount);
}
function getKeepers() external view returns (address[] memory) {
return keeperList;
}
/**
* @notice allows a keeper to activate/register themselves after bonding
*/
function activate() external {
require(!blacklist[msg.sender], "Keep3r::activate: keeper is blacklisted");
require(bondings[msg.sender] != 0 && bondings[msg.sender] < now, "Keep3r::activate: still bonding");
if (firstSeen[msg.sender] == 0) {
firstSeen[msg.sender] = now;
keeperList.push(msg.sender);
lastJob[msg.sender] = now;
}
keepers[msg.sender] = true;
_bond(msg.sender, pendingbonds[msg.sender]);
pendingbonds[msg.sender] = 0;
emit KeeperBonded(msg.sender, block.number, block.timestamp, bonds[msg.sender]);
}
/**
* @notice begin the unbonding process to stop being a keeper
* @param amount allows for partial unbonding
*/
function unbond(uint amount) external {
unbondings[msg.sender] = now.add(UNBOND);
_unbond(msg.sender, amount);
partialUnbonding[msg.sender] = partialUnbonding[msg.sender].add(amount);
emit KeeperUnbonding(msg.sender, block.number, unbondings[msg.sender], amount);
}
/**
* @notice withdraw funds after unbonding has finished
*/
function withdraw() external {
require(unbondings[msg.sender] != 0 && unbondings[msg.sender] < now, "Keep3r::withdraw: still unbonding");
require(!disputes[msg.sender], "Keep3r::withdraw: pending disputes");
_transferTokens(address(this), msg.sender, partialUnbonding[msg.sender]);
emit KeeperUnbound(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender]);
partialUnbonding[msg.sender] = 0;
}
/**
* @notice slash a keeper for downtime
* @param keeper the address being slashed
*/
function down(address keeper) external {
require(keepers[msg.sender], "Keep3r::down: not a keeper");
require(keepers[keeper], "Keep3r::down: keeper not registered");
require(lastJob[keeper].add(DOWNTIME) < now, "Keep3r::down: keeper safe");
uint _slash = bonds[keeper].mul(DOWNTIMESLASH).div(BASE);
_unbond(keeper, _slash);
_bond(msg.sender, _slash);
lastJob[keeper] = now;
lastJob[msg.sender] = now;
emit KeeperSlashed(keeper, msg.sender, block.number, _slash);
}
/**
* @notice allows governance to create a dispute for a given keeper
* @param keeper the address in dispute
*/
function dispute(address keeper) external returns (uint) {
require(msg.sender == governance, "Keep3r::dispute: only governance can dispute");
disputes[keeper] = true;
emit KeeperDispute(keeper, block.number);
}
/**
* @notice allows governance to slash a keeper based on a dispute
* @param keeper the address being slashed
* @param amount the amount being slashed
*/
function slash(address keeper, uint amount) public {
require(msg.sender == governance, "Keep3r::slash: only governance can resolve");
_transferTokens(address(this), governance, amount);
_unbond(keeper, amount);
disputes[keeper] = false;
emit KeeperSlashed(keeper, msg.sender, block.number, amount);
}
/**
* @notice blacklists a keeper from participating in the network
* @param keeper the address being slashed
*/
function revoke(address keeper) external {
require(msg.sender == governance, "Keep3r::slash: only governance can resolve");
keepers[keeper] = false;
blacklist[keeper] = true;
slash(keeper, bonds[keeper]);
}
/**
* @notice allows governance to resolve a dispute on a keeper
* @param keeper the address cleared
*/
function resolve(address keeper) external {
require(msg.sender == governance, "Keep3r::resolve: only governance can resolve");
disputes[keeper] = false;
emit KeeperResolved(keeper, block.number);
}
/**
* @notice Get the number of tokens `spender` is approved to spend on behalf of `account`
* @param account The address of the account holding the funds
* @param spender The address of the account spending the funds
* @return The number of tokens approved
*/
function allowance(address account, address spender) external view returns (uint) {
return allowances[account][spender];
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (2^256-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint amount) public returns (bool) {
allowances[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
/**
* @notice Triggers an approval from owner to spends
* @param owner The address to approve from
* @param spender The address to be approved
* @param amount The number of tokens that are approved (2^256-1 means infinite)
* @param deadline The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function permit(address owner, address spender, uint amount, uint deadline, 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(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "::permit: invalid signature");
require(signatory == owner, "::permit: unauthorized");
require(now <= deadline, "::permit: signature expired");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @notice Get the number of tokens held by the `account`
* @param account The address of the account to get the balance of
* @return The number of tokens held
*/
function balanceOf(address account) external view returns (uint) {
return balances[account];
}
/**
* @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, uint amount) public returns (bool) {
_transferTokens(msg.sender, dst, amount);
return true;
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint amount) external returns (bool) {
address spender = msg.sender;
uint spenderAllowance = allowances[src][spender];
if (spender != src && spenderAllowance != uint(-1)) {
uint newAllowance = spenderAllowance.sub(amount, "::transferFrom: transfer amount exceeds spender allowance");
allowances[src][spender] = newAllowance;
emit Approval(src, spender, newAllowance);
}
_transferTokens(src, dst, amount);
return true;
}
function _transferTokens(address src, address dst, uint amount) internal {
require(src != address(0), "::_transferTokens: cannot transfer from the zero address");
require(dst != address(0), "::_transferTokens: cannot transfer to the zero address");
balances[src] = balances[src].sub(amount, "::_transferTokens: transfer amount exceeds balance");
balances[dst] = balances[dst].add(amount, "::_transferTokens: transfer amount overflows");
emit Transfer(src, dst, amount);
}
function getChainId() internal pure returns (uint) {
uint chainId;
assembly { chainId := chainid() }
return chainId;
}
}
|
Allows governance to change governance (for future upgradability) _governance new governance address to set/
|
function setGovernance(address _governance) external {
require(msg.sender == governance, "Keep3r::setGovernance: only governance can set");
pendingGovernance = _governance;
}
| 603,491 |
./full_match/10/0x3c0FFAca566fCcfD9Cc95139FEF6CBA143795963/sources/contracts/saddle/Swap.sol
|
Swap two tokens using this pool tokenIndexFrom the token the user wants to swap from tokenIndexTo the token the user wants to swap to dx the amount of tokens the user wants to swap from minDy the min amount the user would like to receive, or revert. deadline latest timestamp to accept this transaction/ whenNotPaused
|
function swap(
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy,
uint256 deadline
)
external
nonReentrant
deadlineCheck(deadline)
returns (uint256)
{
return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy);
}
| 3,780,246 |
// CryptoRabbit Source code
pragma solidity ^0.4.20;
/**
*
* @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens
* @author cuilichen
*/
contract ERC721 {
// Required methods
function totalSupply() public view returns (uint total);
function balanceOf(address _owner) public view returns (uint balance);
function ownerOf(uint _tokenId) external view returns (address owner);
function approve(address _to, uint _tokenId) external;
function transfer(address _to, uint _tokenId) external;
function transferFrom(address _from, address _to, uint _tokenId) external;
// Events
event Transfer(address indexed from, address indexed to, uint tokenId);
event Approval(address indexed owner, address indexed approved, uint tokenId);
}
/// @title A base contract to control ownership
/// @author cuilichen
contract OwnerBase {
// The addresses of the accounts that can execute actions within each roles.
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;
/// constructor
function OwnerBase() public {
ceoAddress = msg.sender;
cfoAddress = msg.sender;
cooAddress = msg.sender;
}
/// @dev Access modifier for CEO-only functionality
modifier onlyCEO() {
require(msg.sender == ceoAddress);
_;
}
/// @dev Access modifier for CFO-only functionality
modifier onlyCFO() {
require(msg.sender == cfoAddress);
_;
}
/// @dev Access modifier for COO-only functionality
modifier onlyCOO() {
require(msg.sender == cooAddress);
_;
}
/// @dev Assigns a new address to act as the CEO. Only available to the current CEO.
/// @param _newCEO The address of the new CEO
function setCEO(address _newCEO) external onlyCEO {
require(_newCEO != address(0));
ceoAddress = _newCEO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCFO The address of the new COO
function setCFO(address _newCFO) external onlyCEO {
require(_newCFO != address(0));
cfoAddress = _newCFO;
}
/// @dev Assigns a new address to act as the COO. Only available to the current CEO.
/// @param _newCOO The address of the new COO
function setCOO(address _newCOO) external onlyCEO {
require(_newCOO != address(0));
cooAddress = _newCOO;
}
/// @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);
_;
}
/// @dev Called by any "C-level" role to pause the contract. Used only when
/// a bug or exploit is detected and we need to limit damage.
function pause() external onlyCOO whenNotPaused {
paused = true;
}
/// @dev Unpauses the smart contract. Can only be called by the CEO, since
/// one reason we may pause the contract is when CFO or COO accounts are
/// compromised.
/// @notice This is public rather than external so it can be called by
/// derived contracts.
function unpause() public onlyCOO whenPaused {
// can't unpause if contract was upgraded
paused = false;
}
/// @dev check wether target address is a contract or not
function isNotContract(address addr) internal view returns (bool) {
uint size = 0;
assembly {
size := extcodesize(addr)
}
return size == 0;
}
}
/**
*
* @title Interface for contracts conforming to fighters camp
* @author cuilichen
*/
contract FighterCamp {
//
function isCamp() public pure returns (bool);
// Required methods
function getFighter(uint _tokenId) external view returns (uint32);
}
/// @title Base contract for CryptoRabbit. Holds all common structs, events and base variables.
/// @author cuilichen
/// @dev See the RabbitCore contract documentation to understand how the various contract facets are arranged.
contract RabbitBase is ERC721, OwnerBase, FighterCamp {
/*** EVENTS ***/
/// @dev The Birth event is fired whenever a new rabbit comes into existence.
event Birth(address owner, uint rabbitId, uint32 star, uint32 explosive, uint32 endurance, uint32 nimble, uint64 genes, uint8 isBox);
/*** DATA TYPES ***/
struct RabbitData {
//genes for rabbit
uint64 genes;
//
uint32 star;
//
uint32 explosive;
//
uint32 endurance;
//
uint32 nimble;
//birth time
uint64 birthTime;
}
/// @dev An array containing the Rabbit struct for all rabbits in existence. The ID
/// of each rabbit is actually an index into this array.
RabbitData[] rabbits;
/// @dev A mapping from rabbit IDs to the address that owns them.
mapping (uint => address) rabbitToOwner;
// @dev A mapping from owner address to count of tokens that address owns.
// Used internally inside balanceOf() to resolve ownership count.
mapping (address => uint) howManyDoYouHave;
/// @dev A mapping from RabbitIDs to an address that has been approved to call
/// transfeFrom(). Each Rabbit can only have one approved address for transfer
/// at any time. A zero value means no approval is outstanding.
mapping (uint => address) public rabbitToApproved;
/// @dev Assigns ownership of a specific Rabbit to an address.
function _transItem(address _from, address _to, uint _tokenId) internal {
// Since the number of rabbits is capped to 2^32 we can't overflow this
howManyDoYouHave[_to]++;
// transfer ownership
rabbitToOwner[_tokenId] = _to;
// When creating new rabbits _from is 0x0, but we can't account that address.
if (_from != address(0)) {
howManyDoYouHave[_from]--;
}
// clear any previously approved ownership exchange
delete rabbitToApproved[_tokenId];
// Emit the transfer event.
if (_tokenId > 0) {
emit Transfer(_from, _to, _tokenId);
}
}
/// @dev An internal method that creates a new rabbit and stores it. This
/// method doesn't do any checking and should only be called when the
/// input data is known to be valid. Will generate both a Birth event
/// and a Transfer event.
function _createRabbit(
uint _star,
uint _explosive,
uint _endurance,
uint _nimble,
uint _genes,
address _owner,
uint8 isBox
)
internal
returns (uint)
{
require(_star >= 1 && _star <= 5);
RabbitData memory _tmpRbt = RabbitData({
genes: uint64(_genes),
star: uint32(_star),
explosive: uint32(_explosive),
endurance: uint32(_endurance),
nimble: uint32(_nimble),
birthTime: uint64(now)
});
uint newRabbitID = rabbits.push(_tmpRbt) - 1;
/* */
// emit the birth event
emit Birth(
_owner,
newRabbitID,
_tmpRbt.star,
_tmpRbt.explosive,
_tmpRbt.endurance,
_tmpRbt.nimble,
_tmpRbt.genes,
isBox
);
// This will assign ownership, and also emit the Transfer event as
// per ERC721 draft
if (_owner != address(0)){
_transItem(0, _owner, newRabbitID);
} else {
_transItem(0, ceoAddress, newRabbitID);
}
return newRabbitID;
}
/// @notice Returns all the relevant information about a specific rabbit.
/// @param _tokenId The ID of the rabbit of interest.
function getRabbit(uint _tokenId) external view returns (
uint32 outStar,
uint32 outExplosive,
uint32 outEndurance,
uint32 outNimble,
uint64 outGenes,
uint64 outBirthTime
) {
RabbitData storage rbt = rabbits[_tokenId];
outStar = rbt.star;
outExplosive = rbt.explosive;
outEndurance = rbt.endurance;
outNimble = rbt.nimble;
outGenes = rbt.genes;
outBirthTime = rbt.birthTime;
}
function isCamp() public pure returns (bool){
return true;
}
/// @dev An external method that get infomation of the fighter
/// @param _tokenId The ID of the fighter.
function getFighter(uint _tokenId) external view returns (uint32) {
RabbitData storage rbt = rabbits[_tokenId];
uint32 strength = uint32(rbt.explosive + rbt.endurance + rbt.nimble);
return strength;
}
}
/// @title The facet of the CryptoRabbit core contract that manages ownership, ERC-721 (draft) compliant.
/// @author cuilichen
/// @dev Ref: https://github.com/ethereum/EIPs/issues/721
/// See the RabbitCore contract documentation to understand how the various contract facets are arranged.
contract RabbitOwnership is RabbitBase {
/// @notice Name and symbol of the non fungible token, as defined in ERC721.
string public name;
string public symbol;
//identify this is ERC721
function isERC721() public pure returns (bool) {
return true;
}
// Internal utility functions: These functions all assume that their input arguments
// are valid. We leave it to public methods to sanitize their inputs and follow
// the required logic.
/// @dev Checks if a given address is the current owner of a particular Rabbit.
/// @param _owner the address we are validating against.
/// @param _tokenId rabbit id, only valid when > 0
function _owns(address _owner, uint _tokenId) internal view returns (bool) {
return rabbitToOwner[_tokenId] == _owner;
}
/// @dev Checks if a given address currently has transferApproval for a particular Rabbit.
/// @param _claimant the address we are confirming rabbit is approved for.
/// @param _tokenId rabbit id, only valid when > 0
function _approvedFor(address _claimant, uint _tokenId) internal view returns (bool) {
return rabbitToApproved[_tokenId] == _claimant;
}
/// @dev Marks an address as being approved for transfeFrom(), overwriting any previous
/// approval. Setting _approved to address(0) clears all transfer approval.
/// NOTE: _approve() does NOT send the Approval event. This is intentional because
/// _approve() and transfeFrom() are used together for putting rabbits on auction, and
/// there is no value in spamming the log with Approval events in that case.
function _approve(uint _tokenId, address _to) internal {
rabbitToApproved[_tokenId] = _to;
}
/// @notice Returns the number of rabbits owned by a specific address.
/// @param _owner The owner address to check.
/// @dev Required for ERC-721 compliance
function balanceOf(address _owner) public view returns (uint count) {
return howManyDoYouHave[_owner];
}
/// @notice Transfers a Rabbit to another address. If transferring to a smart
/// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or
/// CryptoRabbit specifically) or your Rabbit may be lost forever. Seriously.
/// @param _to The address of the recipient, can be a user or contract.
/// @param _tokenId The ID of the Rabbit to transfer.
/// @dev Required for ERC-721 compliance.
function transfer(
address _to,
uint _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
// Disallow transfers to this contract to prevent accidental misuse.
require(_to != address(this));
// You can only send your own rabbit.
require(_owns(msg.sender, _tokenId));
// Reassign ownership, clear pending approvals, emit Transfer event.
_transItem(msg.sender, _to, _tokenId);
}
/// @notice Grant another address the right to transfer a specific Rabbit via
/// transfeFrom(). 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 Rabbit that can be transferred if this call succeeds.
/// @dev Required for ERC-721 compliance.
function approve(
address _to,
uint _tokenId
)
external
whenNotPaused
{
require(_owns(msg.sender, _tokenId)); // Only an owner can grant transfer approval.
require(msg.sender != _to); // can not approve to itself;
// Register the approval (replacing any previous approval).
_approve(_tokenId, _to);
// Emit approval event.
emit Approval(msg.sender, _to, _tokenId);
}
/// @notice Transfer a Rabbit 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 Rabbit to be transfered.
/// @param _to The address that should take ownership of the Rabbit. Can be any address,
/// including the caller.
/// @param _tokenId The ID of the Rabbit to be transferred.
/// @dev Required for ERC-721 compliance.
function transferFrom(
address _from,
address _to,
uint _tokenId
)
external
whenNotPaused
{
// Safety check to prevent against an unexpected 0x0 default.
require(_to != address(0));
//
require(_owns(_from, _tokenId));
// Check for approval and valid ownership
require(_approvedFor(msg.sender, _tokenId));
// Reassign ownership (also clears pending approvals and emits Transfer event).
_transItem(_from, _to, _tokenId);
}
/// @notice Returns the total number of rabbits currently in existence.
/// @dev Required for ERC-721 compliance.
function totalSupply() public view returns (uint) {
return rabbits.length - 1;
}
/// @notice Returns the address currently assigned ownership of a given Rabbit.
/// @dev Required for ERC-721 compliance.
function ownerOf(uint _tokenId)
external
view
returns (address owner)
{
owner = rabbitToOwner[_tokenId];
require(owner != address(0));
}
/// @notice Returns a list of all Rabbit IDs assigned to an address.
/// @param _owner The owner whose rabbits we are interested in.
/// @dev This method MUST NEVER be called by smart contract code. First, it's fairly
/// expensive (it walks the entire Rabbit array looking for rabbits belonging to owner),
/// but it also returns a dynamic array, which is only supported for web3 calls, and
/// not contract-to-contract calls.
function tokensOfOwner(address _owner) external view returns(uint[] ownerTokens) {
uint tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint[](0);
} else {
uint[] memory result = new uint[](tokenCount);
uint totalCats = totalSupply();
uint resultIndex = 0;
// We count on the fact that all rabbits have IDs starting at 1 and increasing
// sequentially up to the totalCat count.
uint rabbitId;
for (rabbitId = 1; rabbitId <= totalCats; rabbitId++) {
if (rabbitToOwner[rabbitId] == _owner) {
result[resultIndex] = rabbitId;
resultIndex++;
}
}
return result;
}
}
}
/// @title all functions related to creating rabbits and sell rabbits
contract RabbitMinting is RabbitOwnership {
// Price (in wei) for star5 rabbit
uint public priceStar5Now = 1 ether;
// Price (in wei) for star4 rabbit
uint public priceStar4 = 100 finney;
// Price (in wei) for star3 rabbit
uint public priceStar3 = 5 finney;
uint private priceStar5Min = 1 ether;
uint private priceStar5Add = 2 finney;
//rabbit box1
uint public priceBox1 = 10 finney;
uint public box1Star5 = 50;
uint public box1Star4 = 500;
//rabbit box2
uint public priceBox2 = 100 finney;
uint public box2Star5 = 500;
// Limits the number of star5 rabbits can ever create.
uint public constant LIMIT_STAR5 = 2000;
// Limits the number of star4 rabbits can ever create.
uint public constant LIMIT_STAR4 = 20000;
// Limits the number of rabbits the contract owner can ever create.
uint public constant LIMIT_PROMO = 5000;
// Counts the number of rabbits of star 5
uint public CREATED_STAR5;
// Counts the number of rabbits of star 4
uint public CREATED_STAR4;
// Counts the number of rabbits the contract owner has created.
uint public CREATED_PROMO;
//an secret key used for random
uint private secretKey = 392828872;
//box is on sale
bool private box1OnSale = true;
//box is on sale
bool private box2OnSale = true;
//record any task id for updating datas;
mapping(uint => uint8) usedSignId;
/// @dev set base infomation by coo
function setBaseInfo(uint val, bool _onSale1, bool _onSale2) external onlyCOO {
secretKey = val;
box1OnSale = _onSale1;
box2OnSale = _onSale2;
}
/// @dev we can create promo rabbits, up to a limit. Only callable by COO
function createPromoRabbit(uint _star, address _owner) whenNotPaused external onlyCOO {
require (_owner != address(0));
require(CREATED_PROMO < LIMIT_PROMO);
if (_star == 5){
require(CREATED_STAR5 < LIMIT_STAR5);
} else if (_star == 4){
require(CREATED_STAR4 < LIMIT_STAR4);
}
CREATED_PROMO++;
_createRabbitInGrade(_star, _owner, 0);
}
/// @dev create a rabbit with grade, and set its owner.
function _createRabbitInGrade(uint _star, address _owner, uint8 isBox) internal {
uint _genes = uint(keccak256(uint(_owner) + secretKey + rabbits.length));
uint _explosive = 50;
uint _endurance = 50;
uint _nimble = 50;
if (_star < 5) {
uint tmp = _genes;
tmp = uint(keccak256(tmp));
_explosive = 1 + 10 * (_star - 1) + tmp % 10;
tmp = uint(keccak256(tmp));
_endurance = 1 + 10 * (_star - 1) + tmp % 10;
tmp = uint(keccak256(tmp));
_nimble = 1 + 10 * (_star - 1) + tmp % 10;
}
uint64 _geneShort = uint64(_genes);
if (_star == 5){
CREATED_STAR5++;
priceStar5Now = priceStar5Min + priceStar5Add * CREATED_STAR5;
_geneShort = uint64(_geneShort - _geneShort % 2000 + CREATED_STAR5);
} else if (_star == 4){
CREATED_STAR4++;
}
_createRabbit(
_star,
_explosive,
_endurance,
_nimble,
_geneShort,
_owner,
isBox);
}
/// @notice customer buy a rabbit
/// @param _star the star of the rabbit to buy
function buyOneRabbit(uint _star) external payable whenNotPaused returns (bool) {
require(isNotContract(msg.sender));
uint tmpPrice = 0;
if (_star == 5){
tmpPrice = priceStar5Now;
require(CREATED_STAR5 < LIMIT_STAR5);
} else if (_star == 4){
tmpPrice = priceStar4;
require(CREATED_STAR4 < LIMIT_STAR4);
} else if (_star == 3){
tmpPrice = priceStar3;
} else {
revert();
}
require(msg.value >= tmpPrice);
_createRabbitInGrade(_star, msg.sender, 0);
// Return the funds.
uint fundsExcess = msg.value - tmpPrice;
if (fundsExcess > 1 finney) {
msg.sender.transfer(fundsExcess);
}
return true;
}
/// @notice customer buy a box
function buyBox1() external payable whenNotPaused returns (bool) {
require(isNotContract(msg.sender));
require(box1OnSale);
require(msg.value >= priceBox1);
uint tempVal = uint(keccak256(uint(msg.sender) + secretKey + rabbits.length));
tempVal = tempVal % 10000;
uint _star = 3; //default
if (tempVal <= box1Star5){
_star = 5;
require(CREATED_STAR5 < LIMIT_STAR5);
} else if (tempVal <= box1Star5 + box1Star4){
_star = 4;
require(CREATED_STAR4 < LIMIT_STAR4);
}
_createRabbitInGrade(_star, msg.sender, 2);
// Return the funds.
uint fundsExcess = msg.value - priceBox1;
if (fundsExcess > 1 finney) {
msg.sender.transfer(fundsExcess);
}
return true;
}
/// @notice customer buy a box
function buyBox2() external payable whenNotPaused returns (bool) {
require(isNotContract(msg.sender));
require(box2OnSale);
require(msg.value >= priceBox2);
uint tempVal = uint(keccak256(uint(msg.sender) + secretKey + rabbits.length));
tempVal = tempVal % 10000;
uint _star = 4; //default
if (tempVal <= box2Star5){
_star = 5;
require(CREATED_STAR5 < LIMIT_STAR5);
} else {
require(CREATED_STAR4 < LIMIT_STAR4);
}
_createRabbitInGrade(_star, msg.sender, 3);
// Return the funds.
uint fundsExcess = msg.value - priceBox2;
if (fundsExcess > 1 finney) {
msg.sender.transfer(fundsExcess);
}
return true;
}
}
/// @title all functions related to creating rabbits and sell rabbits
contract RabbitAuction is RabbitMinting {
//events about auctions
event AuctionCreated(uint tokenId, uint startingPrice, uint endingPrice, uint duration, uint startTime, uint32 explosive, uint32 endurance, uint32 nimble, uint32 star);
event AuctionSuccessful(uint tokenId, uint totalPrice, address winner);
event AuctionCancelled(uint tokenId);
event UpdateComplete(address account, uint tokenId);
// 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
uint64 startedAt;
}
// Cut owner takes on each auction, measured in basis points (1/100 of a percent).
// Values 0-10,000 map to 0%-100%
uint public masterCut = 200;
// Map from token ID to their corresponding auction.
mapping (uint => Auction) tokenIdToAuction;
/// @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).
function createAuction(
uint _tokenId,
uint _startingPrice,
uint _endingPrice,
uint _duration
)
external whenNotPaused
{
require(isNotContract(msg.sender));
require(_endingPrice >= 1 finney);
require(_startingPrice >= _endingPrice);
require(_duration <= 100 days);
require(_owns(msg.sender, _tokenId));
//assigning the ownship to this contract,
_transItem(msg.sender, this, _tokenId);
Auction memory auction = Auction(
msg.sender,
uint128(_startingPrice),
uint128(_endingPrice),
uint64(_duration),
uint64(now)
);
_addAuction(_tokenId, auction);
}
/// @dev Returns auction info for an NFT on auction.
/// @param _tokenId - ID of NFT on auction.
function getAuctionData(uint _tokenId) external view returns (
address seller,
uint startingPrice,
uint endingPrice,
uint duration,
uint startedAt,
uint currentPrice
) {
Auction storage auction = tokenIdToAuction[_tokenId];
require(auction.startedAt > 0);
seller = auction.seller;
startingPrice = auction.startingPrice;
endingPrice = auction.endingPrice;
duration = auction.duration;
startedAt = auction.startedAt;
currentPrice = _calcCurrentPrice(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(uint _tokenId) external payable whenNotPaused {
require(isNotContract(msg.sender));
// Get a reference to the auction struct
Auction storage auction = tokenIdToAuction[_tokenId];
require(auction.startedAt > 0);
// Check that the bid is greater than or equal to the current price
uint price = _calcCurrentPrice(auction);
require(msg.value >= price);
// Grab a reference to the seller before the auction struct gets deleted.
address seller = auction.seller;
//
require(_owns(this, _tokenId));
// The bid is good! Remove the auction before sending the fees
// to the sender so we can't have a reentrancy endurance.
delete tokenIdToAuction[_tokenId];
if (price > 0) {
// Calculate the auctioneer's cut.
uint auctioneerCut = price * masterCut / 10000;
uint sellerProceeds = price - auctioneerCut;
require(sellerProceeds <= price);
// Doing a transfer() after removing the auction
seller.transfer(sellerProceeds);
}
// Calculate any excess funds included with the bid.
uint bidExcess = msg.value - price;
// Return the funds.
if (bidExcess >= 1 finney) {
msg.sender.transfer(bidExcess);
}
// Tell the world!
emit AuctionSuccessful(_tokenId, price, msg.sender);
//give goods to bidder.
_transItem(this, 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(uint _tokenId) external whenNotPaused {
Auction storage auction = tokenIdToAuction[_tokenId];
require(auction.startedAt > 0);
address seller = auction.seller;
require(msg.sender == seller);
_cancelAuction(_tokenId);
}
/// @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 cancelAuctionByMaster(uint _tokenId)
external onlyCOO whenPaused
{
_cancelAuction(_tokenId);
}
/// @dev Adds an auction to the list of open auctions. Also fires an event.
/// @param _tokenId The ID of the token to be put on auction.
/// @param _auction Auction to add.
function _addAuction(uint _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;
RabbitData storage rdata = rabbits[_tokenId];
emit AuctionCreated(
uint(_tokenId),
uint(_auction.startingPrice),
uint(_auction.endingPrice),
uint(_auction.duration),
uint(_auction.startedAt),
uint32(rdata.explosive),
uint32(rdata.endurance),
uint32(rdata.nimble),
uint32(rdata.star)
);
}
/// @dev Cancels an auction unconditionally.
function _cancelAuction(uint _tokenId) internal {
Auction storage auction = tokenIdToAuction[_tokenId];
_transItem(this, auction.seller, _tokenId);
delete tokenIdToAuction[_tokenId];
emit AuctionCancelled(_tokenId);
}
/// @dev Returns current price of an NFT on auction.
function _calcCurrentPrice(Auction storage _auction)
internal
view
returns (uint outPrice)
{
int256 duration = _auction.duration;
int256 price0 = _auction.startingPrice;
int256 price2 = _auction.endingPrice;
require(duration > 0);
int256 secondsPassed = int256(now) - int256(_auction.startedAt);
require(secondsPassed >= 0);
if (secondsPassed < _auction.duration) {
int256 priceChanged = (price2 - price0) * secondsPassed / duration;
int256 currentPrice = price0 + priceChanged;
outPrice = uint(currentPrice);
} else {
outPrice = _auction.endingPrice;
}
}
/// @dev tranfer token to the target, in case of some error occured.
/// Only the coo may do this.
/// @param _to The target address.
/// @param _to The id of the token.
function transferOnError(address _to, uint _tokenId) external onlyCOO {
require(_owns(this, _tokenId));
Auction storage auction = tokenIdToAuction[_tokenId];
require(auction.startedAt == 0);
_transItem(this, _to, _tokenId);
}
/// @dev allow the user to draw a rabbit, with a signed message from coo
function getFreeRabbit(uint32 _star, uint _taskId, uint8 v, bytes32 r, bytes32 s) external {
require(usedSignId[_taskId] == 0);
uint[2] memory arr = [_star, _taskId];
string memory text = uint2ToStr(arr);
address signer = verify(text, v, r, s);
require(signer == cooAddress);
_createRabbitInGrade(_star, msg.sender, 4);
usedSignId[_taskId] = 1;
}
/// @dev allow any user to set rabbit data, with a signed message from coo
function setRabbitData(
uint _tokenId,
uint32 _explosive,
uint32 _endurance,
uint32 _nimble,
uint _taskId,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(usedSignId[_taskId] == 0);
Auction storage auction = tokenIdToAuction[_tokenId];
require (auction.startedAt == 0);
uint[5] memory arr = [_tokenId, _explosive, _endurance, _nimble, _taskId];
string memory text = uint5ToStr(arr);
address signer = verify(text, v, r, s);
require(signer == cooAddress);
RabbitData storage rdata = rabbits[_tokenId];
rdata.explosive = _explosive;
rdata.endurance = _endurance;
rdata.nimble = _nimble;
rabbits[_tokenId] = rdata;
usedSignId[_taskId] = 1;
emit UpdateComplete(msg.sender, _tokenId);
}
/// @dev werify wether the message is form coo or not.
function verify(string text, uint8 v, bytes32 r, bytes32 s) public pure returns (address) {
bytes32 hash = keccak256(text);
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(prefix, hash);
address tmp = ecrecover(prefixedHash, v, r, s);
return tmp;
}
/// @dev create an string according to the array
function uint2ToStr(uint[2] arr) internal pure returns (string){
uint length = 0;
uint i = 0;
uint val = 0;
for(; i < arr.length; i++){
val = arr[i];
while(val >= 10) {
length += 1;
val = val / 10;
}
length += 1;//for single
length += 1;//for comma
}
length -= 1;//remove last comma
//copy char to bytes
bytes memory bstr = new bytes(length);
uint k = length - 1;
int j = int(arr.length - 1);
while (j >= 0) {
val = arr[uint(j)];
if (val == 0) {
bstr[k] = byte(48);
if (k > 0) {
k--;
}
} else {
while (val != 0){
bstr[k] = byte(48 + val % 10);
val /= 10;
if (k > 0) {
k--;
}
}
}
if (j > 0) { //add comma
assert(k > 0);
bstr[k] = byte(44);
k--;
}
j--;
}
return string(bstr);
}
/// @dev create an string according to the array
function uint5ToStr(uint[5] arr) internal pure returns (string){
uint length = 0;
uint i = 0;
uint val = 0;
for(; i < arr.length; i++){
val = arr[i];
while(val >= 10) {
length += 1;
val = val / 10;
}
length += 1;//for single
length += 1;//for comma
}
length -= 1;//remove last comma
//copy char to bytes
bytes memory bstr = new bytes(length);
uint k = length - 1;
int j = int(arr.length - 1);
while (j >= 0) {
val = arr[uint(j)];
if (val == 0) {
bstr[k] = byte(48);
if (k > 0) {
k--;
}
} else {
while (val != 0){
bstr[k] = byte(48 + val % 10);
val /= 10;
if (k > 0) {
k--;
}
}
}
if (j > 0) { //add comma
assert(k > 0);
bstr[k] = byte(44);
k--;
}
j--;
}
return string(bstr);
}
}
/// @title CryptoRabbit: Collectible, oh-so-adorable rabbits on the Ethereum blockchain.
/// @author cuilichen
/// @dev The main CryptoRabbit contract, keeps track of rabbits so they don't wander around and get lost.
/// This is the main CryptoRabbit contract. In order to keep our code seperated into logical sections.
contract RabbitCore is RabbitAuction {
event ContractUpgrade(address newContract);
// Set in case the core contract is broken and an upgrade is required
address public newContractAddress;
/// @notice Creates the main CryptoRabbit smart contract instance.
function RabbitCore(string _name, string _symbol) public {
name = _name;
symbol = _symbol;
// the creator of the contract is the initial CEO
ceoAddress = msg.sender;
cooAddress = msg.sender;
cfoAddress = msg.sender;
//first rabbit in this world
_createRabbit(5, 50, 50, 50, 1, msg.sender, 0);
}
/// @dev Used to mark the smart contract as upgraded.
/// @param _v2Address new address
function upgradeContract(address _v2Address) external onlyCOO whenPaused {
// See README.md for updgrade plan
newContractAddress = _v2Address;
emit ContractUpgrade(_v2Address);
}
/// @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.
/// @notice This is public rather than external so we can call super.unpause
/// without using an expensive CALL.
function unpause() public onlyCOO {
require(newContractAddress == address(0));
// Actually unpause the contract.
super.unpause();
}
// @dev Allows the CEO to capture the balance available to the contract.
function withdrawBalance() external onlyCFO {
address tmp = address(this);
cfoAddress.transfer(tmp.balance);
}
}
|
werify wether the message is form coo or not.
|
function verify(string text, uint8 v, bytes32 r, bytes32 s) public pure returns (address) {
bytes32 hash = keccak256(text);
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(prefix, hash);
address tmp = ecrecover(prefixedHash, v, r, s);
return tmp;
}
| 2,515,431 |
./full_match/5/0x18E98c89d3D0E7eDe0f6E8af32c6117c3eDbb8C6/sources/contracts/Memecoin.flatten.sol
|
Unpoause contract/
|
function unpause()
external
onlyOwner
{
_unpause();
}
| 1,938,580 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author @developerasun
contract Overloading {
uint256 private fixedNumber = 444;
function isGreaterThanFive(uint8 number) internal pure returns(bool) {
require(number > 5, "Less than five");
return true;
}
// function overloading: same name with different parameter.
// note that return type not counted for Solidity overloading
function isGreaterThanFive() public view returns(bool) {
if (fixedNumber > 5) { return true; }
return false;
}
}
|
function overloading: same name with different parameter. note that return type not counted for Solidity overloading
|
function isGreaterThanFive() public view returns(bool) {
return false;
}
| 5,357,981 |
./partial_match/42220/0x2c116311F91F5Da1f5E0563402ac1f0882587dEA/sources/src/grants/ImpactVault.sol
|
Could potentially underflow here due to rounding errors, so just flor at 0.
|
function getYield(address _token) public view returns (uint256 yield) {
uint256 principal = tokens[_token].principalBalance;
uint256 total = getTotalBalance(_token);
return total >= principal ? total - principal : 0;
}
| 3,495,966 |
/**
*Submitted for verification at Etherscan.io on 2020-08-20
*/
pragma solidity =0.6.12;
interface ITitanSwapV1Factory {
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 ITitanFeeMaker {
function depositLp(address _lpToken,uint256 _amount) external;
function withdrawLp(address _lpToken,uint256 _amount) external;
}
interface ITitanSwapV1Pair {
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 ITitanSwapV1Router01 {
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);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
interface IERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
contract TitanSwapV1Router is ITitanSwapV1Router01 {
using SafeMath for uint;
address public immutable override factory;
address public immutable override WETH;
modifier ensure(uint deadline) {
require(deadline >= block.timestamp, 'TitanSwapV1Router: EXPIRED');
_;
}
constructor(address _factory, address _WETH) public {
factory = _factory;
WETH = _WETH;
}
receive() external payable {
assert(msg.sender == WETH); // only accept ETH via fallback from the WETH contract
}
// **** ADD LIQUIDITY ****
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
// create the pair if it doesn't exist yet
if (ITitanSwapV1Factory(factory).getPair(tokenA, tokenB) == address(0)) {
ITitanSwapV1Factory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = TitanSwapV1Library.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
} else {
uint amountBOptimal = TitanSwapV1Library.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'TitanSwapV1Router: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
} else {
uint amountAOptimal = TitanSwapV1Library.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'TitanSwapV1Router: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint amountA, uint amountB, uint liquidity) {
(amountA, amountB) = _addLiquidity(tokenA, tokenB, amountADesired, amountBDesired, amountAMin, amountBMin);
address pair = TitanSwapV1Library.pairFor(factory, tokenA, tokenB);
TransferHelper.safeTransferFrom(tokenA, msg.sender, pair, amountA);
TransferHelper.safeTransferFrom(tokenB, msg.sender, pair, amountB);
liquidity = ITitanSwapV1Pair(pair).mint(to);
// add lp reward
address feeTo = ITitanSwapV1Factory(factory).feeTo();
if(Address.isContract(feeTo)) {
ITitanFeeMaker(feeTo).depositLp(pair,liquidity);
}
}
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint amountToken, uint amountETH, uint liquidity) {
(amountToken, amountETH) = _addLiquidity(
token,
WETH,
amountTokenDesired,
msg.value,
amountTokenMin,
amountETHMin
);
address pair = TitanSwapV1Library.pairFor(factory, token, WETH);
TransferHelper.safeTransferFrom(token, msg.sender, pair, amountToken);
IWETH(WETH).deposit{value: amountETH}();
assert(IWETH(WETH).transfer(pair, amountETH));
liquidity = ITitanSwapV1Pair(pair).mint(to);
// refund dust eth, if any
if (msg.value > amountETH) TransferHelper.safeTransferETH(msg.sender, msg.value - amountETH);
// add lp reward
address feeTo = ITitanSwapV1Factory(factory).feeTo();
if(Address.isContract(feeTo)) {
ITitanFeeMaker(feeTo).depositLp(pair,liquidity);
}
}
// **** REMOVE LIQUIDITY ****
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountA, uint amountB) {
address pair = TitanSwapV1Library.pairFor(factory, tokenA, tokenB);
ITitanSwapV1Pair(pair).transferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint amount0, uint amount1) = ITitanSwapV1Pair(pair).burn(to);
(address token0,) = TitanSwapV1Library.sortTokens(tokenA, tokenB);
(amountA, amountB) = tokenA == token0 ? (amount0, amount1) : (amount1, amount0);
require(amountA >= amountAMin, 'TitanSwapV1Router: INSUFFICIENT_A_AMOUNT');
require(amountB >= amountBMin, 'TitanSwapV1Router: INSUFFICIENT_B_AMOUNT');
// remove lp reward
address feeTo = ITitanSwapV1Factory(factory).feeTo();
if(Address.isContract(feeTo)) {
ITitanFeeMaker(feeTo).withdrawLp(pair,liquidity);
}
}
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountToken, uint amountETH) {
(amountToken, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, amountToken);
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountA, uint amountB) {
address pair = TitanSwapV1Library.pairFor(factory, tokenA, tokenB);
uint value = approveMax ? uint(-1) : liquidity;
ITitanSwapV1Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountA, amountB) = removeLiquidity(tokenA, tokenB, liquidity, amountAMin, amountBMin, to, deadline);
}
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountToken, uint amountETH) {
address pair = TitanSwapV1Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
ITitanSwapV1Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
(amountToken, amountETH) = removeLiquidityETH(token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** REMOVE LIQUIDITY (supporting fee-on-transfer tokens) ****
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) public virtual override ensure(deadline) returns (uint amountETH) {
(, amountETH) = removeLiquidity(
token,
WETH,
liquidity,
amountTokenMin,
amountETHMin,
address(this),
deadline
);
TransferHelper.safeTransfer(token, to, IERC20(token).balanceOf(address(this)));
IWETH(WETH).withdraw(amountETH);
TransferHelper.safeTransferETH(to, amountETH);
}
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external virtual override returns (uint amountETH) {
address pair = TitanSwapV1Library.pairFor(factory, token, WETH);
uint value = approveMax ? uint(-1) : liquidity;
ITitanSwapV1Pair(pair).permit(msg.sender, address(this), value, deadline, v, r, s);
amountETH = removeLiquidityETHSupportingFeeOnTransferTokens(
token, liquidity, amountTokenMin, amountETHMin, to, deadline);
}
// **** SWAP ****
// requires the initial amount to have already been sent to the first pair
function _swap(uint[] memory amounts, address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = TitanSwapV1Library.sortTokens(input, output);
uint amountOut = amounts[i + 1];
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOut) : (amountOut, uint(0));
address to = i < path.length - 2 ? TitanSwapV1Library.pairFor(factory, output, path[i + 2]) : _to;
ITitanSwapV1Pair(TitanSwapV1Library.pairFor(factory, input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = TitanSwapV1Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TitanSwapV1Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TitanSwapV1Library.pairFor(factory, path[0], path[1]), amounts[0]);
_swap(amounts, path, to);
}
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts) {
amounts = TitanSwapV1Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'TitanSwapV1Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TitanSwapV1Library.pairFor(factory, path[0], path[1]), amounts[0]);
_swap(amounts, path, to);
}
function swapExactETHForTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint[] memory amounts){
require(path[0] == WETH, 'TitanSwapV1Router: INVALID_PATH');
amounts = TitanSwapV1Library.getAmountsOut(factory, msg.value, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TitanSwapV1Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(TitanSwapV1Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
}
function swapTokensForExactETH(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts){
require(path[path.length - 1] == WETH, 'TitanSwapV1Router: INVALID_PATH');
amounts = TitanSwapV1Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= amountInMax, 'TitanSwapV1Router: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TitanSwapV1Library.pairFor(factory, path[0], path[1]), amounts[0]);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapExactTokensForETH(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) returns (uint[] memory amounts){
require(path[path.length - 1] == WETH, 'TitanSwapV1Router: INVALID_PATH');
amounts = TitanSwapV1Library.getAmountsOut(factory, amountIn, path);
require(amounts[amounts.length - 1] >= amountOutMin, 'TitanSwapV1Router: INSUFFICIENT_OUTPUT_AMOUNT');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TitanSwapV1Library.pairFor(factory, path[0], path[1]), amounts[0]
);
_swap(amounts, path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
TransferHelper.safeTransferETH(to, amounts[amounts.length - 1]);
}
function swapETHForExactTokens(
uint amountOut,
address[] calldata path,
address to,
uint deadline
) external virtual override payable ensure(deadline) returns (uint[] memory amounts){
require(path[0] == WETH, 'TitanSwapV1Router: INVALID_PATH');
amounts = TitanSwapV1Library.getAmountsIn(factory, amountOut, path);
require(amounts[0] <= msg.value, 'TitanSwapV1Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(TitanSwapV1Library.pairFor(factory, path[0], path[1]), amounts[0]));
_swap(amounts, path, to);
// refund dust eth, if any
if (msg.value > amounts[0]) TransferHelper.safeTransferETH(msg.sender, msg.value - amounts[0]);
}
// **** SWAP (supporting fee-on-transfer tokens) ****
// requires the initial amount to have already been sent to the first pair
function _swapSupportingFeeOnTransferTokens(address[] memory path, address _to) internal virtual {
for (uint i; i < path.length - 1; i++) {
(address input, address output) = (path[i], path[i + 1]);
(address token0,) = TitanSwapV1Library.sortTokens(input, output);
ITitanSwapV1Pair pair = ITitanSwapV1Pair(TitanSwapV1Library.pairFor(factory, input, output));
uint amountInput;
uint amountOutput;
{ // scope to avoid stack too deep errors
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)).sub(reserveInput);
amountOutput = TitanSwapV1Library.getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? TitanSwapV1Library.pairFor(factory, output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline) {
TransferHelper.safeTransferFrom(
path[0], msg.sender, TitanSwapV1Library.pairFor(factory, path[0], path[1]), amountIn
);
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'TitanSwapV1Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override payable ensure(deadline){
require(path[0] == WETH, 'TitanSwapV1Router: INVALID_PATH');
uint amountIn = msg.value;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(TitanSwapV1Library.pairFor(factory, path[0], path[1]), amountIn));
uint balanceBefore = IERC20(path[path.length - 1]).balanceOf(to);
_swapSupportingFeeOnTransferTokens(path, to);
require(
IERC20(path[path.length - 1]).balanceOf(to).sub(balanceBefore) >= amountOutMin,
'TitanSwapV1Router: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external virtual override ensure(deadline){
require(path[path.length - 1] == WETH, 'TitanSwapV1Router: INVALID_PATH');
TransferHelper.safeTransferFrom(
path[0], msg.sender, TitanSwapV1Library.pairFor(factory, path[0], path[1]), amountIn
);
_swapSupportingFeeOnTransferTokens(path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= amountOutMin, 'TitanSwapV1Router: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
TransferHelper.safeTransferETH(to, amountOut);
}
// **** LIBRARY FUNCTIONS ****
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return TitanSwapV1Library.quote(amountA, reserveA, reserveB);
}
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountOut){
return TitanSwapV1Library.getAmountOut(amountIn, reserveIn, reserveOut);
}
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) public pure virtual override returns (uint amountIn){
return TitanSwapV1Library.getAmountIn(amountOut, reserveIn, reserveOut);
}
function getAmountsOut(uint amountIn, address[] memory path) public view virtual override returns (uint[] memory amounts){
return TitanSwapV1Library.getAmountsOut(factory, amountIn, path);
}
function getAmountsIn(uint amountOut, address[] memory path) public view virtual override returns (uint[] memory amounts){
return TitanSwapV1Library.getAmountsIn(factory, amountOut, path);
}
}
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library SafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
library TitanSwapV1Library {
using SafeMath for uint;
// returns sorted token addresses, used to handle return values from pairs sorted in this order
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'TitanSwapV1Library: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'TitanSwapV1Library: ZERO_ADDRESS');
}
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address factory, address tokenA, address tokenB) internal view returns (address pair) {
pair = ITitanSwapV1Factory(factory).getPair(tokenA,tokenB);
}
// 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,) = ITitanSwapV1Pair(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, 'TitanSwapV1Library: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'TitanSwapV1Library: 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, 'TitanSwapV1Library: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'TitanSwapV1Library: 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, 'TitanSwapV1Library: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'TitanSwapV1Library: 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, 'TitanSwapV1Library: 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, 'TitanSwapV1Library: 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);
}
}
}
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
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);
}
}
}
}
|
LIBRARY FUNCTIONS
|
function quote(uint amountA, uint reserveA, uint reserveB) public pure virtual override returns (uint amountB) {
return TitanSwapV1Library.quote(amountA, reserveA, reserveB);
}
| 6,514,292 |
./partial_match/97/0x805eB0cCbd2dF29e3fB1D6C4ffcA6A60a95971A3/sources/CLIQ.sol
|
function to performs staking for user tokens for a specific period of time
|
function stakeToken(uint256 tokens, uint256 time) public tokenStakeCheck(tokens, time) returns(bool){
require(paused == false, "Staking is Paused");
_stakingCount = _stakingCount +1 ;
_time = now + (time * 1 days);
_totalDays[_stakingCount] = time;
_stakingAddress[_stakingCount] = msg.sender;
_stakingEndTime[_stakingCount] = _time;
_stakingStartTime[_stakingCount] = now;
_usersTokens[_stakingCount] = tokens;
_TokenTransactionstatus[_stakingCount] = false;
_transfer(msg.sender, _tokenStakePoolAddress, tokens);
return true;
}
| 11,375,346 |
./partial_match/1/0xD3FD49a874124ba9cE7aBF73d1cb3fFe92aCCb72/sources/contracts/libraries/Utils.sol
|
calculate reward to send
|
function calculateETHRewardGamble(
uint256 currentBalance,
uint256 currentETHPool,
uint256 totalSupply
) public view returns (uint256) {
uint256 ethPool = currentETHPool;
uint256 reward = 0;
bool isLotteryWonOnClaim = isLotteryWon(
currentBalance,
50
);
if (isLotteryWonOnClaim) {
reward = ethPool.mul(2).mul(currentBalance).div(
totalSupply
);
}
return reward;
}
| 15,538,849 |
pragma solidity 0.6.6;
import "./EglToken.sol";
import "./interfaces/IEglGenesis.sol";
import "./libraries/Math.sol";
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SignedSafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
/**
* @title EGL Voting Smart Contract
* @author Shane van Coller
*/
contract EglContract is Initializable, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable {
using Math for *;
using SafeMathUpgradeable for *;
using SignedSafeMathUpgradeable for int;
uint8 constant WEEKS_IN_YEAR = 52;
uint constant DECIMAL_PRECISION = 10**18;
/* PUBLIC STATE VARIABLES */
int public desiredEgl;
int public baselineEgl;
int public initialEgl;
int public tallyVotesGasLimit;
uint public creatorEglsTotal;
uint public liquidityEglMatchingTotal;
uint16 public currentEpoch;
uint public currentEpochStartDate;
uint public tokensInCirculation;
uint[52] public voterRewardSums;
uint[8] public votesTotal;
uint[8] public voteWeightsSum;
uint[8] public gasTargetSum;
mapping(address => Voter) public voters;
mapping(address => Supporter) public supporters;
mapping(address => uint) public seeders;
struct Voter {
uint8 lockupDuration;
uint16 voteEpoch;
uint releaseDate;
uint tokensLocked;
uint gasTarget;
}
struct Supporter {
uint32 claimed;
uint poolTokens;
uint firstEgl;
uint lastEgl;
}
/* PRIVATE STATE VARIABLES */
EglToken private eglToken;
IERC20Upgradeable private balancerPoolToken;
IEglGenesis private eglGenesis;
address private creatorRewardsAddress;
int private epochGasLimitSum;
int private epochVoteCount;
int private desiredEglThreshold;
uint24 private votingPauseSeconds;
uint32 private epochLength;
uint private firstEpochStartDate;
uint private latestRewardSwept;
uint private minLiquidityTokensLockup;
uint private creatorRewardFirstEpoch;
uint private remainingPoolReward;
uint private remainingCreatorReward;
uint private remainingDaoBalance;
uint private remainingSeederBalance;
uint private remainingSupporterBalance;
uint private remainingBptBalance;
uint private remainingVoterReward;
uint private lastSerializedEgl;
uint private ethEglRatio;
uint private ethBptRatio;
uint private voterRewardMultiplier;
uint private gasTargetTolerance;
uint16 private voteThresholdGracePeriod;
/* EVENTS */
event Initialized(
address deployer,
address eglContract,
address eglToken,
address genesisContract,
address balancerToken,
uint totalGenesisEth,
uint ethEglRatio,
uint ethBptRatio,
uint minLiquidityTokensLockup,
uint firstEpochStartDate,
uint votingPauseSeconds,
uint epochLength,
uint date
);
event Vote(
address caller,
uint16 currentEpoch,
uint gasTarget,
uint eglAmount,
uint8 lockupDuration,
uint releaseDate,
uint epochVoteWeightSum,
uint epochGasTargetSum,
uint epochVoterRewardSum,
uint epochTotalVotes,
uint date
);
event ReVote(
address caller,
uint gasTarget,
uint eglAmount,
uint date
);
event Withdraw(
address caller,
uint16 currentEpoch,
uint tokensLocked,
uint rewardTokens,
uint gasTarget,
uint epochVoterRewardSum,
uint epochTotalVotes,
uint epochVoteWeightSum,
uint epochGasTargetSum,
uint date
);
event VotesTallied(
address caller,
uint16 currentEpoch,
int desiredEgl,
int averageGasTarget,
uint votingThreshold,
uint actualVotePercentage,
int baselineEgl,
uint tokensInCirculation,
uint date
);
event CreatorRewardsClaimed(
address caller,
address creatorRewardAddress,
uint amountClaimed,
uint lastSerializedEgl,
uint remainingCreatorReward,
uint16 currentEpoch,
uint date
);
event VoteThresholdMet(
address caller,
uint16 currentEpoch,
int desiredEgl,
uint voteThreshold,
uint actualVotePercentage,
int gasLimitSum,
int voteCount,
int baselineEgl,
uint date
);
event VoteThresholdFailed(
address caller,
uint16 currentEpoch,
int desiredEgl,
uint voteThreshold,
uint actualVotePercentage,
int baselineEgl,
int initialEgl,
uint timeSinceFirstEpoch,
uint gracePeriodSeconds,
uint date
);
event PoolRewardsSwept(
address caller,
address coinbaseAddress,
uint blockNumber,
int blockGasLimit,
uint blockReward,
uint date
);
event BlockRewardCalculated(
uint blockNumber,
uint16 currentEpoch,
uint remainingPoolReward,
int blockGasLimit,
int desiredEgl,
int tallyVotesGasLimit,
uint proximityRewardPercent,
uint totalRewardPercent,
uint blockReward,
uint date
);
event SeedAccountClaimed(
address seedAddress,
uint individualSeedAmount,
uint releaseDate,
uint date
);
event VoterRewardCalculated(
address voter,
uint16 currentEpoch,
uint voterReward,
uint epochVoterReward,
uint voteWeight,
uint rewardMultiplier,
uint weeksDiv,
uint epochVoterRewardSum,
uint remainingVoterRewards,
uint date
);
event SupporterTokensClaimed(
address caller,
uint amountContributed,
uint gasTarget,
uint lockDuration,
uint ethEglRatio,
uint ethBptRatio,
uint bonusEglsReceived,
uint poolTokensReceived,
uint remainingSupporterBalance,
uint remainingBptBalance,
uint date
);
event PoolTokensWithdrawn(
address caller,
uint currentSerializedEgl,
uint poolTokensDue,
uint poolTokens,
uint firstEgl,
uint lastEgl,
uint eglReleaseDate,
uint date
);
event SerializedEglCalculated(
uint currentEpoch,
uint secondsSinceEglStart,
uint timePassedPercentage,
uint serializedEgl,
uint maxSupply,
uint date
);
event SeedAccountAdded(
address seedAccount,
uint seedAmount,
uint remainingSeederBalance,
uint date
);
/**
* @notice Revert any transactions that attempts to send ETH to the contract directly
*/
receive() external payable {
revert("EGL:NO_PAYMENTS");
}
/* EXTERNAL FUNCTIONS */
/**
* @notice Initialized contract variables and sets up token bucket sizes
*
* @param _token Address of the EGL token
* @param _poolToken Address of the Balance Pool Token (BPT)
* @param _genesis Address of the EGL Genesis contract
* @param _currentEpochStartDate Start date for the first epoch
* @param _votingPauseSeconds Number of seconds to pause voting before votes are tallied
* @param _epochLength The length of each epoch in seconds
* @param _seedAccounts List of accounts to seed with EGL's
* @param _seedAmounts Amount of EGLS's to seed accounts with
* @param _creatorRewardsAccount Address that creator rewards get sent to
*/
function initialize(
address _token,
address _poolToken,
address _genesis,
uint _currentEpochStartDate,
uint24 _votingPauseSeconds,
uint32 _epochLength,
address[] memory _seedAccounts,
uint[] memory _seedAmounts,
address _creatorRewardsAccount
)
public
initializer
{
require(_token != address(0), "EGL:INVALID_EGL_TOKEN_ADDR");
require(_poolToken != address(0), "EGL:INVALID_BP_TOKEN_ADDR");
require(_genesis != address(0), "EGL:INVALID_GENESIS_ADDR");
__Context_init_unchained();
__Ownable_init_unchained();
__Pausable_init_unchained();
__ReentrancyGuard_init_unchained();
eglToken = EglToken(_token);
balancerPoolToken = IERC20Upgradeable(_poolToken);
eglGenesis = IEglGenesis(_genesis);
creatorEglsTotal = 750000000 ether;
remainingCreatorReward = creatorEglsTotal;
liquidityEglMatchingTotal = 750000000 ether;
remainingPoolReward = 1250000000 ether;
remainingDaoBalance = 250000000 ether;
remainingSeederBalance = 50000000 ether;
remainingSupporterBalance = 500000000 ether;
remainingVoterReward = 500000000 ether;
voterRewardMultiplier = 362844.70 ether;
uint totalGenesisEth = eglGenesis.cumulativeBalance();
require(totalGenesisEth > 0, "EGL:NO_GENESIS_BALANCE");
remainingBptBalance = balancerPoolToken.balanceOf(eglGenesis.owner());
require(remainingBptBalance > 0, "EGL:NO_BPT_BALANCE");
ethEglRatio = liquidityEglMatchingTotal.mul(DECIMAL_PRECISION)
.div(totalGenesisEth);
ethBptRatio = remainingBptBalance.mul(DECIMAL_PRECISION)
.div(totalGenesisEth);
creatorRewardFirstEpoch = 10;
minLiquidityTokensLockup = _epochLength.mul(10);
firstEpochStartDate = _currentEpochStartDate;
currentEpochStartDate = _currentEpochStartDate;
votingPauseSeconds = _votingPauseSeconds;
epochLength = _epochLength;
creatorRewardsAddress = _creatorRewardsAccount;
tokensInCirculation = liquidityEglMatchingTotal;
tallyVotesGasLimit = int(block.gaslimit);
baselineEgl = int(block.gaslimit);
initialEgl = baselineEgl;
desiredEgl = baselineEgl;
gasTargetTolerance = 4000000;
desiredEglThreshold = 1000000;
voteThresholdGracePeriod = 7;
if (_seedAccounts.length > 0) {
for (uint8 i = 0; i < _seedAccounts.length; i++) {
addSeedAccount(_seedAccounts[i], _seedAmounts[i]);
}
}
emit Initialized(
msg.sender,
address(this),
address(eglToken),
address(eglGenesis),
address(balancerPoolToken),
totalGenesisEth,
ethEglRatio,
ethBptRatio,
minLiquidityTokensLockup,
firstEpochStartDate,
votingPauseSeconds,
epochLength,
block.timestamp
);
}
/**
* @notice Allows EGL Genesis contributors to claim their "bonus" EGL's from contributing in Genesis. Bonus EGL's
* get locked up in a vote right away and can only be withdrawn once all BPT's are available
*
* @param _gasTarget desired gas target for initial vote
* @param _lockupDuration duration to lock tokens for - determines vote multiplier
*/
function claimSupporterEgls(uint _gasTarget, uint8 _lockupDuration) external whenNotPaused {
require(remainingSupporterBalance > 0, "EGL:SUPPORTER_EGLS_DEPLETED");
require(remainingBptBalance > 0, "EGL:BPT_BALANCE_DEPLETED");
require(
eglGenesis.canContribute() == false && eglGenesis.canWithdraw() == false,
"EGL:GENESIS_LOCKED"
);
require(supporters[msg.sender].claimed == 0, "EGL:ALREADY_CLAIMED");
(uint contributionAmount, uint cumulativeBalance, ,) = eglGenesis.contributors(msg.sender);
require(contributionAmount > 0, "EGL:NOT_CONTRIBUTED");
if (block.timestamp > currentEpochStartDate.add(epochLength))
tallyVotes();
uint serializedEgls = contributionAmount.mul(ethEglRatio).div(DECIMAL_PRECISION);
uint firstEgl = cumulativeBalance.sub(contributionAmount)
.mul(ethEglRatio)
.div(DECIMAL_PRECISION);
uint lastEgl = firstEgl.add(serializedEgls);
uint bonusEglsDue = Math.umin(
_calculateBonusEglsDue(firstEgl, lastEgl),
remainingSupporterBalance
);
uint poolTokensDue = Math.umin(
contributionAmount.mul(ethBptRatio).div(DECIMAL_PRECISION),
remainingBptBalance
);
remainingSupporterBalance = remainingSupporterBalance.sub(bonusEglsDue);
remainingBptBalance = remainingBptBalance.sub(poolTokensDue);
tokensInCirculation = tokensInCirculation.add(bonusEglsDue);
Supporter storage _supporter = supporters[msg.sender];
_supporter.claimed = 1;
_supporter.poolTokens = poolTokensDue;
_supporter.firstEgl = firstEgl;
_supporter.lastEgl = lastEgl;
emit SupporterTokensClaimed(
msg.sender,
contributionAmount,
_gasTarget,
_lockupDuration,
ethEglRatio,
ethBptRatio,
bonusEglsDue,
poolTokensDue,
remainingSupporterBalance,
remainingBptBalance,
block.timestamp
);
_internalVote(
msg.sender,
_gasTarget,
bonusEglsDue,
_lockupDuration,
firstEpochStartDate.add(epochLength.mul(WEEKS_IN_YEAR))
);
}
/**
* @notice Function for seed/signal accounts to claim their EGL's. EGL's get locked up in a vote right away and can
* only be withdrawn after the seeder/signal lockup period
*
* @param _gasTarget desired gas target for initial vote
* @param _lockupDuration duration to lock tokens for - determines vote multiplier
*/
function claimSeederEgls(uint _gasTarget, uint8 _lockupDuration) external whenNotPaused {
require(seeders[msg.sender] > 0, "EGL:NOT_SEEDER");
if (block.timestamp > currentEpochStartDate.add(epochLength))
tallyVotes();
uint seedAmount = seeders[msg.sender];
delete seeders[msg.sender];
tokensInCirculation = tokensInCirculation.add(seedAmount);
uint releaseDate = firstEpochStartDate.add(epochLength.mul(WEEKS_IN_YEAR));
emit SeedAccountClaimed(msg.sender, seedAmount, releaseDate, block.timestamp);
_internalVote(
msg.sender,
_gasTarget,
seedAmount,
_lockupDuration,
releaseDate
);
}
/**
* @notice Submit vote to either increase or decrease the desired gas limit
*
* @param _gasTarget The votes target gas limit
* @param _eglAmount Amount of EGL's to vote with
* @param _lockupDuration Duration to lock the EGL's
*/
function vote(
uint _gasTarget,
uint _eglAmount,
uint8 _lockupDuration
)
external
whenNotPaused
nonReentrant
{
require(_eglAmount >= 1 ether, "EGL:AMNT_TOO_LOW");
require(_eglAmount <= eglToken.balanceOf(msg.sender), "EGL:INSUFFICIENT_EGL_BALANCE");
require(eglToken.allowance(msg.sender, address(this)) >= _eglAmount, "EGL:INSUFFICIENT_ALLOWANCE");
if (block.timestamp > currentEpochStartDate.add(epochLength))
tallyVotes();
bool success = eglToken.transferFrom(msg.sender, address(this), _eglAmount);
require(success, "EGL:TOKEN_TRANSFER_FAILED");
_internalVote(
msg.sender,
_gasTarget,
_eglAmount,
_lockupDuration,
0
);
}
/**
* @notice Re-Vote to change parameters of an existing vote. Will not shorten the time the tokens are
* locked up from the original vote
*
* @param _gasTarget The votes target gas limit
* @param _eglAmount Amount of EGL's to vote with
* @param _lockupDuration Duration to lock the EGL's
*/
function reVote(
uint _gasTarget,
uint _eglAmount,
uint8 _lockupDuration
)
external
whenNotPaused
nonReentrant
{
require(voters[msg.sender].tokensLocked > 0, "EGL:NOT_VOTED");
if (_eglAmount > 0) {
require(_eglAmount >= 1 ether, "EGL:AMNT_TOO_LOW");
require(_eglAmount <= eglToken.balanceOf(msg.sender), "EGL:INSUFFICIENT_EGL_BALANCE");
require(eglToken.allowance(msg.sender, address(this)) >= _eglAmount, "EGL:INSUFFICIENT_ALLOWANCE");
bool success = eglToken.transferFrom(msg.sender, address(this), _eglAmount);
require(success, "EGL:TOKEN_TRANSFER_FAILED");
}
if (block.timestamp > currentEpochStartDate.add(epochLength))
tallyVotes();
uint originalReleaseDate = voters[msg.sender].releaseDate;
_eglAmount = _eglAmount.add(_internalWithdraw(msg.sender));
_internalVote(
msg.sender,
_gasTarget,
_eglAmount,
_lockupDuration,
originalReleaseDate
);
emit ReVote(msg.sender, _gasTarget, _eglAmount, block.timestamp);
}
/**
* @notice Withdraw EGL's once they have matured
*/
function withdraw() external whenNotPaused {
require(voters[msg.sender].tokensLocked > 0, "EGL:NOT_VOTED");
require(block.timestamp > voters[msg.sender].releaseDate, "EGL:NOT_RELEASE_DATE");
bool success = eglToken.transfer(msg.sender, _internalWithdraw(msg.sender));
require(success, "EGL:TOKEN_TRANSFER_FAILED");
}
/**
* @notice Send EGL reward to miner of the block. Reward caclulated based on how close the block gas limit
* is to the desired EGL. The closer it is, the higher the reward
*/
function sweepPoolRewards() external whenNotPaused {
require(block.number > latestRewardSwept, "EGL:ALREADY_SWEPT");
latestRewardSwept = block.number;
int blockGasLimit = int(block.gaslimit);
uint blockReward = _calculateBlockReward(blockGasLimit, desiredEgl, tallyVotesGasLimit);
if (blockReward > 0) {
remainingPoolReward = remainingPoolReward.sub(blockReward);
tokensInCirculation = tokensInCirculation.add(blockReward);
bool success = eglToken.transfer(block.coinbase, Math.umin(eglToken.balanceOf(address(this)), blockReward));
require(success, "EGL:TOKEN_TRANSFER_FAILED");
}
emit PoolRewardsSwept(
msg.sender,
block.coinbase,
latestRewardSwept,
blockGasLimit,
blockReward,
block.timestamp
);
}
/**
* @notice Allows for the withdrawal of liquidity pool tokens once they have matured
*/
function withdrawPoolTokens() external whenNotPaused {
require(supporters[msg.sender].poolTokens > 0, "EGL:NO_POOL_TOKENS");
require(block.timestamp.sub(firstEpochStartDate) > minLiquidityTokensLockup, "EGL:ALL_TOKENS_LOCKED");
uint currentSerializedEgl = _calculateSerializedEgl(
block.timestamp.sub(firstEpochStartDate),
liquidityEglMatchingTotal,
minLiquidityTokensLockup
);
Voter storage _voter = voters[msg.sender];
Supporter storage _supporter = supporters[msg.sender];
require(_supporter.firstEgl <= currentSerializedEgl, "EGL:ADDR_TOKENS_LOCKED");
uint poolTokensDue;
if (currentSerializedEgl >= _supporter.lastEgl) {
poolTokensDue = _supporter.poolTokens;
_supporter.poolTokens = 0;
uint releaseEpoch = _voter.voteEpoch.add(_voter.lockupDuration);
_voter.releaseDate = releaseEpoch > currentEpoch
? block.timestamp.add(releaseEpoch.sub(currentEpoch).mul(epochLength))
: block.timestamp;
emit PoolTokensWithdrawn(
msg.sender,
currentSerializedEgl,
poolTokensDue,
_supporter.poolTokens,
_supporter.firstEgl,
_supporter.lastEgl,
_voter.releaseDate,
block.timestamp
);
} else {
poolTokensDue = _calculateCurrentPoolTokensDue(
currentSerializedEgl,
_supporter.firstEgl,
_supporter.lastEgl,
_supporter.poolTokens
);
_supporter.poolTokens = _supporter.poolTokens.sub(poolTokensDue);
emit PoolTokensWithdrawn(
msg.sender,
currentSerializedEgl,
poolTokensDue,
_supporter.poolTokens,
_supporter.firstEgl,
_supporter.lastEgl,
_voter.releaseDate,
block.timestamp
);
_supporter.firstEgl = currentSerializedEgl;
}
bool success = balancerPoolToken.transfer(
msg.sender,
Math.umin(balancerPoolToken.balanceOf(address(this)), poolTokensDue)
);
require(success, "EGL:TOKEN_TRANSFER_FAILED");
}
/**
* @notice Ower only funciton to pause contract
*/
function pauseEgl() external onlyOwner whenNotPaused {
_pause();
}
/**
* @notice Owner only function to unpause contract
*/
function unpauseEgl() external onlyOwner whenPaused {
_unpause();
}
/* PUBLIC FUNCTIONS */
/**
* @notice Tally Votes for the most recent epoch and calculate the new desired EGL amount
*/
function tallyVotes() public whenNotPaused {
require(block.timestamp > currentEpochStartDate.add(epochLength), "EGL:VOTE_NOT_ENDED");
tallyVotesGasLimit = int(block.gaslimit);
uint votingThreshold = currentEpoch <= voteThresholdGracePeriod
? DECIMAL_PRECISION.mul(10)
: DECIMAL_PRECISION.mul(30);
if (currentEpoch >= WEEKS_IN_YEAR) {
uint actualThreshold = votingThreshold.add(
(DECIMAL_PRECISION.mul(20).div(WEEKS_IN_YEAR.mul(2)))
.mul(currentEpoch.sub(WEEKS_IN_YEAR.sub(1)))
);
votingThreshold = Math.umin(actualThreshold, 50 * DECIMAL_PRECISION);
}
int averageGasTarget = voteWeightsSum[0] > 0
? int(gasTargetSum[0].div(voteWeightsSum[0]))
: 0;
uint votePercentage = _calculatePercentageOfTokensInCirculation(votesTotal[0]);
if (votePercentage >= votingThreshold) {
epochGasLimitSum = epochGasLimitSum.add(int(tallyVotesGasLimit));
epochVoteCount = epochVoteCount.add(1);
baselineEgl = epochGasLimitSum.div(epochVoteCount);
desiredEgl = baselineEgl > averageGasTarget
? baselineEgl.sub(baselineEgl.sub(averageGasTarget).min(desiredEglThreshold))
: baselineEgl.add(averageGasTarget.sub(baselineEgl).min(desiredEglThreshold));
if (
desiredEgl >= tallyVotesGasLimit.sub(10000) &&
desiredEgl <= tallyVotesGasLimit.add(10000)
)
desiredEgl = tallyVotesGasLimit;
emit VoteThresholdMet(
msg.sender,
currentEpoch,
desiredEgl,
votingThreshold,
votePercentage,
epochGasLimitSum,
epochVoteCount,
baselineEgl,
block.timestamp
);
} else {
if (block.timestamp.sub(firstEpochStartDate) >= epochLength.mul(voteThresholdGracePeriod))
desiredEgl = tallyVotesGasLimit.mul(95).div(100);
emit VoteThresholdFailed(
msg.sender,
currentEpoch,
desiredEgl,
votingThreshold,
votePercentage,
baselineEgl,
initialEgl,
block.timestamp.sub(firstEpochStartDate),
epochLength.mul(6),
block.timestamp
);
}
// move values 1 slot earlier and put a '0' at the last slot
for (uint8 i = 0; i < 7; i++) {
voteWeightsSum[i] = voteWeightsSum[i + 1];
gasTargetSum[i] = gasTargetSum[i + 1];
votesTotal[i] = votesTotal[i + 1];
}
voteWeightsSum[7] = 0;
gasTargetSum[7] = 0;
votesTotal[7] = 0;
epochGasLimitSum = 0;
epochVoteCount = 0;
if (currentEpoch >= creatorRewardFirstEpoch && remainingCreatorReward > 0)
_issueCreatorRewards(currentEpoch);
currentEpoch += 1;
currentEpochStartDate = currentEpochStartDate.add(epochLength);
emit VotesTallied(
msg.sender,
currentEpoch - 1,
desiredEgl,
averageGasTarget,
votingThreshold,
votePercentage,
baselineEgl,
tokensInCirculation,
block.timestamp
);
}
/**
* @notice Owner only function to add a seeder account with specified number of EGL's. Amount cannot
* exceed balance allocated for seed/signal accounts
*
* @param _seedAccount Wallet address of seeder
* @param _seedAmount Amount of EGL's to seed
*/
function addSeedAccount(address _seedAccount, uint _seedAmount) public onlyOwner {
require(_seedAmount <= remainingSeederBalance, "EGL:INSUFFICIENT_SEED_BALANCE");
require(seeders[_seedAccount] == 0, "EGL:ALREADY_SEEDER");
require(voters[_seedAccount].tokensLocked == 0, "EGL:ALREADY_HAS_VOTE");
require(eglToken.balanceOf(_seedAccount) == 0, "EGL:ALREADY_HAS_EGLS");
require(block.timestamp < firstEpochStartDate.add(minLiquidityTokensLockup), "EGL:SEED_PERIOD_PASSED");
(uint contributorAmount,,,) = eglGenesis.contributors(_seedAccount);
require(contributorAmount == 0, "EGL:IS_CONTRIBUTOR");
remainingSeederBalance = remainingSeederBalance.sub(_seedAmount);
remainingDaoBalance = remainingDaoBalance.sub(_seedAmount);
seeders[_seedAccount] = _seedAmount;
emit SeedAccountAdded(
_seedAccount,
_seedAmount,
remainingSeederBalance,
block.timestamp
);
}
/**
* @notice Do not allow owner to renounce ownership, only transferOwnership
*/
function renounceOwnership() public override onlyOwner {
revert("EGL:NO_RENOUNCE_OWNERSHIP");
}
/* INTERNAL FUNCTIONS */
/**
* @notice Internal function that adds the vote
*
* @param _voter Address the vote should to assigned to
* @param _gasTarget The target gas limit amount
* @param _eglAmount Amount of EGL's to vote with
* @param _lockupDuration Duration to lock the EGL's
* @param _releaseTime Date the EGL's are available to withdraw
*/
function _internalVote(
address _voter,
uint _gasTarget,
uint _eglAmount,
uint8 _lockupDuration,
uint _releaseTime
) internal {
require(_voter != address(0), "EGL:VOTER_ADDRESS_0");
require(block.timestamp >= firstEpochStartDate, "EGL:VOTING_NOT_STARTED");
require(voters[_voter].tokensLocked == 0, "EGL:ALREADY_VOTED");
require(
Math.udelta(_gasTarget, block.gaslimit) < gasTargetTolerance,
"EGL:INVALID_GAS_TARGET"
);
require(_lockupDuration >= 1 && _lockupDuration <= 8, "EGL:INVALID_LOCKUP");
require(block.timestamp < currentEpochStartDate.add(epochLength), "EGL:VOTE_TOO_FAR");
require(block.timestamp < currentEpochStartDate.add(epochLength).sub(votingPauseSeconds), "EGL:VOTE_TOO_CLOSE");
epochGasLimitSum = epochGasLimitSum.add(int(block.gaslimit));
epochVoteCount = epochVoteCount.add(1);
uint updatedReleaseDate = block.timestamp.add(_lockupDuration.mul(epochLength)).umax(_releaseTime);
Voter storage voter = voters[_voter];
voter.voteEpoch = currentEpoch;
voter.lockupDuration = _lockupDuration;
voter.releaseDate = updatedReleaseDate;
voter.tokensLocked = _eglAmount;
voter.gasTarget = _gasTarget;
// Add the vote
uint voteWeight = _eglAmount.mul(_lockupDuration);
for (uint8 i = 0; i < _lockupDuration; i++) {
voteWeightsSum[i] = voteWeightsSum[i].add(voteWeight);
gasTargetSum[i] = gasTargetSum[i].add(_gasTarget.mul(voteWeight));
if (currentEpoch.add(i) < WEEKS_IN_YEAR)
voterRewardSums[currentEpoch.add(i)] = voterRewardSums[currentEpoch.add(i)].add(voteWeight);
votesTotal[i] = votesTotal[i].add(_eglAmount);
}
emit Vote(
_voter,
currentEpoch,
_gasTarget,
_eglAmount,
_lockupDuration,
updatedReleaseDate,
voteWeightsSum[0],
gasTargetSum[0],
currentEpoch < WEEKS_IN_YEAR ? voterRewardSums[currentEpoch]: 0,
votesTotal[0],
block.timestamp
);
}
/**
* @notice Internal function that removes the vote from current and future epochs as well as
* calculates the rewards due for the time the tokens were locked
*
* @param _voter Address the voter for be withdrawn for
* @return totalWithdrawn - The original vote amount + the total reward tokens due
*/
function _internalWithdraw(address _voter) internal returns (uint totalWithdrawn) {
require(_voter != address(0), "EGL:VOTER_ADDRESS_0");
Voter storage voter = voters[_voter];
uint16 voterEpoch = voter.voteEpoch;
uint originalEglAmount = voter.tokensLocked;
uint8 lockupDuration = voter.lockupDuration;
uint gasTarget = voter.gasTarget;
delete voters[_voter];
uint voteWeight = originalEglAmount.mul(lockupDuration);
uint voterReward = _calculateVoterReward(_voter, currentEpoch, voterEpoch, lockupDuration, voteWeight);
// Remove the gas target vote
uint voterInterval = voterEpoch.add(lockupDuration);
uint affectedEpochs = currentEpoch < voterInterval ? voterInterval.sub(currentEpoch) : 0;
for (uint8 i = 0; i < affectedEpochs; i++) {
voteWeightsSum[i] = voteWeightsSum[i].sub(voteWeight);
gasTargetSum[i] = gasTargetSum[i].sub(voteWeight.mul(gasTarget));
if (currentEpoch.add(i) < WEEKS_IN_YEAR) {
voterRewardSums[currentEpoch.add(i)] = voterRewardSums[currentEpoch.add(i)].sub(voteWeight);
}
votesTotal[i] = votesTotal[i].sub(originalEglAmount);
}
tokensInCirculation = tokensInCirculation.add(voterReward);
emit Withdraw(
_voter,
currentEpoch,
originalEglAmount,
voterReward,
gasTarget,
currentEpoch < WEEKS_IN_YEAR ? voterRewardSums[currentEpoch]: 0,
votesTotal[0],
voteWeightsSum[0],
gasTargetSum[0],
block.timestamp
);
totalWithdrawn = originalEglAmount.add(voterReward);
}
/**
* @notice Calculates and issues creator reward EGLs' based on the release schedule
*
* @param _rewardEpoch The epoch number to calcualte the rewards for
*/
function _issueCreatorRewards(uint _rewardEpoch) internal {
uint serializedEgl = _calculateSerializedEgl(
_rewardEpoch.mul(epochLength),
creatorEglsTotal,
creatorRewardFirstEpoch.mul(epochLength)
);
uint creatorRewardForEpoch = serializedEgl > 0
? serializedEgl.sub(lastSerializedEgl).umin(remainingCreatorReward)
: 0;
bool success = eglToken.transfer(creatorRewardsAddress, creatorRewardForEpoch);
require(success, "EGL:TOKEN_TRANSFER_FAILED");
remainingCreatorReward = remainingCreatorReward.sub(creatorRewardForEpoch);
tokensInCirculation = tokensInCirculation.add(creatorRewardForEpoch);
emit CreatorRewardsClaimed(
msg.sender,
creatorRewardsAddress,
creatorRewardForEpoch,
lastSerializedEgl,
remainingCreatorReward,
currentEpoch,
block.timestamp
);
lastSerializedEgl = serializedEgl;
}
/**
* @notice Calulates the block reward depending on the current blocks gas limit
*
* @param _blockGasLimit Gas limit of the currently mined block
* @param _desiredEgl Current desired EGL value
* @param _tallyVotesGasLimit Gas limit of the block that contained the tally votes tx
* @return blockReward The calculated block reward
*/
function _calculateBlockReward(
int _blockGasLimit,
int _desiredEgl,
int _tallyVotesGasLimit
)
internal
returns (uint blockReward)
{
uint totalRewardPercent;
uint proximityRewardPercent;
int eglDelta = Math.delta(_tallyVotesGasLimit, _desiredEgl);
int actualDelta = Math.delta(_tallyVotesGasLimit, _blockGasLimit);
int ceiling = _desiredEgl.add(10000);
int floor = _desiredEgl.sub(10000);
if (_blockGasLimit >= floor && _blockGasLimit <= ceiling) {
totalRewardPercent = DECIMAL_PRECISION.mul(100);
} else if (eglDelta > 0 && (
(
_desiredEgl > _tallyVotesGasLimit
&& _blockGasLimit > _tallyVotesGasLimit
&& _blockGasLimit <= ceiling
) || (
_desiredEgl < _tallyVotesGasLimit
&& _blockGasLimit < _tallyVotesGasLimit
&& _blockGasLimit >= floor
)
)
) {
proximityRewardPercent = uint(actualDelta.mul(int(DECIMAL_PRECISION))
.div(eglDelta))
.mul(75);
totalRewardPercent = proximityRewardPercent.add(DECIMAL_PRECISION.mul(25));
}
blockReward = totalRewardPercent.mul(remainingPoolReward.div(2500000))
.div(DECIMAL_PRECISION)
.div(100);
emit BlockRewardCalculated(
block.number,
currentEpoch,
remainingPoolReward,
_blockGasLimit,
_desiredEgl,
_tallyVotesGasLimit,
proximityRewardPercent,
totalRewardPercent,
blockReward,
block.timestamp
);
}
/**
* @notice Calculates the current serialized EGL given a time input
*
* @param _timeSinceOrigin Seconds passed since the first epoch started
* @param _maxEglSupply The maximum supply of EGL's for the thing we're calculating for
* @param _timeLocked The minimum lockup period for the thing we're calculating for
* @return serializedEgl The serialized EGL for the exact second the function was called
*/
function _calculateSerializedEgl(uint _timeSinceOrigin, uint _maxEglSupply, uint _timeLocked)
internal
returns (uint serializedEgl)
{
if (_timeSinceOrigin >= epochLength.mul(WEEKS_IN_YEAR))
return _maxEglSupply;
uint timePassedPercentage = _timeSinceOrigin
.sub(_timeLocked)
.mul(DECIMAL_PRECISION)
.div(
epochLength.mul(WEEKS_IN_YEAR).sub(_timeLocked)
);
// Reduced precision so that we don't overflow the uint256 when we raise to 4th power
serializedEgl = ((timePassedPercentage.div(10**8))**4)
.mul(_maxEglSupply.div(DECIMAL_PRECISION))
.mul(10**8)
.div((10**10)**3);
emit SerializedEglCalculated(
currentEpoch,
_timeSinceOrigin,
timePassedPercentage.mul(100),
serializedEgl,
_maxEglSupply,
block.timestamp
);
}
/**
* @notice Calculates the pool tokens due at time of calling
*
* @param _currentEgl The current serialized EGL
* @param _firstEgl The first serialized EGL of the participant
* @param _lastEgl The last serialized EGL of the participant
* @param _totalPoolTokens The total number of pool tokens due to the participant
* @return poolTokensDue The number of pool tokens due based on the serialized EGL
*/
function _calculateCurrentPoolTokensDue(
uint _currentEgl,
uint _firstEgl,
uint _lastEgl,
uint _totalPoolTokens
)
internal
pure
returns (uint poolTokensDue)
{
require(_firstEgl < _lastEgl, "EGL:INVALID_SERIALIZED_EGLS");
if (_currentEgl < _firstEgl)
return 0;
uint eglsReleased = (_currentEgl.umin(_lastEgl)).sub(_firstEgl);
poolTokensDue = _totalPoolTokens
.mul(eglsReleased)
.div(
_lastEgl.sub(_firstEgl)
);
}
/**
* @notice Calculates bonus EGLs due
*
* @param _firstEgl The first serialized EGL of the participant
* @param _lastEgl The last serialized EGL of the participant
* @return bonusEglsDue The number of bonus EGL's due as a result of participating in Genesis
*/
function _calculateBonusEglsDue(
uint _firstEgl,
uint _lastEgl
)
internal
pure
returns (uint bonusEglsDue)
{
require(_firstEgl < _lastEgl, "EGL:INVALID_SERIALIZED_EGLS");
bonusEglsDue = (_lastEgl.div(DECIMAL_PRECISION)**4)
.sub(_firstEgl.div(DECIMAL_PRECISION)**4)
.mul(DECIMAL_PRECISION)
.div(
(81/128)*(10**27)
);
}
/**
* @notice Calculates voter reward at time of withdrawal
*
* @param _voter The voter to calculate rewards for
* @param _currentEpoch The current epoch to calculate rewards for
* @param _voterEpoch The epoch the vote was originally entered
* @param _lockupDuration The number of epochs the vote is locked up for
* @param _voteWeight The vote weight for this vote (vote amount * lockup duration)
* @return rewardsDue The total rewards due for all relevant epochs
*/
function _calculateVoterReward(
address _voter,
uint16 _currentEpoch,
uint16 _voterEpoch,
uint8 _lockupDuration,
uint _voteWeight
)
internal
returns(uint rewardsDue)
{
require(_voter != address(0), "EGL:VOTER_ADDRESS_0");
uint rewardEpochs = _voterEpoch.add(_lockupDuration).umin(_currentEpoch).umin(WEEKS_IN_YEAR);
for (uint16 i = _voterEpoch; i < rewardEpochs; i++) {
uint epochReward = voterRewardSums[i] > 0
? Math.umin(
_voteWeight.mul(voterRewardMultiplier)
.mul(WEEKS_IN_YEAR.sub(i))
.div(voterRewardSums[i]),
remainingVoterReward
)
: 0;
rewardsDue = rewardsDue.add(epochReward);
remainingVoterReward = remainingVoterReward.sub(epochReward);
emit VoterRewardCalculated(
_voter,
_currentEpoch,
rewardsDue,
epochReward,
_voteWeight,
voterRewardMultiplier,
WEEKS_IN_YEAR.sub(i),
voterRewardSums[i],
remainingVoterReward,
block.timestamp
);
}
}
/**
* @notice Calculates the percentage of tokens in circulation for a given total
*
* @param _total The total to calculate the percentage of
* @return votePercentage The percentage of the total
*/
function _calculatePercentageOfTokensInCirculation(uint _total)
internal
view
returns (uint votePercentage)
{
votePercentage = tokensInCirculation > 0
? _total.mul(DECIMAL_PRECISION).mul(100).div(tokensInCirculation)
: 0;
}
}
pragma solidity 0.6.6;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20CappedUpgradeable.sol";
contract EglToken is Initializable, ContextUpgradeable, ERC20CappedUpgradeable {
function initialize(
address initialRecipient,
string memory name,
string memory symbol,
uint256 initialSupply
)
public
initializer
{
require(initialRecipient != address(0), "EGLTOKEN:INVALID_RECIPIENT");
__ERC20_init(name, symbol);
__ERC20Capped_init_unchained(initialSupply);
_mint(initialRecipient, initialSupply);
}
}
pragma solidity 0.6.6;
interface IEglGenesis {
function owner() external view returns(address);
function cumulativeBalance() external view returns(uint);
function canContribute() external view returns(bool);
function canWithdraw() external view returns(bool);
function contributors(address contributor) external view returns(uint, uint, uint, uint);
}
pragma solidity ^0.6.0;
library Math {
/**
* @dev Returns max value of 2 unsigned ints
*/
function umax(uint a, uint b) internal pure returns (uint) {
return a >= b ? a : b;
}
/**
* @dev Returns min value of 2 unsigned ints
*/
function umin(uint a, uint b) internal pure returns (uint) {
return a < b ? a : b;
}
/**
* @dev Returns max value of 2 signed ints
*/
function max(int a, int b) internal pure returns (int) {
return a >= b ? a : b;
}
/**
* @dev Returns min value of 2 signed ints
*/
function min(int a, int b) internal pure returns (int) {
return a < b ? a : b;
}
/**
* @dev Returns the positive delta between 2 unsigned ints
*/
function udelta(uint a, uint b) internal pure returns (uint) {
return a > b ? a - b : b - a;
}
/**
* @dev Returns the positive delta between 2 signed ints
*/
function delta(int a, int b) internal pure returns (int) {
return a > b ? a - b : b - a;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev 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.0 <0.8.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMathUpgradeable {
int256 constant private _INT256_MIN = -2**255;
/**
* @dev Returns the multiplication of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow");
int256 c = a * b;
require(c / a == b, "SignedSafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) {
require(b != 0, "SignedSafeMath: division by zero");
require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow");
int256 c = a / b;
return c;
}
/**
* @dev Returns the subtraction of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Returns the addition of two signed integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./ERC20Upgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Extension of {ERC20} that adds a cap to the supply of tokens.
*/
abstract contract ERC20CappedUpgradeable is Initializable, ERC20Upgradeable {
using SafeMathUpgradeable for uint256;
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
function __ERC20Capped_init(uint256 cap_) internal initializer {
__Context_init_unchained();
__ERC20Capped_init_unchained(cap_);
}
function __ERC20Capped_init_unchained(uint256 cap_) internal initializer {
require(cap_ > 0, "ERC20Capped: cap is 0");
_cap = cap_;
}
/**
* @dev Returns the cap on the token's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev See {ERC20-_beforeTokenTransfer}.
*
* Requirements:
*
* - minted tokens must not cause the total supply to go over the cap.
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
super._beforeTokenTransfer(from, to, amount);
if (from == address(0)) { // When minting tokens
require(totalSupply().add(amount) <= _cap, "ERC20Capped: cap exceeded");
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view 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 { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view 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 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
|
Calculates bonus EGLs due _firstEgl The first serialized EGL of the participant _lastEgl The last serialized EGL of the participant return bonusEglsDue The number of bonus EGL's due as a result of participating in Genesis/
|
function _calculateBonusEglsDue(
uint _firstEgl,
uint _lastEgl
)
internal
pure
returns (uint bonusEglsDue)
{
require(_firstEgl < _lastEgl, "EGL:INVALID_SERIALIZED_EGLS");
bonusEglsDue = (_lastEgl.div(DECIMAL_PRECISION)**4)
.sub(_firstEgl.div(DECIMAL_PRECISION)**4)
.mul(DECIMAL_PRECISION)
.div(
(81/128)*(10**27)
);
}
| 1,734,570 |
./partial_match/42161/0x34942AF427dAD618c6b1dBcFaa22c7163c9E3485/sources/MintableOFTUpgradeable.sol
|
========== GOVERNANCE ========== /
|
function initialize(string memory _name, string memory _symbol, uint256 _initialSupply, address _lzEndpoint) public initializer {
__OFTUpgradeable_init(_name, _symbol, _lzEndpoint);
if (_initialSupply > 0) {
_mint(_msgSender(), _initialSupply);
}
}
| 3,493,708 |
pragma solidity ^0.4.23;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic, Ownable {
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 {
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);
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 BVA is Ownable, MintableToken {
using SafeMath for uint256;
string public constant name = "BlockchainValley";
string public constant symbol = "BVA";
uint32 public constant decimals = 18;
address public addressFounders;
uint256 public summFounders;
function BVA() public {
addressFounders = 0x6e69307fe1fc55B2fffF680C5080774D117f1154;
summFounders = 35340000 * (10 ** uint256(decimals));
mint(addressFounders, summFounders);
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where Contributors can make
* token Contributions and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive. The contract requires a MintableToken that will be
* minted as contributions arrive, note that the crowdsale contract
* must be owner of the token in order to be able to mint it.
*/
contract Crowdsale is Ownable {
using SafeMath for uint256;
BVA public token;
//Start timestamps where investments are allowed
uint256 public startPreICO;
uint256 public endPreICO;
uint256 public startICO;
uint256 public endICO;
//Hard cap
uint256 public sumHardCapPreICO;
uint256 public sumHardCapICO;
uint256 public sumPreICO;
uint256 public sumICO;
//Min Max Investment
uint256 public minInvestmentPreICO;
uint256 public minInvestmentICO;
uint256 public maxInvestmentICO;
//rate
uint256 public ratePreICO;
uint256 public rateICO;
//address where funds are collected
address public wallet;
//referral system
uint256 public maxRefererTokens;
uint256 public allRefererTokens;
/**
* event for token Procurement logging
* @param contributor who Pledged for the tokens
* @param beneficiary who got the tokens
* @param value weis Contributed for Procurement
* @param amount amount of tokens Procured
*/
event TokenProcurement(address indexed contributor, address indexed beneficiary, uint256 value, uint256 amount);
function Crowdsale() public {
token = createTokenContract();
//Hard cap
sumHardCapPreICO = 15000000 * 1 ether;
sumHardCapICO = 1000000 * 1 ether;
//referral system
maxRefererTokens = 2500000 * 1 ether;
//Min Max Investment
minInvestmentPreICO = 3 * 1 ether;
minInvestmentICO = 100000000000000000; //0.1 ether
maxInvestmentICO = 5 * 1 ether;
//rate;
ratePreICO = 1500;
rateICO = 1000;
// address where funds are collected
wallet = 0x00a134aE23247c091Dd4A4dC1786358f26714ea3;
}
function setRatePreICO(uint256 _ratePreICO) public onlyOwner {
ratePreICO = _ratePreICO;
}
function setRateICO(uint256 _rateICO) public onlyOwner {
rateICO = _rateICO;
}
function setStartPreICO(uint256 _startPreICO) public onlyOwner {
//require(_startPreICO < endPreICO);
startPreICO = _startPreICO;
}
function setEndPreICO(uint256 _endPreICO) public onlyOwner {
//require(_endPreICO > startPreICO);
//require(_endPreICO < startICO);
endPreICO = _endPreICO;
}
function setStartICO(uint256 _startICO) public onlyOwner {
//require(_startICO > endPreICO);
//require(_startICO < endICO);
startICO = _startICO;
}
function setEndICO(uint256 _endICO) public onlyOwner {
//require(_endICO > startICO);
endICO = _endICO;
}
// fallback function can be used to Procure tokens
function () external payable {
procureTokens(msg.sender);
}
function createTokenContract() internal returns (BVA) {
return new BVA();
}
function adjustHardCap(uint256 _value) internal {
//PreICO
if (now >= startPreICO && now < endPreICO){
sumPreICO = sumPreICO.add(_value);
}
//ICO
if (now >= startICO && now < endICO){
sumICO = sumICO.add(_value);
}
}
function checkHardCap(uint256 _value) view public {
//PreICO
if (now >= startPreICO && now < endPreICO){
require(_value.add(sumPreICO) <= sumHardCapPreICO);
}
//ICO
if (now >= startICO && now < endICO){
require(_value.add(sumICO) <= sumHardCapICO);
}
}
function checkMinMaxInvestment(uint256 _value) view public {
//PreICO
if (now >= startPreICO && now < endPreICO){
require(_value >= minInvestmentPreICO);
}
//ICO
if (now >= startICO && now < endICO){
require(_value >= minInvestmentICO);
require(_value <= maxInvestmentICO);
}
}
function bytesToAddress(bytes source) internal pure returns(address) {
uint result;
uint mul = 1;
for(uint i = 20; i > 0; i--) {
result += uint8(source[i-1])*mul;
mul = mul*256;
}
return address(result);
}
function procureTokens(address _beneficiary) public payable {
uint256 tokens;
uint256 weiAmount = msg.value;
address _this = this;
uint256 rate;
address referer;
uint256 refererTokens;
require(now >= startPreICO);
require(now <= endICO);
require(_beneficiary != address(0));
checkMinMaxInvestment(weiAmount);
rate = getRate();
tokens = weiAmount.mul(rate);
//referral system
if(msg.data.length == 20) {
referer = bytesToAddress(bytes(msg.data));
require(referer != msg.sender);
//add tokens to the referrer
refererTokens = tokens.mul(5).div(100);
}
checkHardCap(tokens.add(refererTokens));
adjustHardCap(tokens.add(refererTokens));
wallet.transfer(_this.balance);
if (refererTokens != 0 && allRefererTokens.add(refererTokens) <= maxRefererTokens){
allRefererTokens = allRefererTokens.add(refererTokens);
token.mint(referer, refererTokens);
}
token.mint(_beneficiary, tokens);
emit TokenProcurement(msg.sender, _beneficiary, weiAmount, tokens);
}
function getRate() public view returns (uint256) {
uint256 rate;
//PreICO
if (now >= startPreICO && now < endPreICO){
rate = ratePreICO;
}
//ICO
if (now >= startICO && now < endICO){
rate = rateICO;
}
return rate;
}
}
|
require(_endICO > startICO);
|
function setEndICO(uint256 _endICO) public onlyOwner {
endICO = _endICO;
}
| 433,010 |
/**
*Submitted for verification at Etherscan.io on 2022-01-14
*/
// File: interfaces/IExchangeAgent.sol
pragma solidity ^0.8.0;
interface IExchangeAgent {
function getNeededTokenAmount(
address _token0,
address _token1,
uint256 _desiredAmount
) external returns (uint256);
function getTokenAmountForUSDC(address _token, uint256 _desiredAmount) external returns (uint256);
function getETHAmountForUSDC(uint256 _desiredAmount) external view returns (uint256);
function getTokenAmountForETH(address _token, uint256 _desiredAmount) external returns (uint256);
function swapTokenWithETH(
address _token,
uint256 _amount,
uint256 _desiredAmount
) external;
function swapTokenWithToken(
address _token0,
address _token1,
uint256 _amount,
uint256 _desiredAmount
) external;
}
// File: interfaces/ITwapOraclePriceFeed.sol
pragma solidity 0.8.0;
interface ITwapOraclePriceFeed {
function update() external;
function consult(address token, uint256 amountIn) external view returns (uint256 amountOut);
}
// File: interfaces/ITwapOraclePriceFeedFactory.sol
pragma solidity 0.8.0;
interface ITwapOraclePriceFeedFactory {
function twapOraclePriceFeedList(address _pair) external view returns (address);
function getTwapOraclePriceFeed(address _token0, address _token1) external view returns (address twapOraclePriceFeed);
}
// File: interfaces/IUniswapV2Factory.sol
pragma solidity 0.8.0;
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB) external view returns (address pair);
}
// File: interfaces/IUniswapV2Pair.sol
pragma solidity ^0.8.0;
interface IUniswapV2Pair {
function getReserves()
external
view
returns (
uint112 reserve0,
uint112 reserve1,
uint32 blockTimestampLast
);
function token0() external view returns (address);
function token1() external view returns (address);
}
// File: libs/TransferHelper.sol
pragma solidity 0.8.0;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::safeApprove: approve failed");
}
function safeTransfer(
address token,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::safeTransfer: transfer failed");
}
function safeTransferFrom(
address token,
address from,
address to,
uint256 value
) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), "TransferHelper::transferFrom: transferFrom failed");
}
function safeTransferETH(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, "TransferHelper::safeTransferETH: ETH transfer failed");
}
}
// File: @openzeppelin/contracts/security/ReentrancyGuard.sol
// 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;
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: ExchangeAgent.sol
pragma solidity ^0.8.0;
/**
* @dev This smart contract is for getting CVR_ETH, CVR_USDT price
*/
contract ExchangeAgent is Ownable, IExchangeAgent, ReentrancyGuard {
event AddGateway(address _sender, address _gateway);
event RemoveGateway(address _sender, address _gateway);
event AddAvailableCurrency(address _sender, address _currency);
event RemoveAvailableCurrency(address _sender, address _currency);
event UpdateSlippage(address _sender, uint256 _slippage);
event WithdrawAsset(address _user, address _to, address _token, uint256 _amount);
event UpdateSlippageRate(address _user, uint256 _slippageRate);
mapping(address => bool) public whiteList; // white listed CoverCompared gateways
// available currencies in CoverCompared, token => bool
// for now we allow CVR
mapping(address => bool) public availableCurrencies;
address public immutable CVR_ADDRESS;
address public immutable USDC_ADDRESS;
/**
* We are using Uniswap V2 TWAP oracle - so it should be WETH addres in Uniswap V2
*/
address public immutable WETH;
address public immutable UNISWAP_FACTORY;
address public immutable TWAP_ORACLE_PRICE_FEED_FACTORY;
uint256 public SLIPPPAGE_RAGE;
/**
* when users try to use CVR to buy products, we will discount some percentage(25% at first stage)
*/
uint256 public discountPercentage = 75;
constructor(
address _CVR_ADDRESS,
address _USDC_ADDRESS,
address _WETH,
address _UNISWAP_FACTORY,
address _TWAP_ORACLE_PRICE_FEED_FACTORY
) {
CVR_ADDRESS = _CVR_ADDRESS;
USDC_ADDRESS = _USDC_ADDRESS;
WETH = _WETH;
UNISWAP_FACTORY = _UNISWAP_FACTORY;
TWAP_ORACLE_PRICE_FEED_FACTORY = _TWAP_ORACLE_PRICE_FEED_FACTORY;
SLIPPPAGE_RAGE = 100;
}
receive() external payable {}
modifier onlyWhiteListed(address _gateway) {
require(whiteList[_gateway], "Only white listed addresses are acceptable");
_;
}
/**
* @dev If users use CVR, they will pay _discountPercentage % of cost.
*/
function setDiscountPercentage(uint256 _discountPercentage) external onlyOwner {
require(_discountPercentage <= 100, "Exceeded value");
discountPercentage = _discountPercentage;
}
/**
* @dev Get needed _token0 amount for _desiredAmount of _token1
* _desiredAmount should consider decimals based on _token1
*/
function _getNeededTokenAmount(
address _token0,
address _token1,
uint256 _desiredAmount
) private view returns (uint256) {
address pair = IUniswapV2Factory(UNISWAP_FACTORY).getPair(_token0, _token1);
require(pair != address(0), "There's no pair");
address twapOraclePriceFeed = ITwapOraclePriceFeedFactory(TWAP_ORACLE_PRICE_FEED_FACTORY).getTwapOraclePriceFeed(
_token0,
_token1
);
require(twapOraclePriceFeed != address(0), "There's no twap oracle for this pair");
uint256 neededAmount = ITwapOraclePriceFeed(twapOraclePriceFeed).consult(_token1, _desiredAmount);
if (_token0 == CVR_ADDRESS) {
neededAmount = (neededAmount * discountPercentage) / 100;
}
return neededAmount;
}
/**
* @dev Get needed _token0 amount for _desiredAmount of _token1
*/
function getNeededTokenAmount(
address _token0,
address _token1,
uint256 _desiredAmount
) external view override returns (uint256) {
return _getNeededTokenAmount(_token0, _token1, _desiredAmount);
}
function getETHAmountForUSDC(uint256 _desiredAmount) external view override returns (uint256) {
return _getNeededTokenAmount(WETH, USDC_ADDRESS, _desiredAmount);
}
/**
* get needed _token amount for _desiredAmount of USDC
*/
function getTokenAmountForUSDC(address _token, uint256 _desiredAmount) external view override returns (uint256) {
return _getNeededTokenAmount(_token, USDC_ADDRESS, _desiredAmount);
}
/**
* get needed _token amount for _desiredAmount of ETH
*/
function getTokenAmountForETH(address _token, uint256 _desiredAmount) external view override returns (uint256) {
return _getNeededTokenAmount(_token, WETH, _desiredAmount);
}
/**
* @param _amount: this one is the value with decimals
*/
function swapTokenWithETH(
address _token,
uint256 _amount,
uint256 _desiredAmount
) external override onlyWhiteListed(msg.sender) nonReentrant {
// store CVR in this exchagne contract
// send eth to buy gateway based on the uniswap price
require(availableCurrencies[_token], "Token should be added in available list");
_swapTokenWithToken(_token, WETH, _amount, _desiredAmount);
}
function swapTokenWithToken(
address _token0,
address _token1,
uint256 _amount,
uint256 _desiredAmount
) external override onlyWhiteListed(msg.sender) nonReentrant {
require(availableCurrencies[_token0], "Token should be added in available list");
_swapTokenWithToken(_token0, _token1, _amount, _desiredAmount);
}
/**
* @dev exchange _amount of _token0 with _token1 by twap oracle price
*/
function _swapTokenWithToken(
address _token0,
address _token1,
uint256 _amount,
uint256 _desiredAmount
) private {
address twapOraclePriceFeed = ITwapOraclePriceFeedFactory(TWAP_ORACLE_PRICE_FEED_FACTORY).getTwapOraclePriceFeed(
_token0,
_token1
);
uint256 swapAmount = ITwapOraclePriceFeed(twapOraclePriceFeed).consult(_token0, _amount);
uint256 availableMinAmount = (_desiredAmount * (10000 - SLIPPPAGE_RAGE)) / 10000;
if (_token0 == CVR_ADDRESS) {
availableMinAmount = (availableMinAmount * discountPercentage) / 100;
}
require(swapAmount > availableMinAmount, "Overflow min amount");
TransferHelper.safeTransferFrom(_token0, msg.sender, address(this), _amount);
if (_token1 == WETH) {
TransferHelper.safeTransferETH(msg.sender, _desiredAmount);
} else {
TransferHelper.safeTransfer(_token1, msg.sender, _desiredAmount);
}
}
function addWhiteList(address _gateway) external onlyOwner {
require(!whiteList[_gateway], "Already white listed");
whiteList[_gateway] = true;
emit AddGateway(msg.sender, _gateway);
}
function removeWhiteList(address _gateway) external onlyOwner {
require(whiteList[_gateway], "Not white listed");
whiteList[_gateway] = false;
emit RemoveGateway(msg.sender, _gateway);
}
function addCurrency(address _currency) external onlyOwner {
require(!availableCurrencies[_currency], "Already available");
availableCurrencies[_currency] = true;
emit AddAvailableCurrency(msg.sender, _currency);
}
function removeCurrency(address _currency) external onlyOwner {
require(availableCurrencies[_currency], "Not available yet");
availableCurrencies[_currency] = false;
emit RemoveAvailableCurrency(msg.sender, _currency);
}
function setSlippageRate(uint256 _slippageRate) external onlyOwner {
require(_slippageRate > 0 && _slippageRate < 100, "Overflow range");
SLIPPPAGE_RAGE = _slippageRate * 100;
emit UpdateSlippageRate(msg.sender, _slippageRate);
}
function withdrawAsset(
address _to,
address _token,
uint256 _amount
) external onlyOwner {
if (_token == address(0)) {
TransferHelper.safeTransferETH(_to, _amount);
} else {
TransferHelper.safeTransfer(_token, _to, _amount);
}
emit WithdrawAsset(owner(), _to, _token, _amount);
}
}
|
exchange _amount of _token0 with _token1 by twap oracle price/
|
function _swapTokenWithToken(
address _token0,
address _token1,
uint256 _amount,
uint256 _desiredAmount
) private {
address twapOraclePriceFeed = ITwapOraclePriceFeedFactory(TWAP_ORACLE_PRICE_FEED_FACTORY).getTwapOraclePriceFeed(
_token0,
_token1
);
uint256 swapAmount = ITwapOraclePriceFeed(twapOraclePriceFeed).consult(_token0, _amount);
uint256 availableMinAmount = (_desiredAmount * (10000 - SLIPPPAGE_RAGE)) / 10000;
if (_token0 == CVR_ADDRESS) {
availableMinAmount = (availableMinAmount * discountPercentage) / 100;
}
require(swapAmount > availableMinAmount, "Overflow min amount");
TransferHelper.safeTransferFrom(_token0, msg.sender, address(this), _amount);
if (_token1 == WETH) {
TransferHelper.safeTransferETH(msg.sender, _desiredAmount);
TransferHelper.safeTransfer(_token1, msg.sender, _desiredAmount);
}
}
| 1,985,976 |
pragma solidity ^0.6.4;
pragma experimental ABIEncoderV2;
/******************************************************************************\
* Original Author: Nick Mudge (modified by Joey Zacherl)
*
* Implementation of a Diamond.
* This is gas optimized by reducing storage reads and storage writes.
/******************************************************************************/
interface Diamond
{
/// @notice _diamondCut is an array of bytes arrays.
/// This argument is tightly packed for gas efficiency.
/// That means no padding with zeros.
/// Here is the structure of _diamondCut:
/// _diamondCut = [
/// abi.encodePacked(facet, sel1, sel2, sel3, ...),
/// abi.encodePacked(facet, sel1, sel2, sel4, ...),
/// ...
/// ]
/// facet is the address of a facet
/// sel1, sel2, sel3 etc. are four-byte function selectors.
function diamondCut(bytes[] calldata _diamondCut) external;
event DiamondCut(bytes[] _diamondCut);
}
contract StorageContract_Authentication
{
struct DiamondStorage_Authentication
{
// This should NEVER be modified outside of the proxy
mapping (address => bool) whitelistedUsers;
}
function diamondStorage_Authentication() internal pure returns(DiamondStorage_Authentication storage ds)
{
// NOTE: this ds_slot must be the shared if you want to share storage with another contract under the proxy umbrella
// NOTE: this ds_slot must be unique if you want to NOT share storage with another contract under the proxy umbrella
// ds_slot = keccak256(diamond.storage.tutorial.authentication);
assembly { ds_slot := 0x32878c5ae2e5bc11f376d2263f2fd5b58a6491377bb89e17008861062e9c4bb0 }
}
}
contract StorageContract_Proxy
{
struct DiamondStorage_Proxy
{
// maps function selectors to the facets that execute the functions.
// and maps the selectors to the slot in the selectorSlots array.
// and maps the selectors to the position in the slot.
// func selector => address facet, uint64 slotsIndex, uint64 slotIndex
mapping(bytes4 => bytes32) facets;
// array of slots of function selectors.
// each slot holds 8 function selectors.
mapping(uint => bytes32) selectorSlots;
// uint128 numSelectorsInSlot, uint128 selectorSlotsLength
// selectorSlotsLength is the number of 32-byte slots in selectorSlots.
// selectorSlotLength is the number of selectors in the last slot of
// selectorSlots.
uint selectorSlotsLength;
// Used to query if a contract implements an interface.
// Used to implement ERC-165.
mapping(bytes4 => bool) supportedInterfaces;
}
function diamondStorage_Proxy() internal pure returns(DiamondStorage_Proxy storage ds)
{
// NOTE: this ds_slot must be the shared if you want to share storage with another contract under the proxy umbrella
// NOTE: this ds_slot must be unique if you want to NOT share storage with another contract under the proxy umbrella
// ds_slot = keccak256(diamond.storage.tutorial.proxy);
assembly { ds_slot := 0x974f3cfcf513e09347459922e3dfbf4842f090ee6f9ab895dd61cec8b4be1a22 }
}
}
contract Owned is
StorageContract_Authentication
{
// I'm naming this varible to be super unique so that nother ever overwrites it!
// Unless this name gets re-used again which should never happen...
// Be careful, logic contracts under this proxy umbrella could potentially overwrite this
// owner address method selector causing this owner to be lost!
// So it's critical to NEVER overwrite this function selector when you're upgrading a logic contract.
// In other words, never re-use this long unique name
address public owner_Proxy_ThisNameMustBeUniqueBecauseInTheoryItCouldGetOverridenByALogicContractHavingTheSameFunctionSelector;
constructor() public
{
owner_Proxy_ThisNameMustBeUniqueBecauseInTheoryItCouldGetOverridenByALogicContractHavingTheSameFunctionSelector = msg.sender;
}
modifier onlyOwner()
{
require(msg.sender == owner_Proxy_ThisNameMustBeUniqueBecauseInTheoryItCouldGetOverridenByALogicContractHavingTheSameFunctionSelector, "Must own the contract.");
_;
}
function whitelistUsers (
address[] memory users,
bool value
) public onlyOwner
{
// Only the owner can modify the whitelist
DiamondStorage_Authentication storage ds = diamondStorage_Authentication();
for(uint i = 0; i < users.length; i++)
{
ds.whitelistedUsers[users[i]] = value;
}
}
}
contract DiamondFacet is
Owned,
StorageContract_Proxy,
Diamond
{
bytes32 constant CLEAR_ADDRESS_MASK = 0x0000000000000000000000000000000000000000ffffffffffffffffffffffff;
bytes32 constant CLEAR_SELECTOR_MASK = 0xffffffff00000000000000000000000000000000000000000000000000000000;
struct SlotInfo
{
uint originalSelectorSlotsLength;
bytes32 selectorSlot;
uint oldSelectorSlotsIndex;
uint oldSelectorSlotIndex;
bytes32 oldSelectorSlot;
bool newSlot;
}
function diamondCut(
bytes[] memory _diamondCut
) public onlyOwner override
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
SlotInfo memory slot;
slot.originalSelectorSlotsLength = ds.selectorSlotsLength;
uint selectorSlotsLength = uint128(slot.originalSelectorSlotsLength);
uint selectorSlotLength = uint128(slot.originalSelectorSlotsLength >> 128);
if(selectorSlotLength > 0)
{
slot.selectorSlot = ds.selectorSlots[selectorSlotsLength];
}
// loop through diamond cut
for(uint diamondCutIndex; diamondCutIndex < _diamondCut.length; diamondCutIndex++)
{
bytes memory facetCut = _diamondCut[diamondCutIndex];
require(facetCut.length > 20, "Missing facet or selector info.");
bytes32 currentSlot;
assembly
{
currentSlot := mload(add(facetCut,32))
}
bytes32 newFacet = bytes20(currentSlot);
uint numSelectors = (facetCut.length - 20) / 4;
uint position = 52;
// adding or replacing functions
if(newFacet != 0)
{
// add and replace selectors
for(uint selectorIndex; selectorIndex < numSelectors; selectorIndex++)
{
bytes4 selector;
assembly
{
selector := mload(add(facetCut,position))
}
position += 4;
bytes32 oldFacet = ds.facets[selector];
// add
if(oldFacet == 0)
{
ds.facets[selector] = newFacet | bytes32(selectorSlotLength) << 64 | bytes32(selectorSlotsLength);
slot.selectorSlot = slot.selectorSlot & ~(CLEAR_SELECTOR_MASK >> selectorSlotLength * 32) | bytes32(selector) >> selectorSlotLength * 32;
selectorSlotLength++;
if(selectorSlotLength == 8)
{
ds.selectorSlots[selectorSlotsLength] = slot.selectorSlot;
slot.selectorSlot = 0;
selectorSlotLength = 0;
selectorSlotsLength++;
slot.newSlot = false;
}
else
{
slot.newSlot = true;
}
}
// replace
else
{
require(bytes20(oldFacet) != bytes20(newFacet), "Function cut to same facet.");
ds.facets[selector] = oldFacet & CLEAR_ADDRESS_MASK | newFacet;
}
}
}
// remove functions
else
{
for(uint selectorIndex; selectorIndex < numSelectors; selectorIndex++)
{
bytes4 selector;
assembly
{
selector := mload(add(facetCut,position))
}
position += 4;
bytes32 oldFacet = ds.facets[selector];
require(oldFacet != 0, "Function doesn't exist. Can't remove.");
if(slot.selectorSlot == 0)
{
selectorSlotsLength--;
slot.selectorSlot = ds.selectorSlots[selectorSlotsLength];
selectorSlotLength = 8;
}
slot.oldSelectorSlotsIndex = uint64(uint(oldFacet));
slot.oldSelectorSlotIndex = uint32(uint(oldFacet >> 64));
bytes4 lastSelector = bytes4(slot.selectorSlot << (selectorSlotLength-1) * 32);
if(slot.oldSelectorSlotsIndex != selectorSlotsLength)
{
slot.oldSelectorSlot = ds.selectorSlots[slot.oldSelectorSlotsIndex];
slot.oldSelectorSlot = slot.oldSelectorSlot & ~(CLEAR_SELECTOR_MASK >> slot.oldSelectorSlotIndex * 32) | bytes32(lastSelector) >> slot.oldSelectorSlotIndex * 32;
ds.selectorSlots[slot.oldSelectorSlotsIndex] = slot.oldSelectorSlot;
selectorSlotLength--;
}
else
{
slot.selectorSlot = slot.selectorSlot & ~(CLEAR_SELECTOR_MASK >> slot.oldSelectorSlotIndex * 32) | bytes32(lastSelector) >> slot.oldSelectorSlotIndex * 32;
selectorSlotLength--;
}
if(selectorSlotLength == 0)
{
delete ds.selectorSlots[selectorSlotsLength];
slot.selectorSlot = 0;
}
if(lastSelector != selector)
{
ds.facets[lastSelector] = oldFacet & CLEAR_ADDRESS_MASK | bytes20(ds.facets[lastSelector]);
}
delete ds.facets[selector];
}
}
}
uint newSelectorSlotsLength = selectorSlotLength << 128 | selectorSlotsLength;
if(newSelectorSlotsLength != slot.originalSelectorSlotsLength)
{
ds.selectorSlotsLength = newSelectorSlotsLength;
}
if(slot.newSlot)
{
ds.selectorSlots[selectorSlotsLength] = slot.selectorSlot;
}
emit DiamondCut(_diamondCut);
}
}
// A loupe is a small magnifying glass used to look at diamonds.
// These functions look at diamonds
interface DiamondLoupe
{
/// These functions are expected to be called frequently
/// by tools. Therefore the return values are tightly
/// packed for efficiency. That means no padding with zeros.
/// @notice Gets all facets and their selectors.
/// @return An array of bytes arrays containing each facet
/// and each facet's selectors.
/// The return value is tightly packed.
/// Here is the structure of the return value:
/// returnValue = [
/// abi.encodePacked(facet, sel1, sel2, sel3, ...),
/// abi.encodePacked(facet, sel1, sel2, sel3, ...),
/// ...
/// ]
/// facet is the address of a facet.
/// sel1, sel2, sel3 etc. are four-byte function selectors.
function facets() external view returns(bytes[] memory);
/// @notice Gets all the function selectors supported by a specific facet.
/// @param _facet The facet address.
/// @return A byte array of function selectors.
/// The return value is tightly packed. Here is an example:
/// return abi.encodePacked(selector1, selector2, selector3, ...)
function facetFunctionSelectors(address _facet) external view returns(bytes memory);
/// @notice Get all the facet addresses used by a diamond.
/// @return A byte array of tightly packed facet addresses.
/// Example return value:
/// return abi.encodePacked(facet1, facet2, facet3, ...)
function facetAddresses() external view returns(bytes memory);
/// @notice Gets the facet that supports the given selector.
/// @dev If facet is not found return address(0).
/// @param _functionSelector The function selector.
/// @return The facet address.
function facetAddress(bytes4 _functionSelector) external view returns(address);
}
interface ERC165
{
/// @notice Query if a contract implements an interface
/// @param interfaceID The interface identifier, as specified in ERC-165
/// @dev Interface identification is specified in ERC-165. This function
/// uses less than 30,000 gas.
/// @return `true` if the contract implements `interfaceID` and
/// `interfaceID` is not 0xffffffff, `false` otherwise
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
contract DiamondLoupeFacet is DiamondLoupe, StorageContract_Proxy
{
/// These functions are expected to be called frequently
/// by tools. Therefore the return values are tightly
/// packed for efficiency. That means no padding with zeros.
struct Facet
{
address facet;
bytes4[] functionSelectors;
}
/// @notice Gets all facets and their selectors.
/// @return An array of bytes arrays containing each facet
/// and each facet's selectors.
/// The return value is tightly packed.
/// That means no padding with zeros.
/// Here is the structure of the return value:
/// returnValue = [
/// abi.encodePacked(facet, sel1, sel2, sel3, ...),
/// abi.encodePacked(facet, sel1, sel2, sel3, ...),
/// ...
/// ]
/// facet is the address of a facet.
/// sel1, sel2, sel3 etc. are four-byte function selectors.
function facets(
) external view override returns(bytes[] memory)
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
uint totalSelectorSlots = ds.selectorSlotsLength;
uint selectorSlotLength = uint128(totalSelectorSlots >> 128);
totalSelectorSlots = uint128(totalSelectorSlots);
uint totalSelectors = totalSelectorSlots * 8 + selectorSlotLength;
if(selectorSlotLength > 0)
{
totalSelectorSlots++;
}
// get default size of arrays
uint defaultSize = totalSelectors;
if(defaultSize > 20)
{
defaultSize = 20;
}
Facet[] memory facets_ = new Facet[](defaultSize);
uint8[] memory numFacetSelectors = new uint8[](defaultSize);
uint numFacets;
uint selectorCount;
// loop through function selectors
for(uint slotIndex; selectorCount < totalSelectors; slotIndex++)
{
bytes32 slot = ds.selectorSlots[slotIndex];
for(uint selectorIndex; selectorIndex < 8; selectorIndex++)
{
selectorCount++;
if(selectorCount > totalSelectors)
{
break;
}
bytes4 selector = bytes4(slot << selectorIndex * 32);
address facet = address(bytes20(ds.facets[selector]));
bool continueLoop = false;
for(uint facetIndex; facetIndex < numFacets; facetIndex++)
{
if(facets_[facetIndex].facet == facet)
{
uint arrayLength = facets_[facetIndex].functionSelectors.length;
// if array is too small then enlarge it
if(numFacetSelectors[facetIndex]+1 > arrayLength)
{
bytes4[] memory biggerArray = new bytes4[](arrayLength + defaultSize);
// copy contents of old array
for(uint i; i < arrayLength; i++)
{
biggerArray[i] = facets_[facetIndex].functionSelectors[i];
}
facets_[facetIndex].functionSelectors = biggerArray;
}
facets_[facetIndex].functionSelectors[numFacetSelectors[facetIndex]] = selector;
// probably will never have more than 255 functions from one facet contract
require(numFacetSelectors[facetIndex] < 255);
numFacetSelectors[facetIndex]++;
continueLoop = true;
break;
}
}
if(continueLoop)
{
continueLoop = false;
continue;
}
uint arrayLength = facets_.length;
// if array is too small then enlarge it
if(numFacets+1 > arrayLength)
{
Facet[] memory biggerArray = new Facet[](arrayLength + defaultSize);
uint8[] memory biggerArray2 = new uint8[](arrayLength + defaultSize);
for(uint i; i < arrayLength; i++)
{
biggerArray[i] = facets_[i];
biggerArray2[i] = numFacetSelectors[i];
}
facets_ = biggerArray;
numFacetSelectors = biggerArray2;
}
facets_[numFacets].facet = facet;
facets_[numFacets].functionSelectors = new bytes4[](defaultSize);
facets_[numFacets].functionSelectors[0] = selector;
numFacetSelectors[numFacets] = 1;
numFacets++;
}
}
bytes[] memory returnFacets = new bytes[](numFacets);
for(uint facetIndex; facetIndex < numFacets; facetIndex++)
{
uint numSelectors = numFacetSelectors[facetIndex];
bytes memory selectorsBytes = new bytes(4 * numSelectors);
bytes4[] memory selectors = facets_[facetIndex].functionSelectors;
uint bytePosition;
for(uint i; i < numSelectors; i++)
{
for(uint j; j < 4; j++)
{
selectorsBytes[bytePosition] = byte(selectors[i] << j * 8);
bytePosition++;
}
}
returnFacets[facetIndex] = abi.encodePacked(facets_[facetIndex].facet, selectorsBytes);
}
return returnFacets;
}
/// @notice Gets all the function selectors supported by a specific facet.
/// @param _facet The facet address.
/// @return A bytes array of function selectors.
/// The return value is tightly packed. Here is an example:
/// return abi.encodePacked(selector1, selector2, selector3, ...)
function facetFunctionSelectors(
address _facet
) external view override returns(bytes memory)
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
uint totalSelectorSlots = ds.selectorSlotsLength;
uint selectorSlotLength = uint128(totalSelectorSlots >> 128);
totalSelectorSlots = uint128(totalSelectorSlots);
uint totalSelectors = totalSelectorSlots * 8 + selectorSlotLength;
if(selectorSlotLength > 0)
{
totalSelectorSlots++;
}
uint numFacetSelectors;
bytes4[] memory facetSelectors = new bytes4[](totalSelectors);
uint selectorCount;
// loop through function selectors
for(uint slotIndex; selectorCount < totalSelectors; slotIndex++)
{
bytes32 slot = ds.selectorSlots[slotIndex];
for(uint selectorIndex; selectorIndex < 8; selectorIndex++)
{
selectorCount++;
if(selectorCount > totalSelectors)
{
break;
}
bytes4 selector = bytes4(slot << selectorIndex * 32);
address facet = address(bytes20(ds.facets[selector]));
if(_facet == facet)
{
facetSelectors[numFacetSelectors] = selector;
numFacetSelectors++;
}
}
}
bytes memory returnBytes = new bytes(4 * numFacetSelectors);
uint bytePosition;
for(uint i; i < numFacetSelectors; i++)
{
for(uint j; j < 4; j++)
{
returnBytes[bytePosition] = byte(facetSelectors[i] << j * 8);
bytePosition++;
}
}
return returnBytes;
}
/// @notice Get all the facet addresses used by a diamond.
/// @return A byte array of tightly packed facet addresses.
/// Example return value:
/// return abi.encodePacked(facet1, facet2, facet3, ...)
function facetAddresses(
) external view override returns(bytes memory)
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
uint totalSelectorSlots = ds.selectorSlotsLength;
uint selectorSlotLength = uint128(totalSelectorSlots >> 128);
totalSelectorSlots = uint128(totalSelectorSlots);
uint totalSelectors = totalSelectorSlots * 8 + selectorSlotLength;
if(selectorSlotLength > 0)
{
totalSelectorSlots++;
}
address[] memory facets_ = new address[](totalSelectors);
uint numFacets;
uint selectorCount;
// loop through function selectors
for(uint slotIndex; selectorCount < totalSelectors; slotIndex++)
{
bytes32 slot = ds.selectorSlots[slotIndex];
for(uint selectorIndex; selectorIndex < 8; selectorIndex++)
{
selectorCount++;
if(selectorCount > totalSelectors)
{
break;
}
bytes4 selector = bytes4(slot << selectorIndex * 32);
address facet = address(bytes20(ds.facets[selector]));
bool continueLoop = false;
for(uint facetIndex; facetIndex < numFacets; facetIndex++)
{
if(facet == facets_[facetIndex])
{
continueLoop = true;
break;
}
}
if(continueLoop)
{
continueLoop = false;
continue;
}
facets_[numFacets] = facet;
numFacets++;
}
}
bytes memory returnBytes = new bytes(20 * numFacets);
uint bytePosition;
for(uint i; i < numFacets; i++)
{
for(uint j; j < 20; j++)
{
returnBytes[bytePosition] = byte(bytes20(facets_[i]) << j * 8);
bytePosition++;
}
}
return returnBytes;
}
/// @notice Gets the facet that supports the given selector.
/// @dev If facet is not found return address(0).
/// @param _functionSelector The function selector.
/// @return The facet address.
function facetAddress(
bytes4 _functionSelector
) external view override returns(address)
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
return address(bytes20(ds.facets[_functionSelector]));
}
}
contract TutorialProxy is
Owned,
StorageContract_Proxy
{
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor(
) public
{
emit OwnershipTransferred(address(0), msg.sender);
// Whitelist the contract creator
DiamondStorage_Authentication storage ds_Authentication = diamondStorage_Authentication();
ds_Authentication.whitelistedUsers[msg.sender] = true;
// Create a DiamondFacet contract which implements the Diamond interface
DiamondFacet diamondFacet = new DiamondFacet();
// Create a DiamondLoupeFacet contract which implements the Diamond Loupe interface
DiamondLoupeFacet diamondLoupeFacet = new DiamondLoupeFacet();
bytes[] memory diamondCut = new bytes[](3);
// Adding cut function
diamondCut[0] = abi.encodePacked(diamondFacet, Diamond.diamondCut.selector);
// Adding diamond loupe functions
diamondCut[1] = abi.encodePacked(
diamondLoupeFacet,
DiamondLoupe.facetFunctionSelectors.selector,
DiamondLoupe.facets.selector,
DiamondLoupe.facetAddress.selector,
DiamondLoupe.facetAddresses.selector
);
// Adding supportsInterface function
diamondCut[2] = abi.encodePacked(address(this), ERC165.supportsInterface.selector);
// execute cut function
bytes memory cutFunction = abi.encodeWithSelector(Diamond.diamondCut.selector, diamondCut);
(bool success,) = address(diamondFacet).delegatecall(cutFunction);
require(success, "Adding functions failed.");
// adding ERC165 data
DiamondStorage_Proxy storage ds_Proxy = diamondStorage_Proxy();
ds_Proxy.supportedInterfaces[ERC165.supportsInterface.selector] = true;
ds_Proxy.supportedInterfaces[Diamond.diamondCut.selector] = true;
bytes4 interfaceID = DiamondLoupe.facets.selector ^ DiamondLoupe.facetFunctionSelectors.selector ^ DiamondLoupe.facetAddresses.selector ^ DiamondLoupe.facetAddress.selector;
ds_Proxy.supportedInterfaces[interfaceID] = true;
}
// This is an immutable functions because it is defined directly in the diamond.
// This implements ERC-165.
function supportsInterface(
bytes4 _interfaceID
) external view returns (bool)
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
return ds.supportedInterfaces[_interfaceID];
}
// Finds facet for function that is called and executes the
// function if it is found and returns any value.
fallback() external payable
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
address facet = address(bytes20(ds.facets[msg.sig]));
require(facet != address(0), "Function does not exist.");
assembly
{
let ptr := mload(0x40)
calldatacopy(ptr, 0, calldatasize())
let result := delegatecall(gas(), facet, ptr, calldatasize(), 0, 0)
let size := returndatasize()
returndatacopy(ptr, 0, size)
switch result
case 0 {revert(ptr, size)}
default {return (ptr, size)}
}
}
receive() external payable {}
}
|
Gets the facet that supports the given selector. If facet is not found return address(0). _functionSelector The function selector. return The facet address.
|
function facetAddress(
bytes4 _functionSelector
) external view override returns(address)
{
DiamondStorage_Proxy storage ds = diamondStorage_Proxy();
return address(bytes20(ds.facets[_functionSelector]));
}
| 6,453,010 |
pragma solidity ^0.4.23;
import "./safemathint.sol";
import "./ownable.sol";
// TODO maybe add modifier so that a candidate cannot vote himself
// TODO safemath for uint and int
/// @title Simple voting dapp
/// @author spirosbax
contract voting is Ownable {
using SafeMathInt for int256;
/* this is where we store our candidates and match the with ids
it is public so everyone can see every candidates votes,
we get automatic get methods, eg. candidateToVotes(2) will return the Candidate with id = 2 */
mapping(bytes32 => int256) private candidateToVotes;
bytes32[] public candidates;
event NewCandidateAdded(bytes32 _name);
event VotedCandidate(bytes32 _name);
event DeletedCandidate(bytes32 _name);
modifier candidateExists(bytes32 _name) {
require((candidateToVotes[_name] == -1) || (candidateToVotes[_name] > 0)); // check if candidate exists
_;
}
/// add new Candidate
/// @param _name the name of the new Candidate
/// @dev anyone can add a new Candidate
function addNewCandidate(bytes32 _name) public {
_addNewCandidate(_name);
}
/// internal function for adding a candidate
/// @param _name the name of the Candidate to be added
/// @dev fires an NewCandidateAdded event
function _addNewCandidate(bytes32 _name) internal {
require(candidateToVotes[_name] == 0); // check that candidate has not already been added
candidateToVotes[_name] = -1;
candidates.push(_name);
emit NewCandidateAdded(_name);
}
/// vote for a Candidate, anyone can vote for a Candidate
/// @param _name the id of the Candidate to be voted
/// @dev throws event VotedCandidate
// TODO add a way for the callee to pay so the data can be written to the blockchain
function voteForCandidate(bytes32 _name) public {
_voteForCandidate(_name);
}
function _voteForCandidate(bytes32 _name) internal candidateExists(_name) {
if (candidateToVotes[_name] == -1) {
candidateToVotes[_name] = candidateToVotes[_name].add(2);
} else {
candidateToVotes[_name] = candidateToVotes[_name].add(1);
}
emit VotedCandidate(_name);
}
/// deletes a candidate, only owner can delete candidates
/// @param _name the id of the Candidate to be deleted
/// @dev throws event DeletedCandidate
function deleteCandidate(bytes32 _name) public onlyOwner {
_deleteCandidate(_name);
}
function _deleteCandidate(bytes32 _name) internal candidateExists(_name) {
candidateToVotes[_name] = -2;
for(uint256 i = 0; i < candidates.length; i++) {
if(keccak256(candidates[i]) == keccak256(_name)) {
delete candidates[i];
}
}
emit DeletedCandidate(_name);
}
/// returns the votes of candidate with id _name
/// @param _name the id of the candidate
function getCandidateVotes(bytes32 _name) view external candidateExists(_name) returns (int){
if (candidateToVotes[_name] == -1) {
return 0;
}
return candidateToVotes[_name];
}
/// returns list of candidates
function getCandidateList() view external returns (bytes32[]) {
return candidates;
}
}
|
add new Candidate _name the name of the new Candidate anyone can add a new Candidate
|
function addNewCandidate(bytes32 _name) public {
_addNewCandidate(_name);
}
| 2,478,415 |
pragma solidity ^0.4.21;
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic {
event Transfer(address indexed _from, address indexed _to, uint256 _tokenId);
event Approval(address indexed _owner, address indexed _approved, uint256 _tokenId);
event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId) public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator) public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/// @title An optional contract that allows us to associate metadata to our cards.
/// @author The CryptoStrikers Team
contract StrikersMetadata {
/// @dev The base url for the API where we fetch the metadata.
/// ex: https://us-central1-cryptostrikers-api.cloudfunctions.net/cards/
string public apiUrl;
constructor(string _apiUrl) public {
apiUrl = _apiUrl;
}
/// @dev Returns the API URL for a given token Id.
/// ex: https://us-central1-cryptostrikers-api.cloudfunctions.net/cards/22
/// Right now, this endpoint returns a JSON blob conforming to OpenSea's spec.
/// see: https://docs.opensea.io/docs/2-adding-metadata
function tokenURI(uint256 _tokenId) external view returns (string) {
string memory _id = uint2str(_tokenId);
return strConcat(apiUrl, _id);
}
// String helpers below were taken from Oraclize.
// https://github.com/oraclize/ethereum-api/blob/master/oraclizeAPI_0.4.sol
function strConcat(string _a, string _b) internal pure returns (string) {
bytes memory _ba = bytes(_a);
bytes memory _bb = bytes(_b);
string memory ab = new string(_ba.length + _bb.length);
bytes memory bab = bytes(ab);
uint k = 0;
for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i];
for (i = 0; i < _bb.length; i++) bab[k++] = _bb[i];
return string(bab);
}
function uint2str(uint i) internal pure returns (string) {
if (i == 0) return "0";
uint j = i;
uint len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint k = len - 1;
while (i != 0) {
bstr[k--] = byte(48 + i % 10);
i /= 10;
}
return string(bstr);
}
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. This function MUST use 50,000 gas or less. Return of other
* than the magic value MUST result in the transaction being reverted.
* Note: the contract address is always the message sender.
* @param _from The sending address
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
*/
function onERC721Received(address _from, uint256 _tokenId, bytes _data) public returns(bytes4);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC721Basic {
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 constant ERC721_RECEIVED = 0xf0b9e5ba;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existance of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* @dev The zero address indicates there is no approved address.
* @dev There can only be one approved address per token at a given time.
* @dev Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
if (getApproved(_tokenId) != address(0) || _to != address(0)) {
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for a the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* @dev An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(address _owner, address _operator) public view returns (bool) {
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* @dev Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(address _from, address _to, uint256 _tokenId) public canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* @dev If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* @dev Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(address _spender, uint256 _tokenId) internal view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* @dev Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
emit Approval(_owner, address(0), _tokenId);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* @dev The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(_from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is ERC721, ERC721BasicToken {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
function ERC721Token(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() public view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(address _owner, uint256 _index) public view returns (uint256) {
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* @dev Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* @dev Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* @dev Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* @dev Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
/// @title The contract that manages all the players that appear in our game.
/// @author The CryptoStrikers Team
contract StrikersPlayerList is Ownable {
// We only use playerIds in StrikersChecklist.sol (to
// indicate which player features on instances of a
// given ChecklistItem), and nowhere else in the app.
// While it's not explictly necessary for any of our
// contracts to know that playerId 0 corresponds to
// Lionel Messi, we think that it's nice to have
// a canonical source of truth for who the playerIds
// actually refer to. Storing strings (player names)
// is expensive, so we just use Events to prove that,
// at some point, we said a playerId represents a given person.
/// @dev The event we fire when we add a player.
event PlayerAdded(uint8 indexed id, string name);
/// @dev How many players we've added so far
/// (max 255, though we don't plan on getting close)
uint8 public playerCount;
/// @dev Here we add the players we are launching with on Day 1.
/// Players are loosely ranked by things like FIFA ratings,
/// number of Instagram followers, and opinions of CryptoStrikers
/// team members. Feel free to yell at us on Twitter.
constructor() public {
addPlayer("Lionel Messi"); // 0
addPlayer("Cristiano Ronaldo"); // 1
addPlayer("Neymar"); // 2
addPlayer("Mohamed Salah"); // 3
addPlayer("Robert Lewandowski"); // 4
addPlayer("Kevin De Bruyne"); // 5
addPlayer("Luka Modrić"); // 6
addPlayer("Eden Hazard"); // 7
addPlayer("Sergio Ramos"); // 8
addPlayer("Toni Kroos"); // 9
addPlayer("Luis Suárez"); // 10
addPlayer("Harry Kane"); // 11
addPlayer("Sergio Agüero"); // 12
addPlayer("Kylian Mbappé"); // 13
addPlayer("Gonzalo Higuaín"); // 14
addPlayer("David de Gea"); // 15
addPlayer("Antoine Griezmann"); // 16
addPlayer("N'Golo Kanté"); // 17
addPlayer("Edinson Cavani"); // 18
addPlayer("Paul Pogba"); // 19
addPlayer("Isco"); // 20
addPlayer("Marcelo"); // 21
addPlayer("Manuel Neuer"); // 22
addPlayer("Dries Mertens"); // 23
addPlayer("James Rodríguez"); // 24
addPlayer("Paulo Dybala"); // 25
addPlayer("Christian Eriksen"); // 26
addPlayer("David Silva"); // 27
addPlayer("Gabriel Jesus"); // 28
addPlayer("Thiago"); // 29
addPlayer("Thibaut Courtois"); // 30
addPlayer("Philippe Coutinho"); // 31
addPlayer("Andrés Iniesta"); // 32
addPlayer("Casemiro"); // 33
addPlayer("Romelu Lukaku"); // 34
addPlayer("Gerard Piqué"); // 35
addPlayer("Mats Hummels"); // 36
addPlayer("Diego Godín"); // 37
addPlayer("Mesut Özil"); // 38
addPlayer("Son Heung-min"); // 39
addPlayer("Raheem Sterling"); // 40
addPlayer("Hugo Lloris"); // 41
addPlayer("Radamel Falcao"); // 42
addPlayer("Ivan Rakitić"); // 43
addPlayer("Leroy Sané"); // 44
addPlayer("Roberto Firmino"); // 45
addPlayer("Sadio Mané"); // 46
addPlayer("Thomas Müller"); // 47
addPlayer("Dele Alli"); // 48
addPlayer("Keylor Navas"); // 49
addPlayer("Thiago Silva"); // 50
addPlayer("Raphaël Varane"); // 51
addPlayer("Ángel Di María"); // 52
addPlayer("Jordi Alba"); // 53
addPlayer("Medhi Benatia"); // 54
addPlayer("Timo Werner"); // 55
addPlayer("Gylfi Sigurðsson"); // 56
addPlayer("Nemanja Matić"); // 57
addPlayer("Kalidou Koulibaly"); // 58
addPlayer("Bernardo Silva"); // 59
addPlayer("Vincent Kompany"); // 60
addPlayer("João Moutinho"); // 61
addPlayer("Toby Alderweireld"); // 62
addPlayer("Emil Forsberg"); // 63
addPlayer("Mario Mandžukić"); // 64
addPlayer("Sergej Milinković-Savić"); // 65
addPlayer("Shinji Kagawa"); // 66
addPlayer("Granit Xhaka"); // 67
addPlayer("Andreas Christensen"); // 68
addPlayer("Piotr Zieliński"); // 69
addPlayer("Fyodor Smolov"); // 70
addPlayer("Xherdan Shaqiri"); // 71
addPlayer("Marcus Rashford"); // 72
addPlayer("Javier Hernández"); // 73
addPlayer("Hirving Lozano"); // 74
addPlayer("Hakim Ziyech"); // 75
addPlayer("Victor Moses"); // 76
addPlayer("Jefferson Farfán"); // 77
addPlayer("Mohamed Elneny"); // 78
addPlayer("Marcus Berg"); // 79
addPlayer("Guillermo Ochoa"); // 80
addPlayer("Igor Akinfeev"); // 81
addPlayer("Sardar Azmoun"); // 82
addPlayer("Christian Cueva"); // 83
addPlayer("Wahbi Khazri"); // 84
addPlayer("Keisuke Honda"); // 85
addPlayer("Tim Cahill"); // 86
addPlayer("John Obi Mikel"); // 87
addPlayer("Ki Sung-yueng"); // 88
addPlayer("Bryan Ruiz"); // 89
addPlayer("Maya Yoshida"); // 90
addPlayer("Nawaf Al Abed"); // 91
addPlayer("Lee Chung-yong"); // 92
addPlayer("Gabriel Gómez"); // 93
addPlayer("Naïm Sliti"); // 94
addPlayer("Reza Ghoochannejhad"); // 95
addPlayer("Mile Jedinak"); // 96
addPlayer("Mohammad Al-Sahlawi"); // 97
addPlayer("Aron Gunnarsson"); // 98
addPlayer("Blas Pérez"); // 99
addPlayer("Dani Alves"); // 100
addPlayer("Zlatan Ibrahimović"); // 101
}
/// @dev Fires an event, proving that we said a player corresponds to a given ID.
/// @param _name The name of the player we are adding.
function addPlayer(string _name) public onlyOwner {
require(playerCount < 255, "You've already added the maximum amount of players.");
emit PlayerAdded(playerCount, _name);
playerCount++;
}
}
/// @title The contract that manages checklist items, sets, and rarity tiers.
/// @author The CryptoStrikers Team
contract StrikersChecklist is StrikersPlayerList {
// High level overview of everything going on in this contract:
//
// ChecklistItem is the parent class to Card and has 3 properties:
// - uint8 checklistId (000 to 255)
// - uint8 playerId (see StrikersPlayerList.sol)
// - RarityTier tier (more info below)
//
// Two things to note: the checklistId is not explicitly stored
// on the checklistItem struct, and it's composed of two parts.
// (For the following, assume it is left padded with zeros to reach
// three digits, such that checklistId 0 becomes 000)
// - the first digit represents the setId
// * 0 = Originals Set
// * 1 = Iconics Set
// * 2 = Unreleased Set
// - the last two digits represent its index in the appropriate set arary
//
// For example, checklist ID 100 would represent fhe first checklist item
// in the iconicChecklistItems array (first digit = 1 = Iconics Set, last two
// digits = 00 = first index of array)
//
// Because checklistId is represented as a uint8 throughout the app, the highest
// value it can take is 255, which means we can't add more than 56 items to our
// Unreleased Set's unreleasedChecklistItems array (setId 2). Also, once we've initialized
// this contract, it's impossible for us to add more checklist items to the Originals
// and Iconics set -- what you see here is what you get.
//
// Simple enough right?
/// @dev We initialize this contract with so much data that we have
/// to stage it in 4 different steps, ~33 checklist items at a time.
enum DeployStep {
WaitingForStepOne,
WaitingForStepTwo,
WaitingForStepThree,
WaitingForStepFour,
DoneInitialDeploy
}
/// @dev Enum containing all our rarity tiers, just because
/// it's cleaner dealing with these values than with uint8s.
enum RarityTier {
IconicReferral,
IconicInsert,
Diamond,
Gold,
Silver,
Bronze
}
/// @dev A lookup table indicating how limited the cards
/// in each tier are. If this value is 0, it means
/// that cards of this rarity tier are unlimited,
/// which is only the case for the 8 Iconics cards
/// we give away as part of our referral program.
uint16[] public tierLimits = [
0, // Iconic - Referral Bonus (uncapped)
100, // Iconic Inserts ("Card of the Day")
1000, // Diamond
1664, // Gold
3328, // Silver
4352 // Bronze
];
/// @dev ChecklistItem is essentially the parent class to Card.
/// It represents a given superclass of cards (eg Originals Messi),
/// and then each Card is an instance of this ChecklistItem, with
/// its own serial number, mint date, etc.
struct ChecklistItem {
uint8 playerId;
RarityTier tier;
}
/// @dev The deploy step we're at. Defaults to WaitingForStepOne.
DeployStep public deployStep;
/// @dev Array containing all the Originals checklist items (000 - 099)
ChecklistItem[] public originalChecklistItems;
/// @dev Array containing all the Iconics checklist items (100 - 131)
ChecklistItem[] public iconicChecklistItems;
/// @dev Array containing all the unreleased checklist items (200 - 255 max)
ChecklistItem[] public unreleasedChecklistItems;
/// @dev Internal function to add a checklist item to the Originals set.
/// @param _playerId The player represented by this checklist item. (see StrikersPlayerList.sol)
/// @param _tier This checklist item's rarity tier. (see Rarity Tier enum and corresponding tierLimits)
function _addOriginalChecklistItem(uint8 _playerId, RarityTier _tier) internal {
originalChecklistItems.push(ChecklistItem({
playerId: _playerId,
tier: _tier
}));
}
/// @dev Internal function to add a checklist item to the Iconics set.
/// @param _playerId The player represented by this checklist item. (see StrikersPlayerList.sol)
/// @param _tier This checklist item's rarity tier. (see Rarity Tier enum and corresponding tierLimits)
function _addIconicChecklistItem(uint8 _playerId, RarityTier _tier) internal {
iconicChecklistItems.push(ChecklistItem({
playerId: _playerId,
tier: _tier
}));
}
/// @dev External function to add a checklist item to our mystery set.
/// Must have completed initial deploy, and can't add more than 56 items (because checklistId is a uint8).
/// @param _playerId The player represented by this checklist item. (see StrikersPlayerList.sol)
/// @param _tier This checklist item's rarity tier. (see Rarity Tier enum and corresponding tierLimits)
function addUnreleasedChecklistItem(uint8 _playerId, RarityTier _tier) external onlyOwner {
require(deployStep == DeployStep.DoneInitialDeploy, "Finish deploying the Originals and Iconics sets first.");
require(unreleasedCount() < 56, "You can't add any more checklist items.");
require(_playerId < playerCount, "This player doesn't exist in our player list.");
unreleasedChecklistItems.push(ChecklistItem({
playerId: _playerId,
tier: _tier
}));
}
/// @dev Returns how many Original checklist items we've added.
function originalsCount() external view returns (uint256) {
return originalChecklistItems.length;
}
/// @dev Returns how many Iconic checklist items we've added.
function iconicsCount() public view returns (uint256) {
return iconicChecklistItems.length;
}
/// @dev Returns how many Unreleased checklist items we've added.
function unreleasedCount() public view returns (uint256) {
return unreleasedChecklistItems.length;
}
// In the next four functions, we initialize this contract with our
// 132 initial checklist items (100 Originals, 32 Iconics). Because
// of how much data we need to store, it has to be broken up into
// four different function calls, which need to be called in sequence.
// The ordering of the checklist items we add determines their
// checklist ID, which is left-padded in our frontend to be a
// 3-digit identifier where the first digit is the setId and the last
// 2 digits represents the checklist items index in the appropriate ___ChecklistItems array.
// For example, Originals Messi is the first item for set ID 0, and this
// is displayed as #000 throughout the app. Our Card struct declare its
// checklistId property as uint8, so we have
// to be mindful that we can only have 256 total checklist items.
/// @dev Deploys Originals #000 through #032.
function deployStepOne() external onlyOwner {
require(deployStep == DeployStep.WaitingForStepOne, "You're not following the steps in order...");
/* ORIGINALS - DIAMOND */
_addOriginalChecklistItem(0, RarityTier.Diamond); // 000 Messi
_addOriginalChecklistItem(1, RarityTier.Diamond); // 001 Ronaldo
_addOriginalChecklistItem(2, RarityTier.Diamond); // 002 Neymar
_addOriginalChecklistItem(3, RarityTier.Diamond); // 003 Salah
/* ORIGINALS - GOLD */
_addOriginalChecklistItem(4, RarityTier.Gold); // 004 Lewandowski
_addOriginalChecklistItem(5, RarityTier.Gold); // 005 De Bruyne
_addOriginalChecklistItem(6, RarityTier.Gold); // 006 Modrić
_addOriginalChecklistItem(7, RarityTier.Gold); // 007 Hazard
_addOriginalChecklistItem(8, RarityTier.Gold); // 008 Ramos
_addOriginalChecklistItem(9, RarityTier.Gold); // 009 Kroos
_addOriginalChecklistItem(10, RarityTier.Gold); // 010 Suárez
_addOriginalChecklistItem(11, RarityTier.Gold); // 011 Kane
_addOriginalChecklistItem(12, RarityTier.Gold); // 012 Agüero
_addOriginalChecklistItem(13, RarityTier.Gold); // 013 Mbappé
_addOriginalChecklistItem(14, RarityTier.Gold); // 014 Higuaín
_addOriginalChecklistItem(15, RarityTier.Gold); // 015 de Gea
_addOriginalChecklistItem(16, RarityTier.Gold); // 016 Griezmann
_addOriginalChecklistItem(17, RarityTier.Gold); // 017 Kanté
_addOriginalChecklistItem(18, RarityTier.Gold); // 018 Cavani
_addOriginalChecklistItem(19, RarityTier.Gold); // 019 Pogba
/* ORIGINALS - SILVER (020 to 032) */
_addOriginalChecklistItem(20, RarityTier.Silver); // 020 Isco
_addOriginalChecklistItem(21, RarityTier.Silver); // 021 Marcelo
_addOriginalChecklistItem(22, RarityTier.Silver); // 022 Neuer
_addOriginalChecklistItem(23, RarityTier.Silver); // 023 Mertens
_addOriginalChecklistItem(24, RarityTier.Silver); // 024 James
_addOriginalChecklistItem(25, RarityTier.Silver); // 025 Dybala
_addOriginalChecklistItem(26, RarityTier.Silver); // 026 Eriksen
_addOriginalChecklistItem(27, RarityTier.Silver); // 027 David Silva
_addOriginalChecklistItem(28, RarityTier.Silver); // 028 Gabriel Jesus
_addOriginalChecklistItem(29, RarityTier.Silver); // 029 Thiago
_addOriginalChecklistItem(30, RarityTier.Silver); // 030 Courtois
_addOriginalChecklistItem(31, RarityTier.Silver); // 031 Coutinho
_addOriginalChecklistItem(32, RarityTier.Silver); // 032 Iniesta
// Move to the next deploy step.
deployStep = DeployStep.WaitingForStepTwo;
}
/// @dev Deploys Originals #033 through #065.
function deployStepTwo() external onlyOwner {
require(deployStep == DeployStep.WaitingForStepTwo, "You're not following the steps in order...");
/* ORIGINALS - SILVER (033 to 049) */
_addOriginalChecklistItem(33, RarityTier.Silver); // 033 Casemiro
_addOriginalChecklistItem(34, RarityTier.Silver); // 034 Lukaku
_addOriginalChecklistItem(35, RarityTier.Silver); // 035 Piqué
_addOriginalChecklistItem(36, RarityTier.Silver); // 036 Hummels
_addOriginalChecklistItem(37, RarityTier.Silver); // 037 Godín
_addOriginalChecklistItem(38, RarityTier.Silver); // 038 Özil
_addOriginalChecklistItem(39, RarityTier.Silver); // 039 Son
_addOriginalChecklistItem(40, RarityTier.Silver); // 040 Sterling
_addOriginalChecklistItem(41, RarityTier.Silver); // 041 Lloris
_addOriginalChecklistItem(42, RarityTier.Silver); // 042 Falcao
_addOriginalChecklistItem(43, RarityTier.Silver); // 043 Rakitić
_addOriginalChecklistItem(44, RarityTier.Silver); // 044 Sané
_addOriginalChecklistItem(45, RarityTier.Silver); // 045 Firmino
_addOriginalChecklistItem(46, RarityTier.Silver); // 046 Mané
_addOriginalChecklistItem(47, RarityTier.Silver); // 047 Müller
_addOriginalChecklistItem(48, RarityTier.Silver); // 048 Alli
_addOriginalChecklistItem(49, RarityTier.Silver); // 049 Navas
/* ORIGINALS - BRONZE (050 to 065) */
_addOriginalChecklistItem(50, RarityTier.Bronze); // 050 Thiago Silva
_addOriginalChecklistItem(51, RarityTier.Bronze); // 051 Varane
_addOriginalChecklistItem(52, RarityTier.Bronze); // 052 Di María
_addOriginalChecklistItem(53, RarityTier.Bronze); // 053 Alba
_addOriginalChecklistItem(54, RarityTier.Bronze); // 054 Benatia
_addOriginalChecklistItem(55, RarityTier.Bronze); // 055 Werner
_addOriginalChecklistItem(56, RarityTier.Bronze); // 056 Sigurðsson
_addOriginalChecklistItem(57, RarityTier.Bronze); // 057 Matić
_addOriginalChecklistItem(58, RarityTier.Bronze); // 058 Koulibaly
_addOriginalChecklistItem(59, RarityTier.Bronze); // 059 Bernardo Silva
_addOriginalChecklistItem(60, RarityTier.Bronze); // 060 Kompany
_addOriginalChecklistItem(61, RarityTier.Bronze); // 061 Moutinho
_addOriginalChecklistItem(62, RarityTier.Bronze); // 062 Alderweireld
_addOriginalChecklistItem(63, RarityTier.Bronze); // 063 Forsberg
_addOriginalChecklistItem(64, RarityTier.Bronze); // 064 Mandžukić
_addOriginalChecklistItem(65, RarityTier.Bronze); // 065 Milinković-Savić
// Move to the next deploy step.
deployStep = DeployStep.WaitingForStepThree;
}
/// @dev Deploys Originals #066 through #099.
function deployStepThree() external onlyOwner {
require(deployStep == DeployStep.WaitingForStepThree, "You're not following the steps in order...");
/* ORIGINALS - BRONZE (066 to 099) */
_addOriginalChecklistItem(66, RarityTier.Bronze); // 066 Kagawa
_addOriginalChecklistItem(67, RarityTier.Bronze); // 067 Xhaka
_addOriginalChecklistItem(68, RarityTier.Bronze); // 068 Christensen
_addOriginalChecklistItem(69, RarityTier.Bronze); // 069 Zieliński
_addOriginalChecklistItem(70, RarityTier.Bronze); // 070 Smolov
_addOriginalChecklistItem(71, RarityTier.Bronze); // 071 Shaqiri
_addOriginalChecklistItem(72, RarityTier.Bronze); // 072 Rashford
_addOriginalChecklistItem(73, RarityTier.Bronze); // 073 Hernández
_addOriginalChecklistItem(74, RarityTier.Bronze); // 074 Lozano
_addOriginalChecklistItem(75, RarityTier.Bronze); // 075 Ziyech
_addOriginalChecklistItem(76, RarityTier.Bronze); // 076 Moses
_addOriginalChecklistItem(77, RarityTier.Bronze); // 077 Farfán
_addOriginalChecklistItem(78, RarityTier.Bronze); // 078 Elneny
_addOriginalChecklistItem(79, RarityTier.Bronze); // 079 Berg
_addOriginalChecklistItem(80, RarityTier.Bronze); // 080 Ochoa
_addOriginalChecklistItem(81, RarityTier.Bronze); // 081 Akinfeev
_addOriginalChecklistItem(82, RarityTier.Bronze); // 082 Azmoun
_addOriginalChecklistItem(83, RarityTier.Bronze); // 083 Cueva
_addOriginalChecklistItem(84, RarityTier.Bronze); // 084 Khazri
_addOriginalChecklistItem(85, RarityTier.Bronze); // 085 Honda
_addOriginalChecklistItem(86, RarityTier.Bronze); // 086 Cahill
_addOriginalChecklistItem(87, RarityTier.Bronze); // 087 Mikel
_addOriginalChecklistItem(88, RarityTier.Bronze); // 088 Sung-yueng
_addOriginalChecklistItem(89, RarityTier.Bronze); // 089 Ruiz
_addOriginalChecklistItem(90, RarityTier.Bronze); // 090 Yoshida
_addOriginalChecklistItem(91, RarityTier.Bronze); // 091 Al Abed
_addOriginalChecklistItem(92, RarityTier.Bronze); // 092 Chung-yong
_addOriginalChecklistItem(93, RarityTier.Bronze); // 093 Gómez
_addOriginalChecklistItem(94, RarityTier.Bronze); // 094 Sliti
_addOriginalChecklistItem(95, RarityTier.Bronze); // 095 Ghoochannejhad
_addOriginalChecklistItem(96, RarityTier.Bronze); // 096 Jedinak
_addOriginalChecklistItem(97, RarityTier.Bronze); // 097 Al-Sahlawi
_addOriginalChecklistItem(98, RarityTier.Bronze); // 098 Gunnarsson
_addOriginalChecklistItem(99, RarityTier.Bronze); // 099 Pérez
// Move to the next deploy step.
deployStep = DeployStep.WaitingForStepFour;
}
/// @dev Deploys all Iconics and marks the deploy as complete!
function deployStepFour() external onlyOwner {
require(deployStep == DeployStep.WaitingForStepFour, "You're not following the steps in order...");
/* ICONICS */
_addIconicChecklistItem(0, RarityTier.IconicInsert); // 100 Messi
_addIconicChecklistItem(1, RarityTier.IconicInsert); // 101 Ronaldo
_addIconicChecklistItem(2, RarityTier.IconicInsert); // 102 Neymar
_addIconicChecklistItem(3, RarityTier.IconicInsert); // 103 Salah
_addIconicChecklistItem(4, RarityTier.IconicInsert); // 104 Lewandowski
_addIconicChecklistItem(5, RarityTier.IconicInsert); // 105 De Bruyne
_addIconicChecklistItem(6, RarityTier.IconicInsert); // 106 Modrić
_addIconicChecklistItem(7, RarityTier.IconicInsert); // 107 Hazard
_addIconicChecklistItem(8, RarityTier.IconicInsert); // 108 Ramos
_addIconicChecklistItem(9, RarityTier.IconicInsert); // 109 Kroos
_addIconicChecklistItem(10, RarityTier.IconicInsert); // 110 Suárez
_addIconicChecklistItem(11, RarityTier.IconicInsert); // 111 Kane
_addIconicChecklistItem(12, RarityTier.IconicInsert); // 112 Agüero
_addIconicChecklistItem(15, RarityTier.IconicInsert); // 113 de Gea
_addIconicChecklistItem(16, RarityTier.IconicInsert); // 114 Griezmann
_addIconicChecklistItem(17, RarityTier.IconicReferral); // 115 Kanté
_addIconicChecklistItem(18, RarityTier.IconicReferral); // 116 Cavani
_addIconicChecklistItem(19, RarityTier.IconicInsert); // 117 Pogba
_addIconicChecklistItem(21, RarityTier.IconicInsert); // 118 Marcelo
_addIconicChecklistItem(24, RarityTier.IconicInsert); // 119 James
_addIconicChecklistItem(26, RarityTier.IconicInsert); // 120 Eriksen
_addIconicChecklistItem(29, RarityTier.IconicReferral); // 121 Thiago
_addIconicChecklistItem(36, RarityTier.IconicReferral); // 122 Hummels
_addIconicChecklistItem(38, RarityTier.IconicReferral); // 123 Özil
_addIconicChecklistItem(39, RarityTier.IconicInsert); // 124 Son
_addIconicChecklistItem(46, RarityTier.IconicInsert); // 125 Mané
_addIconicChecklistItem(48, RarityTier.IconicInsert); // 126 Alli
_addIconicChecklistItem(49, RarityTier.IconicReferral); // 127 Navas
_addIconicChecklistItem(73, RarityTier.IconicInsert); // 128 Hernández
_addIconicChecklistItem(85, RarityTier.IconicInsert); // 129 Honda
_addIconicChecklistItem(100, RarityTier.IconicReferral); // 130 Alves
_addIconicChecklistItem(101, RarityTier.IconicReferral); // 131 Zlatan
// Mark the initial deploy as complete.
deployStep = DeployStep.DoneInitialDeploy;
}
/// @dev Returns the mint limit for a given checklist item, based on its tier.
/// @param _checklistId Which checklist item we need to get the limit for.
/// @return How much of this checklist item we are allowed to mint.
function limitForChecklistId(uint8 _checklistId) external view returns (uint16) {
RarityTier rarityTier;
uint8 index;
if (_checklistId < 100) { // Originals = #000 to #099
rarityTier = originalChecklistItems[_checklistId].tier;
} else if (_checklistId < 200) { // Iconics = #100 to #131
index = _checklistId - 100;
require(index < iconicsCount(), "This Iconics checklist item doesn't exist.");
rarityTier = iconicChecklistItems[index].tier;
} else { // Unreleased = #200 to max #255
index = _checklistId - 200;
require(index < unreleasedCount(), "This Unreleased checklist item doesn't exist.");
rarityTier = unreleasedChecklistItems[index].tier;
}
return tierLimits[uint8(rarityTier)];
}
}
/// @title Base contract for CryptoStrikers. Defines what a card is and how to mint one.
/// @author The CryptoStrikers Team
contract StrikersBase is ERC721Token("CryptoStrikers", "STRK") {
/// @dev Emit this event whenever we mint a new card (see _mintCard below)
event CardMinted(uint256 cardId);
/// @dev The struct representing the game's main object, a sports trading card.
struct Card {
// The timestamp at which this card was minted.
// With uint32 we are good until 2106, by which point we will have not minted
// a card in like, 88 years.
uint32 mintTime;
// The checklist item represented by this card. See StrikersChecklist.sol for more info.
uint8 checklistId;
// Cards for a given player have a serial number, which gets
// incremented in sequence. For example, if we mint 1000 of a card,
// the third one to be minted has serialNumber = 3 (out of 1000).
uint16 serialNumber;
}
/*** STORAGE ***/
/// @dev All the cards that have been minted, indexed by cardId.
Card[] public cards;
/// @dev Keeps track of how many cards we have minted for a given checklist item
/// to make sure we don't go over the limit for it.
/// NB: uint16 has a capacity of 65,535, but we are not minting more than
/// 4,352 of any given checklist item.
mapping (uint8 => uint16) public mintedCountForChecklistId;
/// @dev A reference to our checklist contract, which contains all the minting limits.
StrikersChecklist public strikersChecklist;
/*** FUNCTIONS ***/
/// @dev For a given owner, returns two arrays. The first contains the IDs of every card owned
/// by this address. The second returns the corresponding checklist ID for each of these cards.
/// There are a few places we need this info in the web app and short of being able to return an
/// actual array of Cards, this is the best solution we could come up with...
function cardAndChecklistIdsForOwner(address _owner) external view returns (uint256[], uint8[]) {
uint256[] memory cardIds = ownedTokens[_owner];
uint256 cardCount = cardIds.length;
uint8[] memory checklistIds = new uint8[](cardCount);
for (uint256 i = 0; i < cardCount; i++) {
uint256 cardId = cardIds[i];
checklistIds[i] = cards[cardId].checklistId;
}
return (cardIds, checklistIds);
}
/// @dev An internal method that creates a new card and stores it.
/// Emits both a CardMinted and a Transfer event.
/// @param _checklistId The ID of the checklistItem represented by the card (see Checklist.sol)
/// @param _owner The card's first owner!
function _mintCard(
uint8 _checklistId,
address _owner
)
internal
returns (uint256)
{
uint16 mintLimit = strikersChecklist.limitForChecklistId(_checklistId);
require(mintLimit == 0 || mintedCountForChecklistId[_checklistId] < mintLimit, "Can't mint any more of this card!");
uint16 serialNumber = ++mintedCountForChecklistId[_checklistId];
Card memory newCard = Card({
mintTime: uint32(now),
checklistId: _checklistId,
serialNumber: serialNumber
});
uint256 newCardId = cards.push(newCard) - 1;
emit CardMinted(newCardId);
_mint(_owner, newCardId);
return newCardId;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
/// @title The contract that exposes minting functions to the outside world and limits who can call them.
/// @author The CryptoStrikers Team
contract StrikersMinting is StrikersBase, Pausable {
/// @dev Emit this when we decide to no longer mint a given checklist ID.
event PulledFromCirculation(uint8 checklistId);
/// @dev If the value for a checklistId is true, we can no longer mint it.
mapping (uint8 => bool) public outOfCirculation;
/// @dev The address of the contract that manages the pack sale.
address public packSaleAddress;
/// @dev Only the owner can update the address of the pack sale contract.
/// @param _address The address of the new StrikersPackSale contract.
function setPackSaleAddress(address _address) external onlyOwner {
packSaleAddress = _address;
}
/// @dev Allows the contract at packSaleAddress to mint cards.
/// @param _checklistId The checklist item represented by this new card.
/// @param _owner The card's first owner!
/// @return The new card's ID.
function mintPackSaleCard(uint8 _checklistId, address _owner) external returns (uint256) {
require(msg.sender == packSaleAddress, "Only the pack sale contract can mint here.");
require(!outOfCirculation[_checklistId], "Can't mint any more of this checklist item...");
return _mintCard(_checklistId, _owner);
}
/// @dev Allows the owner to mint cards from our Unreleased Set.
/// @param _checklistId The checklist item represented by this new card. Must be >= 200.
/// @param _owner The card's first owner!
function mintUnreleasedCard(uint8 _checklistId, address _owner) external onlyOwner {
require(_checklistId >= 200, "You can only use this to mint unreleased cards.");
require(!outOfCirculation[_checklistId], "Can't mint any more of this checklist item...");
_mintCard(_checklistId, _owner);
}
/// @dev Allows the owner or the pack sale contract to prevent an Iconic or Unreleased card from ever being minted again.
/// @param _checklistId The Iconic or Unreleased card we want to remove from circulation.
function pullFromCirculation(uint8 _checklistId) external {
bool ownerOrPackSale = (msg.sender == owner) || (msg.sender == packSaleAddress);
require(ownerOrPackSale, "Only the owner or pack sale can take checklist items out of circulation.");
require(_checklistId >= 100, "This function is reserved for Iconics and Unreleased sets.");
outOfCirculation[_checklistId] = true;
emit PulledFromCirculation(_checklistId);
}
}
/// @title StrikersTrading - Allows users to trustlessly trade cards.
/// @author The CryptoStrikers Team
contract StrikersTrading is StrikersMinting {
/// @dev Emitting this allows us to look up if a trade has been
/// successfully filled, by who, and which cards were involved.
event TradeFilled(
bytes32 indexed tradeHash,
address indexed maker,
uint256 makerCardId,
address indexed taker,
uint256 takerCardId
);
/// @dev Emitting this allows us to look up if a trade has been cancelled.
event TradeCancelled(bytes32 indexed tradeHash, address indexed maker);
/// @dev All the possible states for a trade.
enum TradeState {
Valid,
Filled,
Cancelled
}
/// @dev Mapping of tradeHash => TradeState. Defaults to Valid.
mapping (bytes32 => TradeState) public tradeStates;
/// @dev A taker (someone who has received a signed trade hash)
/// submits a cardId to this function and, if it satisfies
/// the given criteria, the trade is executed.
/// @param _maker Address of the maker (i.e. trade creator).
/// @param _makerCardId ID of the card the maker has agreed to give up.
/// @param _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!)
/// @param _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. "any Originals John Smith").
/// If not, then it's a card ID (e.g. "Originals John Smith #8/100").
/// @param _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks).
/// @param _submittedCardId The card the taker is using to fill the trade. Must satisfy either the card or checklist ID
/// specified in _takerCardOrChecklistId.
/// @param _v ECDSA signature parameter v from the tradeHash signed by the maker.
/// @param _r ECDSA signature parameters r from the tradeHash signed by the maker.
/// @param _s ECDSA signature parameters s from the tradeHash signed by the maker.
function fillTrade(
address _maker,
uint256 _makerCardId,
address _taker,
uint256 _takerCardOrChecklistId,
uint256 _salt,
uint256 _submittedCardId,
uint8 _v,
bytes32 _r,
bytes32 _s)
external
whenNotPaused
{
require(_maker != msg.sender, "You can't fill your own trade.");
require(_taker == address(0) || _taker == msg.sender, "You are not authorized to fill this trade.");
if (_taker == address(0)) {
// This trade is open to the public so we are requesting a checklistItem, rather than a specific card.
require(cards[_submittedCardId].checklistId == _takerCardOrChecklistId, "The card you submitted is not valid for this trade.");
} else {
// We are trading directly with another user and are requesting a specific card.
require(_submittedCardId == _takerCardOrChecklistId, "The card you submitted is not valid for this trade.");
}
bytes32 tradeHash = getTradeHash(
_maker,
_makerCardId,
_taker,
_takerCardOrChecklistId,
_salt
);
require(tradeStates[tradeHash] == TradeState.Valid, "This trade is no longer valid.");
require(isValidSignature(_maker, tradeHash, _v, _r, _s), "Invalid signature.");
tradeStates[tradeHash] = TradeState.Filled;
// For better UX, we assume that by signing the trade, the maker has given
// implicit approval for this token to be transferred. This saves us from an
// extra approval transaction...
tokenApprovals[_makerCardId] = msg.sender;
safeTransferFrom(_maker, msg.sender, _makerCardId);
safeTransferFrom(msg.sender, _maker, _submittedCardId);
emit TradeFilled(tradeHash, _maker, _makerCardId, msg.sender, _submittedCardId);
}
/// @dev Allows the maker to cancel a trade that hasn't been filled yet.
/// @param _maker Address of the maker (i.e. trade creator).
/// @param _makerCardId ID of the card the maker has agreed to give up.
/// @param _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!)
/// @param _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. "any Lionel Messi").
/// If not, then it's a card ID (e.g. "Lionel Messi #8/100").
/// @param _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks).
function cancelTrade(
address _maker,
uint256 _makerCardId,
address _taker,
uint256 _takerCardOrChecklistId,
uint256 _salt)
external
{
require(_maker == msg.sender, "Only the trade creator can cancel this trade.");
bytes32 tradeHash = getTradeHash(
_maker,
_makerCardId,
_taker,
_takerCardOrChecklistId,
_salt
);
require(tradeStates[tradeHash] == TradeState.Valid, "This trade has already been cancelled or filled.");
tradeStates[tradeHash] = TradeState.Cancelled;
emit TradeCancelled(tradeHash, _maker);
}
/// @dev Calculates Keccak-256 hash of a trade with specified parameters.
/// @param _maker Address of the maker (i.e. trade creator).
/// @param _makerCardId ID of the card the maker has agreed to give up.
/// @param _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!)
/// @param _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. "any Lionel Messi").
/// If not, then it's a card ID (e.g. "Lionel Messi #8/100").
/// @param _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks).
/// @return Keccak-256 hash of trade.
function getTradeHash(
address _maker,
uint256 _makerCardId,
address _taker,
uint256 _takerCardOrChecklistId,
uint256 _salt)
public
view
returns (bytes32)
{
// Hashing the contract address prevents a trade from being replayed on any new trade contract we deploy.
bytes memory packed = abi.encodePacked(this, _maker, _makerCardId, _taker, _takerCardOrChecklistId, _salt);
return keccak256(packed);
}
/// @dev Verifies that a signed trade is valid.
/// @param _signer Address of signer.
/// @param _tradeHash Signed Keccak-256 hash.
/// @param _v ECDSA signature parameter v.
/// @param _r ECDSA signature parameters r.
/// @param _s ECDSA signature parameters s.
/// @return Validity of signature.
function isValidSignature(
address _signer,
bytes32 _tradeHash,
uint8 _v,
bytes32 _r,
bytes32 _s)
public
pure
returns (bool)
{
bytes memory packed = abi.encodePacked("\x19Ethereum Signed Message:\n32", _tradeHash);
return _signer == ecrecover(keccak256(packed), _v, _r, _s);
}
}
/// @title The main, ERC721-compliant CryptoStrikers contract.
/// @author The CryptoStrikers Team
contract StrikersCore is StrikersTrading {
/// @dev An external metadata contract that the owner can upgrade.
StrikersMetadata public strikersMetadata;
/// @dev We initialize the CryptoStrikers game with an immutable checklist that oversees card rarity.
constructor(address _checklistAddress) public {
strikersChecklist = StrikersChecklist(_checklistAddress);
}
/// @dev Allows the contract owner to update the metadata contract.
function setMetadataAddress(address _contractAddress) external onlyOwner {
strikersMetadata = StrikersMetadata(_contractAddress);
}
/// @dev If we've set an external metadata contract, use that.
function tokenURI(uint256 _tokenId) public view returns (string) {
if (strikersMetadata == address(0)) {
return super.tokenURI(_tokenId);
}
require(exists(_tokenId), "Card does not exist.");
return strikersMetadata.tokenURI(_tokenId);
}
}
|
A taker (someone who has received a signed trade hash) submits a cardId to this function and, if it satisfies the given criteria, the trade is executed. _maker Address of the maker (i.e. trade creator). _makerCardId ID of the card the maker has agreed to give up. _taker The counterparty the maker wishes to trade with (if it's address(0), anybody can fill the trade!) _takerCardOrChecklistId If taker is the 0-address, then this is a checklist ID (e.g. "any Originals John Smith"). If not, then it's a card ID (e.g. "Originals John Smith 8/100"). _salt A uint256 timestamp to differentiate trades that have otherwise identical params (prevents replay attacks). _submittedCardId The card the taker is using to fill the trade. Must satisfy either the card or checklist ID specified in _takerCardOrChecklistId. _v ECDSA signature parameter v from the tradeHash signed by the maker. _r ECDSA signature parameters r from the tradeHash signed by the maker. _s ECDSA signature parameters s from the tradeHash signed by the maker. This trade is open to the public so we are requesting a checklistItem, rather than a specific card. We are trading directly with another user and are requesting a specific card.
|
function fillTrade(
address _maker,
uint256 _makerCardId,
address _taker,
uint256 _takerCardOrChecklistId,
uint256 _salt,
uint256 _submittedCardId,
uint8 _v,
bytes32 _r,
bytes32 _s)
external
whenNotPaused
{
require(_maker != msg.sender, "You can't fill your own trade.");
require(_taker == address(0) || _taker == msg.sender, "You are not authorized to fill this trade.");
if (_taker == address(0)) {
require(cards[_submittedCardId].checklistId == _takerCardOrChecklistId, "The card you submitted is not valid for this trade.");
require(_submittedCardId == _takerCardOrChecklistId, "The card you submitted is not valid for this trade.");
}
bytes32 tradeHash = getTradeHash(
_maker,
_makerCardId,
_taker,
_takerCardOrChecklistId,
_salt
);
require(tradeStates[tradeHash] == TradeState.Valid, "This trade is no longer valid.");
require(isValidSignature(_maker, tradeHash, _v, _r, _s), "Invalid signature.");
tradeStates[tradeHash] = TradeState.Filled;
safeTransferFrom(_maker, msg.sender, _makerCardId);
safeTransferFrom(msg.sender, _maker, _submittedCardId);
emit TradeFilled(tradeHash, _maker, _makerCardId, msg.sender, _submittedCardId);
}
| 5,349,960 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
pragma abicoder v2;
interface IPayment {
function collectETH() external returns (uint amount);
function collectTokens(address token) external returns (uint amount);
}
interface IforbitspaceX is IPayment {
struct SwapParam {
address addressToApprove;
address exchangeTarget;
address tokenIn; // tokenFrom
address tokenOut; // tokenTo
bytes swapData;
}
function aggregate(
address tokenIn,
address tokenOut,
uint amountInTotal,
address recipient,
SwapParam[] calldata params
) external payable returns (uint amountInAcutual, uint amountOutAcutual);
}
//
/**
* @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 (uint);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint);
/**
* @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, uint 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 (uint);
/**
* @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, uint 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,
uint 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, uint 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, uint value);
}
//
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint 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, uint 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,
uint 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,
uint 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);
}
}
}
}
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint 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,
uint value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint value
) internal {
uint newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint value
) internal {
unchecked {
uint oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint a, uint b) internal pure returns (bool, uint) {
unchecked {
uint 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(uint a, uint b) internal pure returns (bool, uint) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint a, uint b) internal pure returns (bool, uint) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint 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(uint a, uint b) internal pure returns (bool, uint) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint a, uint b) internal pure returns (bool, uint) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint a, uint b) internal pure returns (uint) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b) internal pure returns (uint) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint a, uint b) internal pure returns (uint) {
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(uint a, uint b) internal pure returns (uint) {
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(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint a,
uint b,
string memory errorMessage
) internal pure returns (uint) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
//
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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;
}
}
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);
}
}
interface IWETH is IERC20 {
/// @notice Deposit ether to get wrapped ether
function deposit() external payable;
/// @notice Withdraw wrapped ether to get ether
function withdraw(uint) external;
}
abstract contract Payment is IPayment, Ownable {
using SafeMath for uint;
using SafeERC20 for IERC20;
address public constant ETH_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
address public immutable WETH_ADDRESS;
receive() external payable {}
constructor(address _WETH) {
WETH_ADDRESS = _WETH;
}
function approve(
address addressToApprove,
address token,
uint amount
) internal {
if (IERC20(token).allowance(address(this), addressToApprove) < amount) {
IERC20(token).safeApprove(addressToApprove, 0);
IERC20(token).safeIncreaseAllowance(addressToApprove, type(uint).max);
}
}
function balanceOf(address token) internal view returns (uint bal) {
if (token == ETH_ADDRESS) {
token = WETH_ADDRESS;
}
bal = IERC20(token).balanceOf(address(this));
}
function pay(
address payer,
address recipient,
address token,
uint amount
) internal {
if (amount > 0) {
if (payer == address(this)) {
if (token == ETH_ADDRESS) {
if (balanceOf(WETH_ADDRESS) > 0) IWETH(WETH_ADDRESS).withdraw(balanceOf(WETH_ADDRESS));
Address.sendValue(payable(recipient), amount);
} else {
IERC20(token).safeTransfer(recipient, amount);
}
} else {
if (token == ETH_ADDRESS) {
IWETH(WETH_ADDRESS).deposit{ value: amount }();
} else {
IERC20(token).safeTransferFrom(payer, address(this), amount);
}
}
}
}
function collectETH() public override returns (uint amount) {
if (balanceOf(WETH_ADDRESS) > 0) {
IWETH(WETH_ADDRESS).withdraw(balanceOf(WETH_ADDRESS));
}
if ((amount = address(this).balance) > 0) {
Address.sendValue(payable(owner()), amount);
}
}
function collectTokens(address token) public override returns (uint amount) {
if (token == ETH_ADDRESS) {
amount = collectETH();
} else if ((amount = balanceOf(token)) > 0) {
IERC20(token).safeTransfer(owner(), amount);
}
}
}
//
contract forbitspaceX is IforbitspaceX, Payment {
using SafeMath for uint;
using Address for address;
constructor(address _WETH) Payment(_WETH) {}
function aggregate(
address tokenIn,
address tokenOut,
uint amountInTotal,
address recipient,
SwapParam[] calldata params
) public payable override returns (uint amountInActual, uint amountOutActual) {
// check invalid tokens address
require(!(tokenIn == tokenOut), "I_T_A");
require(!(tokenIn == ETH_ADDRESS && tokenOut == WETH_ADDRESS), "I_T_A");
require(!(tokenIn == WETH_ADDRESS && tokenOut == ETH_ADDRESS), "I_T_A");
// check invalid value
if (tokenIn == ETH_ADDRESS) {
amountInTotal = msg.value;
} else {
require(msg.value == 0, "I_V");
}
require(amountInTotal > 0, "I_V");
pay(_msgSender(), address(this), tokenIn, amountInTotal);
// amountAcutual before
amountInActual = balanceOf(tokenIn);
amountOutActual = balanceOf(tokenOut);
// call swap on multi dexs
_swap(params);
// amountAcutual after
amountInActual = amountInActual.sub(balanceOf(tokenIn));
amountOutActual = balanceOf(tokenOut).sub(amountOutActual);
require((amountInActual > 0) && (amountOutActual > 0), "I_A_T_A"); // incorrect actual total amounts
pay(address(this), _msgSender(), tokenIn, amountInTotal.sub(amountInActual, "N_E_T")); // not enough tokens
pay(address(this), recipient, tokenOut, amountOutActual.mul(9995).div(10000)); // 0.05% fee
// sweep token for owner
collectTokens(tokenIn);
collectTokens(tokenOut);
}
function _swap(SwapParam[] calldata params) private {
for (uint i = 0; i < params.length; i++) {
SwapParam calldata p = params[i];
(
address exchangeTarget,
address addressToApprove,
address tokenIn,
address tokenOut,
bytes calldata swapData
) = (p.exchangeTarget, p.addressToApprove, p.tokenIn, p.tokenOut, p.swapData);
approve(addressToApprove, tokenIn, type(uint).max);
uint amountInActual = balanceOf(tokenIn);
uint amountOutActual = balanceOf(tokenOut);
exchangeTarget.functionCall(swapData, "L_C_F"); // low-level call failed
amountInActual = amountInActual.sub(balanceOf(tokenIn));
amountOutActual = balanceOf(tokenOut).sub(amountOutActual);
require((amountInActual > 0) && (amountOutActual > 0), "I_A_A"); // incorrect actual amounts
}
}
}
|
Returns the multiplication of two unsigned integers, with an overflow flag. _Available since v3.4._/ 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
|
function tryMul(uint a, uint b) internal pure returns (bool, uint) {
unchecked {
if (a == 0) return (true, 0);
uint c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
| 406,700 |
./full_match/1/0x289B297994CbEcF8B6829F4bB0FA78ED7E3713e0/sources/contracts/ETH/PresaleV2.sol
|
to initialize staking manager with new addredd _stakingManagerAddress address of the staking smartcontract/
|
function setStakingManager(
address _stakingManagerAddress
) external onlyOwner {
require(
_stakingManagerAddress != address(0),
"staking manager cannot be inatialized with zero address"
);
stakingManagerInterface = StakingManager(_stakingManagerAddress);
IERC20Upgradeable(saleToken).approve(
_stakingManagerAddress,
type(uint256).max
);
}
| 8,315,928 |
./partial_match/1/0x2f102b13B0e5510e1c64350a56b33769f57C8A62/sources/CommonCents.sol
|
Set whether contract should distribute tax automatically/
|
function toggleSwap(bool _swapEnabled) external onlyOwner {
swapEnabled = _swapEnabled;
}
| 2,837,447 |
pragma solidity ^0.4.25;
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
contract FlightSuretyData {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
address private contractOwner; // Account used to deploy contract
bool private operational = true; // Blocks all state changes throughout the contract if false
uint private funds;
struct Insurance {
address owner;
bytes32 key;
uint256 amount;
}
struct Airline { //Struct to classify an airline and hold relevant info
string name;
string abbreviation;
bool isRegistered;
bool isAuthorized;
}
uint constant M = 4; //constant M refers to number of airlines needed to use multi-party consensus
uint private registeredAirlineCount = 0;
mapping (address => mapping(address => bool)) private multiCalls;
address[] multiCallsArray = new address[](0); //array of addresses that have called the registerFlight function
mapping(address => Airline) public airlines; // Mapping for storing employees. Question: Does this contract have to inheret from the app contract in order to use a mapping that maps to an Airline type? (airline type is stored in the app contract, maybe this will have to change)
mapping(address => uint256) private authorizedAirlines; // Mapping for airlines authorized
Insurance[] private insurance;
mapping(address => uint256) private credit;
uint private totalFunding = 0; //total funding is the bank for the insurance program. When a new airline joins, this var increases by 10 ether
mapping(address => uint256) private voteCounter;
mapping(address => bool) private authorizedCallers;
/********************************************************************************************/
/* EVENT DEFINITIONS */
/********************************************************************************************/
/**
* @dev Constructor
* The deploying account becomes contractOwner
*/
constructor () public {
contractOwner = msg.sender;
}
/********************************************************************************************/
/* 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(operational, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the msg.sender to be a registered airline
*/
modifier requireIsRegisteredAirline()
{
require(isRegisteredAirline() == true, "Airline is not registered");
_;
}
/**
* @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 msg.value to be at least 10 ether in order to fund the contract
*/
modifier canFund() {
require(msg.value >= 10 ether, "Caller does not have funds to support registration.");
_;
}
/**
* @dev Modifier that distributes change back to the msg.sender upon registration
*/
modifier registrationChange() {
uint _price = 10 ether;
uint amountToReturn = msg.value - _price;
msg.sender.transfer(amountToReturn);
_;
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Get operating status of contract
*
* @return A bool that is the current operating status
*/
function isOperational() public view returns(bool) {
return operational;
}
/**
* @dev Authorize app contracts to access data contract
*
*/
function authorizeCaller(address contractAddress) external requireContractOwner {
authorizedCallers[contractAddress] = true;
}
/**
* @dev Get registration status of an airline
*
* @return A bool that is the current registration status
*/
function isRegisteredAirline() public view returns(bool) {
if (authorizedAirlines[msg.sender] == 1) {
return true;
} else {
return false;
}
}
/**
* @dev Sets contract operations on/off
*
* When operational mode is disabled, all write transactions except for this one will fail
//Questions on this...
function setOperatingStatus (bool mode) external requireContractOwner {
require(mode != operational, "New mode must be different from existing mode");
require(airlines[msg.sender], "Caller must be registered as an Airline");
bool isDuplicate = false;
operational = mode;
}
/**
* @dev Get airline name
*
* @return the name field in the Airline struct, helding in the airlines mapping
*/
// function getAirline(address addy) public view returns(Airline) {
// return airlines[addy];
//}
/**
* @dev Get airline abbreviation
*
* @return the abbreviation field in the Airline struct, helding in the airlines mapping
*/
function getAirlineAbreviation() public view returns(string) {
return airlines[msg.sender].abbreviation;
}
/**
* @dev Get airline count
*
* @return the count of registered airlines in the system (not authorized)
*/
function getRegisteredAirlineCount() public view returns(uint) {
return registeredAirlineCount;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev register initial airline
*/
function registerInitialAirline(address airlineAccount) external {
//declare the new Airline newAirline1 in memory
Airline memory newAirline1;
//Use the . notation to access members of the Struct "Airline"
newAirline1.name = "Default Airline";
newAirline1.abbreviation = "ABC";
newAirline1.isRegistered = true;
newAirline1.isAuthorized = false;
//Add Airline to mapping that stores registered Airlines
airlines[airlineAccount] = newAirline1;
}
/**
* @dev Buy insurance for a flight
* I'm implementing this as a mapping to keep track of who owns insurance on which flightSuretyApp
* I created a new struct and mapping to handle this functionality
* I think it should work
function buy (address airline, string flight, uint256 timestamp, uint256 amount) external payable {
require(msg.value == amount, "Transaction is suspect");
if (amount > 1) {
uint256 creditAmount = amount - 1;
creditInsurees(msg.sender, creditAmount);
}
bytes32 key = getFlightKey(airline, flight, timestamp);
Insurance newInsurance = Insurance(msg.sender, key, amount);
insurance.push(newInsurance);
}*/
/**
* @dev Credits payouts to insurees
function creditInsurees (address airline, string flight, uint256 timestamp) external pure {
flightKey = getFlightKey(airline, flight, timestamp);
for (uint i=0; i < insurance.length; i++) {
if (insurance[i].key == flightKey) {
credit[insurance[i].owner] = mul(insurance[i].amount, 1.5);
}
}
}
/**
* @dev Transfers eligible payout funds to insuree
*
function pay ( ) external pure {
require(credit[msg.sender] > 0, "Caller does not have any credit");
uint256 amountToReturn = credit[msg.sender];
credit[msg.sender] = 0;
msg.sender.transfer(amountToReturn);
}*/
/**
* @dev Initial funding for the insurance. Unless there are too many delayed flights
* resulting in insurance payouts, the contract should be self-sustaining
*
*/
function fund () public canFund registrationChange payable {
totalFunding = totalFunding.add(10 ether); // does this make the 10 ether come out of the msg.value?
authorizedAirlines[msg.sender] = 1;
}
function getFlightKey ( address airline, string memory flight, uint256 timestamp ) internal pure returns(bytes32) {
return keccak256(abi.encodePacked(airline, flight, timestamp));
}
/**
* @dev Fallback function for funding smart contract.
*
*/
function() external payable {
fund();
}
}
|
Get airline abbreviation return the abbreviation field in the Airline struct, helding in the airlines mapping/
|
function getAirlineAbreviation() public view returns(string) {
return airlines[msg.sender].abbreviation;
}
| 15,836,763 |
./full_match/1/0x30e0c3ee6cBe2B9bDACa9d620a274796E7eea71A/sources/contracts/CrowdPool/Meter/CrowdPool.sol
|
Set token token info
|
function init_private(SharedStructs.CrowdPoolInfo memory _crowdpool_info)
external
{
require(msg.sender == manage_addr, "Only manage address is available");
crowdpool_info = _crowdpool_info;
tokeninfo.name = IERC20Metadata(_crowdpool_info.pool_token).name();
tokeninfo.symbol = IERC20Metadata(_crowdpool_info.pool_token).symbol();
tokeninfo.decimal = IERC20Metadata(_crowdpool_info.pool_token).decimals();
tokeninfo.totalsupply = IERC20Metadata(_crowdpool_info.pool_token)
.totalSupply();
}
| 8,384,596 |
./partial_match/42/0xcb9A85F1B0f19f778804B75712264d75D6ACBA3F/sources/MasterChef2.sol
|
update rank after withdrawing
|
function updateTopRankAfterWithdraw(uint256 _pid, uint256 _oracleWeight) private{
uint256[] memory rankPidIndex = rankPoolIndex;
uint256 existIndex = rankPidIndex.length;
for(uint256 i = 0; i < rankPidIndex.length; i ++){
if(rankPidIndex[i] == _pid){
existIndex = i;
break;
}
}
return;
if(_oracleWeight == 0){
rankPoolIndex[existIndex] = rankPidIndex[rankPidIndex.length - 1];
rankPoolIndex.pop();
return;
}
if(existIndex == rankPidIndex.length - 1){
return;
}
uint256 lastPoolOraclWeight = calculateOracleWeight(rankPidIndex[rankPidIndex.length - 1], 0, false);
if(lastPoolOraclWeight > _oracleWeight){
rankPoolIndex[existIndex] = rankPidIndex[rankPidIndex.length - 1];
rankPoolIndex[rankPidIndex.length - 1] = _pid;
}
}
| 3,368,127 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.