file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
|---|---|---|---|
./full_match/3/0x0ACb19bf5eE38389B3877020276eB5621663e818/sources/CustomNFT.sol
|
Mint tokens by user. Users can call this function and pay for "gas" for token minting Owner needs to sign the tokenId Reverts if tokenId already exists Reverts if owner has not signed tokenId tokenId Id of NFT to be minted r signature s signature v recovery id of signature _fees Fees to be used in secondary market/
|
function mint(
uint256 tokenId,
address to,
uint8 v, bytes32 r, bytes32 s,
Fee[] memory _fees,
string memory uri
)
public
noEmergencyFreeze
returns (bool)
{
bytes32 message = getMessageForMint(tokenId, to, _fees);
require(isAdmin(getSigner(message,r,s,v)), "admin signature is required");
super._mint(to, tokenId, uri);
super.addFees(tokenId, _fees);
return true;
}
| 8,099,841
|
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @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.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/CraNFTy.sol
pragma solidity 0.8.12;
contract CraNFTy is ERC721Enumerable, Ownable {
using Address for address;
// Maximum limit of NFTs that can ever exist
uint256 public constant MAX_SUPPLY = 10000;
// Maximum limit of mint per transaction
uint256 public constant MAX_MINT_PER_TX = 5;
// Starting and stopping stage and whitelist
bool public stageActive = false;
bool public whitelistActive = false;
// Reserved for the team, customs, giveaways, collabs and so on.
uint256 public reserved;
// Price of each token
uint256 public price;
// Maximum limit of mintable token of current stage
uint256 public maxStageSupply;
// The base link that leads to the image / video of the token
string public baseTokenURI;
// List of addresses that have a number of reserved tokens for whitelist
mapping (address => uint256) public whitelistReserved;
constructor () ERC721 ("Craft NFTy", "CFT") {
maxStageSupply = 0;
price = 50000000000000000;
reserved = 200;
baseTokenURI = "https://api.cranfty.com/";
}
// Override so the openzeppelin tokenURI() method will use this method to create the full tokenURI instead
function _baseURI() internal view virtual override returns (string memory) {
return baseTokenURI;
}
// See which address owns which NFTs
function NFTsOfOwner(address _addr) public view returns(uint256[] memory) {
uint256 tokenCount = balanceOf(_addr);
uint256[] memory tokensId = new uint256[](tokenCount);
for(uint256 i; i < tokenCount; i++){
tokensId[i] = tokenOfOwnerByIndex(_addr, i);
}
return tokensId;
}
// Standart mint function
function mintNFT(uint256 _amountNFTs) public payable {
uint256 supply = totalSupply();
require( stageActive, "Stage not active" );
require( _amountNFTs > 0 && _amountNFTs <= MAX_MINT_PER_TX, "Can only mint between 1 and 5 NFTs at once" );
require( supply + _amountNFTs <= MAX_SUPPLY, "Cannot mint more than max supply" );
require( supply + _amountNFTs <= maxStageSupply, "Cannot mint more than the supply of this stage" );
require( msg.value == price * _amountNFTs, "Wrong amount of ETH sent" );
for(uint256 i; i < _amountNFTs; i++){
_safeMint( msg.sender, supply + i );
}
}
// Whitelist mint function
function mintNFTWhitelist(uint256 _amountNFTs) public payable {
uint256 supply = totalSupply();
uint256 reservedAmt = whitelistReserved[msg.sender];
require( whitelistActive, "Whitelist not active" );
require( reservedAmt > 0, "No NFTs reserved for your address" );
require( _amountNFTs <= reservedAmt, "Cannot mint more than the amount reserved for your wallet" );
require( supply + _amountNFTs <= MAX_SUPPLY, "Cannot mint more than max supply" );
require( msg.value == price * _amountNFTs, "Wrong amount of ETH sent" );
whitelistReserved[msg.sender] = reservedAmt - _amountNFTs;
for(uint256 i; i < _amountNFTs; i++){
_safeMint( msg.sender, supply + i );
}
}
// Admin minting function to reserve tokens for the team, collabs, customs and giveaways
function mintNFTReserved(uint256 _amountNFTs) public onlyOwner {
// Limited to a publicly set amount
require( _amountNFTs <= reserved, "Cannot mint more than the amount reserved" );
reserved -= _amountNFTs;
uint256 supply = totalSupply();
for(uint256 i; i < _amountNFTs; i++){
_safeMint( msg.sender, supply + i );
}
}
// Edit reserved whitelist spots
function editWhitelistReserved(address[] memory _a, uint256[] memory _amountNFTs) public onlyOwner {
for(uint256 i; i < _a.length; i++){
whitelistReserved[_a[i]] = _amountNFTs[i];
}
}
// Start and stop whitelist
function setWhitelistActive(bool _whitelistActivation) public onlyOwner {
whitelistActive = _whitelistActivation;
}
// Start stage sale
function setStageActive(bool _stageActivation, uint256 _newSupply, uint256 _newPrice) public onlyOwner {
stageActive = _stageActivation;
maxStageSupply = _newSupply;
price = _newPrice;
}
// Set a different price in case ETH changes drastically
function setPrice(uint256 _newPrice) public onlyOwner {
price = _newPrice;
}
// Set new baseURI
function setBaseURI(string memory _bURI) public onlyOwner {
baseTokenURI = _bURI;
}
// This will payout the owner the contract balance
function withdraw() public payable onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
}
|
Edit reserved whitelist spots
|
function editWhitelistReserved(address[] memory _a, uint256[] memory _amountNFTs) public onlyOwner {
for(uint256 i; i < _a.length; i++){
whitelistReserved[_a[i]] = _amountNFTs[i];
}
}
| 13,672,761
|
//SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.12;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./interfaces/IOptions.sol";
import "./interfaces/IHegexoption.sol";
/**
* @author [email protected]
* @title Option factory aka Mighty Option Chef
* @notice Option Chef has the monopoly to mint and destroy NFT Hegexoptions
*/
contract OptionChef is Ownable {
//storage
IHegicOptions public hegicOption;
IHegexoption public hegexoption;
//ideally this should've been a mapping/arr of id->Struct {owner, id}
//there are a few EVM gotchas for this (afaik one can't peek into
//mapped structs from another contracts, happy to restructure if I'm wrong though)
mapping (uint => uint) uIds;
mapping (uint => uint) ids;
//events
event Wrapped(address account, uint optionId);
event Unwrapped(address account, uint tokenId);
event Exercised(uint _tokenId, uint profit);
event CreatedHegic(uint optionId, uint hegexId);
//utility functions
function updateHegicOption(IHegicOptions _hegicOption)
external
onlyOwner {
hegicOption = _hegicOption ;
}
function updateHegexoption(IHegexoption _hegexoption)
external
onlyOwner {
hegexoption = _hegexoption;
}
constructor(IHegicOptions _hegicOption) public {
hegicOption = _hegicOption ;
}
//core (un)wrap functionality
/**
* @notice Hegexoption wrapper adapter for Hegic
*/
function wrapHegic(uint _uId) public returns (uint newTokenId) {
require(ids[_uId] == 0 , "UOPT:exists");
(, address holder, , , , , , ) = hegicOption.options(_uId);
//auth is a bit unintuitive for wrapping, see NFT.sol:isApprovedOrOwner()
require(holder == msg.sender || holder == address(this), "UOPT:ownership");
newTokenId = hegexoption.mintHegexoption(msg.sender);
uIds[newTokenId] = _uId;
ids[_uId] = newTokenId;
emit Wrapped(msg.sender, _uId);
}
/**
* @notice Hegexoption unwrapper adapter for Hegic
* @notice check burning logic, do we really want to burn it (vs meta)
* @notice TODO recheck escrow mechanism on 0x relay to prevent unwrapping when locked
*/
function unwrapHegic(uint _tokenId) external onlyTokenOwner(_tokenId) {
// checks if hegicOption will allow to transfer option ownership
(IHegicOptions.State state, , , , , , uint expiration ,) = getUnderlyingOptionParams(_tokenId);
if (state == IHegicOptions.State.Active || expiration >= block.timestamp) {
hegicOption.transfer(uIds[_tokenId], msg.sender);
}
//burns anyway if token is expired
hegexoption.burnHegexoption(_tokenId);
ids[uIds[_tokenId]] = 0;
uIds[_tokenId] = 0;
emit Unwrapped(msg.sender, _tokenId);
}
function exerciseHegic(uint _tokenId) external onlyTokenOwner(_tokenId) {
hegicOption.exercise(getUnderlyingOptionId(_tokenId));
uint profit = address(this).balance;
payable(msg.sender).transfer(profit);
emit Exercised(_tokenId, profit);
}
function getUnderlyingOptionId(uint _tokenId) public view returns (uint) {
return uIds[_tokenId];
}
function getUnderlyingOptionParams(uint _tokenId)
public
view
returns (
IHegicOptions.State state,
address payable holder,
uint256 strike,
uint256 amount,
uint256 lockedAmount,
uint256 premium,
uint256 expiration,
IHegicOptions.OptionType optionType)
{
(state,
holder,
strike,
amount,
lockedAmount,
premium,
expiration,
optionType) = hegicOption.options(uIds[_tokenId]);
}
/**
* @notice check whether Chef has underlying option locked
*/
function isDelegated(uint _tokenId) public view returns (bool) {
( , address holder, , , , , , ) = hegicOption.options(uIds[_tokenId]);
return holder == address(this);
}
function createHegic(
uint _period,
uint _amount,
uint _strike,
IHegicOptions.OptionType _optionType
)
payable
external
returns (uint)
{
uint optionId = hegicOption.create{value: msg.value}(_period, _amount, _strike, _optionType);
// return eth excess
payable(msg.sender).transfer(address(this).balance);
uint hegexId = wrapHegic(optionId);
return hegexId;
emit CreatedHegic(optionId, hegexId);
}
modifier onlyTokenOwner(uint _itemId) {
require(msg.sender == hegexoption.ownerOf(_itemId), "UOPT:ownership/exchange");
_;
}
receive() external payable {}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.12;
interface IHegexoption {
//custom functions in use
function burnHegexoption(uint _id) external;
function mintHegexoption(address _to) external returns (uint256);
//IERC721 functions in use
function ownerOf(uint256 tokenId) external view returns (address owner);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.12;
interface IHegicOptions {
event Create(
uint256 indexed id,
address indexed account,
uint256 settlementFee,
uint256 totalFee
);
event Exercise(uint256 indexed id, uint256 profit);
event Expire(uint256 indexed id, uint256 premium);
enum State {Inactive, Active, Exercised, Expired}
enum OptionType {Invalid, Put, Call}
struct Option {
State state;
address payable holder;
uint256 strike;
uint256 amount;
uint256 lockedAmount;
uint256 premium;
uint256 expiration;
OptionType optionType;
}
function create(
uint256 period,
uint256 amount,
uint256 strike,
OptionType optionType
)
external
payable
returns (uint256 optionID);
function transfer(uint256 optionID, address payable newHolder) external;
function exercise(uint256 optionID) external;
function options(uint) external view returns (
State state,
address payable holder,
uint256 strike,
uint256 amount,
uint256 lockedAmount,
uint256 premium,
uint256 expiration,
OptionType optionType
);
function unlock(uint256 optionID) external;
}
interface IHegicETHOptions is IHegicOptions {
function fees(
uint256 period,
uint256 amount,
uint256 strike,
OptionType optionType
)
external
view
returns (
uint256 total,
uint256 settlementFee,
uint256 strikeFee,
uint256 periodFee
);
}
interface IHegicERC20Options is IHegicOptions {
function fees(
uint256 period,
uint256 amount,
uint256 strike,
OptionType optionType
)
external
view
returns (
uint256 total,
uint256 totalETH,
uint256 settlementFee,
uint256 strikeFee,
uint256 periodFee
);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
|
custom functions in useIERC721 functions in use
|
interface IHegexoption {
function burnHegexoption(uint _id) external;
function mintHegexoption(address _to) external returns (uint256);
function ownerOf(uint256 tokenId) external view returns (address owner);
}
| 1,527,143
|
/*
* Havven Contract
*
* The collateral token of the Havven stablecoin system.
*
* version: nUSDa.1
* date: 29 Jun 2018
* url: https://github.com/Havven/havven/releases/tag/nUSDa.1
*
* MIT License
* ===========
*
* Copyright (c) 2018 Havven
*
* 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
*/
pragma solidity 0.4.24;
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: SafeDecimalMath.sol
version: 1.0
author: Anton Jurisevic
date: 2018-2-5
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A fixed point decimal library that provides basic mathematical
operations, and checks for unsafe arguments, for example that
would lead to overflows.
Exceptions are thrown whenever those unsafe operations
occur.
-----------------------------------------------------------------
*/
/**
* @title Safely manipulate unsigned fixed-point decimals at a given precision level.
* @dev Functions accepting uints in this contract and derived contracts
* are taken to be such fixed point decimals (including fiat, ether, and nomin quantities).
*/
contract SafeDecimalMath {
/* Number of decimal places in the representation. */
uint8 public constant decimals = 18;
/* The number representing 1.0. */
uint public constant UNIT = 10 ** uint(decimals);
/**
* @return True iff adding x and y will not overflow.
*/
function addIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return x + y >= y;
}
/**
* @return The result of adding x and y, throwing an exception in case of overflow.
*/
function safeAdd(uint x, uint y)
pure
internal
returns (uint)
{
require(x + y >= y);
return x + y;
}
/**
* @return True iff subtracting y from x will not overflow in the negative direction.
*/
function subIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y <= x;
}
/**
* @return The result of subtracting y from x, throwing an exception in case of overflow.
*/
function safeSub(uint x, uint y)
pure
internal
returns (uint)
{
require(y <= x);
return x - y;
}
/**
* @return True iff multiplying x and y would not overflow.
*/
function mulIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
if (x == 0) {
return true;
}
return (x * y) / x == y;
}
/**
* @return The result of multiplying x and y, throwing an exception in case of overflow.
*/
function safeMul(uint x, uint y)
pure
internal
returns (uint)
{
if (x == 0) {
return 0;
}
uint p = x * y;
require(p / x == y);
return p;
}
/**
* @return The result of multiplying x and y, interpreting the operands as fixed-point
* decimals. Throws an exception in case of overflow.
*
* @dev A unit factor is divided out after the product of x and y is evaluated,
* so that product must be less than 2**256.
* Incidentally, the internal division always rounds down: one could have rounded to the nearest integer,
* but then one would be spending a significant fraction of a cent (of order a microether
* at present gas prices) in order to save less than one part in 0.5 * 10^18 per operation, if the operands
* contain small enough fractional components. It would also marginally diminish the
* domain this function is defined upon.
*/
function safeMul_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Divide by UNIT to remove the extra factor introduced by the product. */
return safeMul(x, y) / UNIT;
}
/**
* @return True iff the denominator of x/y is nonzero.
*/
function divIsSafe(uint x, uint y)
pure
internal
returns (bool)
{
return y != 0;
}
/**
* @return The result of dividing x by y, throwing an exception if the divisor is zero.
*/
function safeDiv(uint x, uint y)
pure
internal
returns (uint)
{
/* Although a 0 denominator already throws an exception,
* it is equivalent to a THROW operation, which consumes all gas.
* A require statement emits REVERT instead, which remits remaining gas. */
require(y != 0);
return x / y;
}
/**
* @return The result of dividing x by y, interpreting the operands as fixed point decimal numbers.
* @dev Throws an exception in case of overflow or zero divisor; x must be less than 2^256 / UNIT.
* Internal rounding is downward: a similar caveat holds as with safeDecMul().
*/
function safeDiv_dec(uint x, uint y)
pure
internal
returns (uint)
{
/* Reintroduce the UNIT factor that will be divided out by y. */
return safeDiv(safeMul(x, UNIT), y);
}
/**
* @dev Convert an unsigned integer to a unsigned fixed-point decimal.
* Throw an exception if the result would be out of range.
*/
function intToDec(uint i)
pure
internal
returns (uint)
{
return safeMul(i, UNIT);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Owned.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
date: 2018-2-26
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
An Owned contract, to be inherited by other contracts.
Requires its owner to be explicitly set in the constructor.
Provides an onlyOwner access modifier.
To change owner, the current owner must nominate the next owner,
who then has to accept the nomination. The nomination can be
cancelled before it is accepted by the new owner by having the
previous owner change the nomination (setting it to 0).
-----------------------------------------------------------------
*/
/**
* @title A contract with an owner.
* @notice Contract ownership can be transferred by first nominating the new owner,
* who must then accept the ownership, which prevents accidental incorrect ownership transfers.
*/
contract Owned {
address public owner;
address public nominatedOwner;
/**
* @dev Owned Constructor
*/
constructor(address _owner)
public
{
require(_owner != address(0));
owner = _owner;
emit OwnerChanged(address(0), _owner);
}
/**
* @notice Nominate a new owner of this contract.
* @dev Only the current owner may nominate a new owner.
*/
function nominateNewOwner(address _owner)
external
onlyOwner
{
nominatedOwner = _owner;
emit OwnerNominated(_owner);
}
/**
* @notice Accept the nomination to be owner.
*/
function acceptOwnership()
external
{
require(msg.sender == nominatedOwner);
emit OwnerChanged(owner, nominatedOwner);
owner = nominatedOwner;
nominatedOwner = address(0);
}
modifier onlyOwner
{
require(msg.sender == owner);
_;
}
event OwnerNominated(address newOwner);
event OwnerChanged(address oldOwner, address newOwner);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: SelfDestructible.sol
version: 1.2
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows an inheriting contract to be destroyed after
its owner indicates an intention and then waits for a period
without changing their mind. All ether contained in the contract
is forwarded to a nominated beneficiary upon destruction.
-----------------------------------------------------------------
*/
/**
* @title A contract that can be destroyed by its owner after a delay elapses.
*/
contract SelfDestructible is Owned {
uint public initiationTime;
bool public selfDestructInitiated;
address public selfDestructBeneficiary;
uint public constant SELFDESTRUCT_DELAY = 4 weeks;
/**
* @dev Constructor
* @param _owner The account which controls this contract.
*/
constructor(address _owner)
Owned(_owner)
public
{
require(_owner != address(0));
selfDestructBeneficiary = _owner;
emit SelfDestructBeneficiaryUpdated(_owner);
}
/**
* @notice Set the beneficiary address of this contract.
* @dev Only the contract owner may call this. The provided beneficiary must be non-null.
* @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction.
*/
function setSelfDestructBeneficiary(address _beneficiary)
external
onlyOwner
{
require(_beneficiary != address(0));
selfDestructBeneficiary = _beneficiary;
emit SelfDestructBeneficiaryUpdated(_beneficiary);
}
/**
* @notice Begin the self-destruction counter of this contract.
* Once the delay has elapsed, the contract may be self-destructed.
* @dev Only the contract owner may call this.
*/
function initiateSelfDestruct()
external
onlyOwner
{
initiationTime = now;
selfDestructInitiated = true;
emit SelfDestructInitiated(SELFDESTRUCT_DELAY);
}
/**
* @notice Terminate and reset the self-destruction timer.
* @dev Only the contract owner may call this.
*/
function terminateSelfDestruct()
external
onlyOwner
{
initiationTime = 0;
selfDestructInitiated = false;
emit SelfDestructTerminated();
}
/**
* @notice If the self-destruction delay has elapsed, destroy this contract and
* remit any ether it owns to the beneficiary address.
* @dev Only the contract owner may call this.
*/
function selfDestruct()
external
onlyOwner
{
require(selfDestructInitiated && initiationTime + SELFDESTRUCT_DELAY < now);
address beneficiary = selfDestructBeneficiary;
emit SelfDestructed(beneficiary);
selfdestruct(beneficiary);
}
event SelfDestructTerminated();
event SelfDestructed(address beneficiary);
event SelfDestructInitiated(uint selfDestructDelay);
event SelfDestructBeneficiaryUpdated(address newBeneficiary);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: State.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
contract State is Owned {
// the address of the contract that can modify variables
// this can only be changed by the owner of this contract
address public associatedContract;
constructor(address _owner, address _associatedContract)
Owned(_owner)
public
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== SETTERS ========== */
// Change the associated contract to a new address
function setAssociatedContract(address _associatedContract)
external
onlyOwner
{
associatedContract = _associatedContract;
emit AssociatedContractUpdated(_associatedContract);
}
/* ========== MODIFIERS ========== */
modifier onlyAssociatedContract
{
require(msg.sender == associatedContract);
_;
}
/* ========== EVENTS ========== */
event AssociatedContractUpdated(address associatedContract);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: TokenState.sol
version: 1.1
author: Dominic Romanowski
Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract that holds the state of an ERC20 compliant token.
This contract is used side by side with external state token
contracts, such as Havven and Nomin.
It provides an easy way to upgrade contract logic while
maintaining all user balances and allowances. This is designed
to make the changeover as easy as possible, since mappings
are not so cheap or straightforward to migrate.
The first deployed contract would create this state contract,
using it as its store of balances.
When a new contract is deployed, it links to the existing
state contract, whose owner would then change its associated
contract to the new one.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token State
* @notice Stores balance information of an ERC20 token contract.
*/
contract TokenState is State {
/* ERC20 fields. */
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
/**
* @dev Constructor
* @param _owner The address which controls this contract.
* @param _associatedContract The ERC20 contract whose state this composes.
*/
constructor(address _owner, address _associatedContract)
State(_owner, _associatedContract)
public
{}
/* ========== SETTERS ========== */
/**
* @notice Set ERC20 allowance.
* @dev Only the associated contract may call this.
* @param tokenOwner The authorising party.
* @param spender The authorised party.
* @param value The total value the authorised party may spend on the
* authorising party's behalf.
*/
function setAllowance(address tokenOwner, address spender, uint value)
external
onlyAssociatedContract
{
allowance[tokenOwner][spender] = value;
}
/**
* @notice Set the balance in a given account
* @dev Only the associated contract may call this.
* @param account The account whose value to set.
* @param value The new balance of the given account.
*/
function setBalanceOf(address account, uint value)
external
onlyAssociatedContract
{
balanceOf[account] = value;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxy.sol
version: 1.3
author: Anton Jurisevic
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxy contract that, if it does not recognise the function
being called on it, passes all value and call data to an
underlying target contract.
This proxy has the capacity to toggle between DELEGATECALL
and CALL style proxy functionality.
The former executes in the proxy's context, and so will preserve
msg.sender and store data at the proxy address. The latter will not.
Therefore, any contract the proxy wraps in the CALL style must
implement the Proxyable interface, in order that it can pass msg.sender
into the underlying contract as the state parameter, messageSender.
-----------------------------------------------------------------
*/
contract Proxy is Owned {
Proxyable public target;
bool public useDELEGATECALL;
constructor(address _owner)
Owned(_owner)
public
{}
function setTarget(Proxyable _target)
external
onlyOwner
{
target = _target;
emit TargetUpdated(_target);
}
function setUseDELEGATECALL(bool value)
external
onlyOwner
{
useDELEGATECALL = value;
}
function _emit(bytes callData, uint numTopics,
bytes32 topic1, bytes32 topic2,
bytes32 topic3, bytes32 topic4)
external
onlyTarget
{
uint size = callData.length;
bytes memory _callData = callData;
assembly {
/* The first 32 bytes of callData contain its length (as specified by the abi).
* Length is assumed to be a uint256 and therefore maximum of 32 bytes
* in length. It is also leftpadded to be a multiple of 32 bytes.
* This means moving call_data across 32 bytes guarantees we correctly access
* the data itself. */
switch numTopics
case 0 {
log0(add(_callData, 32), size)
}
case 1 {
log1(add(_callData, 32), size, topic1)
}
case 2 {
log2(add(_callData, 32), size, topic1, topic2)
}
case 3 {
log3(add(_callData, 32), size, topic1, topic2, topic3)
}
case 4 {
log4(add(_callData, 32), size, topic1, topic2, topic3, topic4)
}
}
}
function()
external
payable
{
if (useDELEGATECALL) {
assembly {
/* Copy call data into free memory region. */
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* Forward all gas and call data to the target contract. */
let result := delegatecall(gas, sload(target_slot), free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
/* Revert if the call failed, otherwise return the result. */
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
} else {
/* Here we are as above, but must send the messageSender explicitly
* since we are using CALL rather than DELEGATECALL. */
target.setMessageSender(msg.sender);
assembly {
let free_ptr := mload(0x40)
calldatacopy(free_ptr, 0, calldatasize)
/* We must explicitly forward ether to the underlying contract as well. */
let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0)
returndatacopy(free_ptr, 0, returndatasize)
if iszero(result) { revert(free_ptr, returndatasize) }
return(free_ptr, returndatasize)
}
}
}
modifier onlyTarget {
require(Proxyable(msg.sender) == target);
_;
}
event TargetUpdated(Proxyable newTarget);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Proxyable.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
checked: Mike Spain
approved: Samuel Brooks
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A proxyable contract that works hand in hand with the Proxy contract
to allow for anyone to interact with the underlying contract both
directly and through the proxy.
-----------------------------------------------------------------
*/
// This contract should be treated like an abstract contract
contract Proxyable is Owned {
/* The proxy this contract exists behind. */
Proxy public proxy;
/* The caller of the proxy, passed through to this contract.
* Note that every function using this member must apply the onlyProxy or
* optionalProxy modifiers, otherwise their invocations can use stale values. */
address messageSender;
constructor(address _proxy, address _owner)
Owned(_owner)
public
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setProxy(address _proxy)
external
onlyOwner
{
proxy = Proxy(_proxy);
emit ProxyUpdated(_proxy);
}
function setMessageSender(address sender)
external
onlyProxy
{
messageSender = sender;
}
modifier onlyProxy {
require(Proxy(msg.sender) == proxy);
_;
}
modifier optionalProxy
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
_;
}
modifier optionalProxy_onlyOwner
{
if (Proxy(msg.sender) != proxy) {
messageSender = msg.sender;
}
require(messageSender == owner);
_;
}
event ProxyUpdated(address proxyAddress);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: ExternStateToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A partial ERC20 token contract, designed to operate with a proxy.
To produce a complete ERC20 token, transfer and transferFrom
tokens must be implemented, using the provided _byProxy internal
functions.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state and designed to operate behind a proxy.
*/
contract ExternStateToken is SafeDecimalMath, SelfDestructible, Proxyable {
/* ========== STATE VARIABLES ========== */
/* Stores balances and allowances. */
TokenState public tokenState;
/* Other ERC20 fields.
* Note that the decimals field is defined in SafeDecimalMath.*/
string public name;
string public symbol;
uint public totalSupply;
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _tokenState The TokenState contract address.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState,
string _name, string _symbol, uint _totalSupply,
address _owner)
SelfDestructible(_owner)
Proxyable(_proxy, _owner)
public
{
name = _name;
symbol = _symbol;
totalSupply = _totalSupply;
tokenState = _tokenState;
}
/* ========== VIEWS ========== */
/**
* @notice Returns the ERC20 allowance of one party to spend on behalf of another.
* @param owner The party authorising spending of their funds.
* @param spender The party spending tokenOwner's funds.
*/
function allowance(address owner, address spender)
public
view
returns (uint)
{
return tokenState.allowance(owner, spender);
}
/**
* @notice Returns the ERC20 token balance of a given account.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return tokenState.balanceOf(account);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Set the address of the TokenState contract.
* @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000..
* as balances would be unreachable.
*/
function setTokenState(TokenState _tokenState)
external
optionalProxy_onlyOwner
{
tokenState = _tokenState;
emitTokenStateUpdated(_tokenState);
}
function _internalTransfer(address from, address to, uint value)
internal
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0));
require(to != address(this));
require(to != address(proxy));
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), value));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), value));
emitTransfer(from, to, value);
return true;
}
/**
* @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing
* the onlyProxy or optionalProxy modifiers.
*/
function _transfer_byProxy(address from, address to, uint value)
internal
returns (bool)
{
return _internalTransfer(from, to, value);
}
/**
* @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions
* possessing the optionalProxy or optionalProxy modifiers.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* Insufficient allowance will be handled by the safe subtraction. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, value);
}
/**
* @notice Approves spender to transfer on the message sender's behalf.
*/
function approve(address spender, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
tokenState.setAllowance(sender, spender, value);
emitApproval(sender, spender, value);
return true;
}
/* ========== EVENTS ========== */
event Transfer(address indexed from, address indexed to, uint value);
bytes32 constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)");
function emitTransfer(address from, address to, uint value) internal {
proxy._emit(abi.encode(value), 3, TRANSFER_SIG, bytes32(from), bytes32(to), 0);
}
event Approval(address indexed owner, address indexed spender, uint value);
bytes32 constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)");
function emitApproval(address owner, address spender, uint value) internal {
proxy._emit(abi.encode(value), 3, APPROVAL_SIG, bytes32(owner), bytes32(spender), 0);
}
event TokenStateUpdated(address newTokenState);
bytes32 constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)");
function emitTokenStateUpdated(address newTokenState) internal {
proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: FeeToken.sol
version: 1.3
author: Anton Jurisevic
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A token which also has a configurable fee rate
charged on its transfers. This is designed to be overridden in
order to produce an ERC20-compliant token.
These fees accrue into a pool, from which a nominated authority
may withdraw.
This contract utilises an external state for upgradeability.
-----------------------------------------------------------------
*/
/**
* @title ERC20 Token contract, with detached state.
* Additionally charges fees on each transfer.
*/
contract FeeToken is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* ERC20 members are declared in ExternStateToken. */
/* A percentage fee charged on each transfer. */
uint public transferFeeRate;
/* Fee may not exceed 10%. */
uint constant MAX_TRANSFER_FEE_RATE = UNIT / 10;
/* The address with the authority to distribute fees. */
address public feeAuthority;
/* The address that fees will be pooled in. */
address public constant FEE_ADDRESS = 0xfeefeefeefeefeefeefeefeefeefeefeefeefeef;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor.
* @param _proxy The proxy associated with this contract.
* @param _name Token's ERC20 name.
* @param _symbol Token's ERC20 symbol.
* @param _totalSupply The total supply of the token.
* @param _transferFeeRate The fee rate to charge on transfers.
* @param _feeAuthority The address which has the authority to withdraw fees from the accumulated pool.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, string _name, string _symbol, uint _totalSupply,
uint _transferFeeRate, address _feeAuthority, address _owner)
ExternStateToken(_proxy, _tokenState,
_name, _symbol, _totalSupply,
_owner)
public
{
feeAuthority = _feeAuthority;
/* Constructed transfer fee rate should respect the maximum fee rate. */
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE);
transferFeeRate = _transferFeeRate;
}
/* ========== SETTERS ========== */
/**
* @notice Set the transfer fee, anywhere within the range 0-10%.
* @dev The fee rate is in decimal format, with UNIT being the value of 100%.
*/
function setTransferFeeRate(uint _transferFeeRate)
external
optionalProxy_onlyOwner
{
require(_transferFeeRate <= MAX_TRANSFER_FEE_RATE);
transferFeeRate = _transferFeeRate;
emitTransferFeeRateUpdated(_transferFeeRate);
}
/**
* @notice Set the address of the user/contract responsible for collecting or
* distributing fees.
*/
function setFeeAuthority(address _feeAuthority)
public
optionalProxy_onlyOwner
{
feeAuthority = _feeAuthority;
emitFeeAuthorityUpdated(_feeAuthority);
}
/* ========== VIEWS ========== */
/**
* @notice Calculate the Fee charged on top of a value being sent
* @return Return the fee charged
*/
function transferFeeIncurred(uint value)
public
view
returns (uint)
{
return safeMul_dec(value, transferFeeRate);
/* Transfers less than the reciprocal of transferFeeRate should be completely eaten up by fees.
* This is on the basis that transfers less than this value will result in a nil fee.
* Probably too insignificant to worry about, but the following code will achieve it.
* if (fee == 0 && transferFeeRate != 0) {
* return _value;
* }
* return fee;
*/
}
/**
* @notice The value that you would need to send so that the recipient receives
* a specified value.
*/
function transferPlusFee(uint value)
external
view
returns (uint)
{
return safeAdd(value, transferFeeIncurred(value));
}
/**
* @notice The amount the recipient will receive if you send a certain number of tokens.
*/
function amountReceived(uint value)
public
view
returns (uint)
{
return safeDiv_dec(value, safeAdd(UNIT, transferFeeRate));
}
/**
* @notice Collected fees sit here until they are distributed.
* @dev The balance of the nomin contract itself is the fee pool.
*/
function feePool()
external
view
returns (uint)
{
return tokenState.balanceOf(FEE_ADDRESS);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Base of transfer functions
*/
function _internalTransfer(address from, address to, uint amount, uint fee)
internal
returns (bool)
{
/* Disallow transfers to irretrievable-addresses. */
require(to != address(0));
require(to != address(this));
require(to != address(proxy));
/* Insufficient balance will be handled by the safe subtraction. */
tokenState.setBalanceOf(from, safeSub(tokenState.balanceOf(from), safeAdd(amount, fee)));
tokenState.setBalanceOf(to, safeAdd(tokenState.balanceOf(to), amount));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), fee));
/* Emit events for both the transfer itself and the fee. */
emitTransfer(from, to, amount);
emitTransfer(from, FEE_ADDRESS, fee);
return true;
}
/**
* @notice ERC20 friendly transfer function.
*/
function _transfer_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
uint received = amountReceived(value);
uint fee = safeSub(value, received);
return _internalTransfer(sender, to, received, fee);
}
/**
* @notice ERC20 friendly transferFrom function.
*/
function _transferFrom_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is deducted from the amount sent. */
uint received = amountReceived(value);
uint fee = safeSub(value, received);
/* Reduce the allowance by the amount we're transferring.
* The safeSub call will handle an insufficient allowance. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), value));
return _internalTransfer(from, to, received, fee);
}
/**
* @notice Ability to transfer where the sender pays the fees (not ERC20)
*/
function _transferSenderPaysFee_byProxy(address sender, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
return _internalTransfer(sender, to, value, fee);
}
/**
* @notice Ability to transferFrom where they sender pays the fees (not ERC20).
*/
function _transferFromSenderPaysFee_byProxy(address sender, address from, address to, uint value)
internal
returns (bool)
{
/* The fee is added to the amount sent. */
uint fee = transferFeeIncurred(value);
uint total = safeAdd(value, fee);
/* Reduce the allowance by the amount we're transferring. */
tokenState.setAllowance(from, sender, safeSub(tokenState.allowance(from, sender), total));
return _internalTransfer(from, to, value, fee);
}
/**
* @notice Withdraw tokens from the fee pool into a given account.
* @dev Only the fee authority may call this.
*/
function withdrawFees(address account, uint value)
external
onlyFeeAuthority
returns (bool)
{
require(account != address(0));
/* 0-value withdrawals do nothing. */
if (value == 0) {
return false;
}
/* Safe subtraction ensures an exception is thrown if the balance is insufficient. */
tokenState.setBalanceOf(FEE_ADDRESS, safeSub(tokenState.balanceOf(FEE_ADDRESS), value));
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), value));
emitFeesWithdrawn(account, value);
emitTransfer(FEE_ADDRESS, account, value);
return true;
}
/**
* @notice Donate tokens from the sender's balance into the fee pool.
*/
function donateToFeePool(uint n)
external
optionalProxy
returns (bool)
{
address sender = messageSender;
/* Empty donations are disallowed. */
uint balance = tokenState.balanceOf(sender);
require(balance != 0);
/* safeSub ensures the donor has sufficient balance. */
tokenState.setBalanceOf(sender, safeSub(balance, n));
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), n));
emitFeesDonated(sender, n);
emitTransfer(sender, FEE_ADDRESS, n);
return true;
}
/* ========== MODIFIERS ========== */
modifier onlyFeeAuthority
{
require(msg.sender == feeAuthority);
_;
}
/* ========== EVENTS ========== */
event TransferFeeRateUpdated(uint newFeeRate);
bytes32 constant TRANSFERFEERATEUPDATED_SIG = keccak256("TransferFeeRateUpdated(uint256)");
function emitTransferFeeRateUpdated(uint newFeeRate) internal {
proxy._emit(abi.encode(newFeeRate), 1, TRANSFERFEERATEUPDATED_SIG, 0, 0, 0);
}
event FeeAuthorityUpdated(address newFeeAuthority);
bytes32 constant FEEAUTHORITYUPDATED_SIG = keccak256("FeeAuthorityUpdated(address)");
function emitFeeAuthorityUpdated(address newFeeAuthority) internal {
proxy._emit(abi.encode(newFeeAuthority), 1, FEEAUTHORITYUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event FeesDonated(address indexed donor, uint value);
bytes32 constant FEESDONATED_SIG = keccak256("FeesDonated(address,uint256)");
function emitFeesDonated(address donor, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESDONATED_SIG, bytes32(donor), 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Court.sol
version: 1.2
author: Anton Jurisevic
Mike Spain
Dominic Romanowski
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This provides the nomin contract with a confiscation
facility, if enough havven owners vote to confiscate a target
account's nomins.
This is designed to provide a mechanism to respond to abusive
contracts such as nomin wrappers, which would allow users to
trade wrapped nomins without accruing fees on those transactions.
In order to prevent tyranny, an account may only be frozen if
users controlling at least 30% of the value of havvens participate,
and a two thirds majority is attained in that vote.
In order to prevent tyranny of the majority or mob justice,
confiscation motions are only approved if the havven foundation
approves the result.
This latter requirement may be lifted in future versions.
The foundation, or any user with a sufficient havven balance may
bring a confiscation motion.
A motion lasts for a default period of one week, with a further
confirmation period in which the foundation approves the result.
The latter period may conclude early upon the foundation's decision
to either veto or approve the mooted confiscation motion.
If the confirmation period elapses without the foundation making
a decision, the motion fails.
The weight of a havven holder's vote is determined by examining
their average balance over the last completed fee period prior to
the beginning of a given motion.
Thus, since a fee period can roll over in the middle of a motion,
we must also track a user's average balance of the last two periods.
This system is designed such that it cannot be attacked by users
transferring funds between themselves, while also not requiring them
to lock their havvens for the duration of the vote. This is possible
since any transfer that increases the average balance in one account
will be reflected by an equivalent reduction in the voting weight in
the other.
At present a user may cast a vote only for one motion at a time,
but may cancel their vote at any time except during the confirmation period,
when the vote tallies must remain static until the matter has been settled.
A motion to confiscate the balance of a given address composes
a state machine built of the following states:
Waiting:
- A user with standing brings a motion:
If the target address is not frozen;
initialise vote tallies to 0;
transition to the Voting state.
- An account cancels a previous residual vote:
remain in the Waiting state.
Voting:
- The foundation vetoes the in-progress motion:
transition to the Waiting state.
- The voting period elapses:
transition to the Confirmation state.
- An account votes (for or against the motion):
its weight is added to the appropriate tally;
remain in the Voting state.
- An account cancels its previous vote:
its weight is deducted from the appropriate tally (if any);
remain in the Voting state.
Confirmation:
- The foundation vetoes the completed motion:
transition to the Waiting state.
- The foundation approves confiscation of the target account:
freeze the target account, transfer its nomin balance to the fee pool;
transition to the Waiting state.
- The confirmation period elapses:
transition to the Waiting state.
User votes are not automatically cancelled upon the conclusion of a motion.
Therefore, after a motion comes to a conclusion, if a user wishes to vote
in another motion, they must manually cancel their vote in order to do so.
This procedure is designed to be relatively simple.
There are some things that can be added to enhance the functionality
at the expense of simplicity and efficiency:
- Democratic unfreezing of nomin accounts (induces multiple categories of vote)
- Configurable per-vote durations;
- Vote standing denominated in a fiat quantity rather than a quantity of havvens;
- Confiscate from multiple addresses in a single vote;
We might consider updating the contract with any of these features at a later date if necessary.
-----------------------------------------------------------------
*/
/**
* @title A court contract allowing a democratic mechanism to dissuade token wrappers.
*/
contract Court is SafeDecimalMath, Owned {
/* ========== STATE VARIABLES ========== */
/* The addresses of the token contracts this confiscation court interacts with. */
Havven public havven;
Nomin public nomin;
/* The minimum issued nomin balance required to be considered to have
* standing to begin confiscation proceedings. */
uint public minStandingBalance = 100 * UNIT;
/* The voting period lasts for this duration,
* and if set, must fall within the given bounds. */
uint public votingPeriod = 1 weeks;
uint constant MIN_VOTING_PERIOD = 3 days;
uint constant MAX_VOTING_PERIOD = 4 weeks;
/* Duration of the period during which the foundation may confirm
* or veto a motion that has concluded.
* If set, the confirmation duration must fall within the given bounds. */
uint public confirmationPeriod = 1 weeks;
uint constant MIN_CONFIRMATION_PERIOD = 1 days;
uint constant MAX_CONFIRMATION_PERIOD = 2 weeks;
/* No fewer than this fraction of total available voting power must
* participate in a motion in order for a quorum to be reached.
* The participation fraction required may be set no lower than 10%.
* As a fraction, it is expressed in terms of UNIT, not as an absolute quantity. */
uint public requiredParticipation = 3 * UNIT / 10;
uint constant MIN_REQUIRED_PARTICIPATION = UNIT / 10;
/* At least this fraction of participating votes must be in favour of
* confiscation for the motion to pass.
* The required majority may be no lower than 50%.
* As a fraction, it is expressed in terms of UNIT, not as an absolute quantity. */
uint public requiredMajority = (2 * UNIT) / 3;
uint constant MIN_REQUIRED_MAJORITY = UNIT / 2;
/* The next ID to use for opening a motion.
* The 0 motion ID corresponds to no motion,
* and is used as a null value for later comparison. */
uint nextMotionID = 1;
/* Mapping from motion IDs to target addresses. */
mapping(uint => address) public motionTarget;
/* The ID a motion on an address is currently operating at.
* Zero if no such motion is running. */
mapping(address => uint) public targetMotionID;
/* The timestamp at which a motion began. This is used to determine
* whether a motion is: running, in the confirmation period,
* or has concluded.
* A motion runs from its start time t until (t + votingPeriod),
* and then the confirmation period terminates no later than
* (t + votingPeriod + confirmationPeriod). */
mapping(uint => uint) public motionStartTime;
/* The tallies for and against confiscation of a given balance.
* These are set to zero at the start of a motion, and also on conclusion,
* just to keep the state clean. */
mapping(uint => uint) public votesFor;
mapping(uint => uint) public votesAgainst;
/* The last average balance of a user at the time they voted
* in a particular motion.
* If we did not save this information then we would have to
* disallow transfers into an account lest it cancel a vote
* with greater weight than that with which it originally voted,
* and the fee period rolled over in between. */
// TODO: This may be unnecessary now that votes are forced to be
// within a fee period. Likely possible to delete this.
mapping(address => mapping(uint => uint)) voteWeight;
/* The possible vote types.
* Abstention: not participating in a motion; This is the default value.
* Yea: voting in favour of a motion.
* Nay: voting against a motion. */
enum Vote {Abstention, Yea, Nay}
/* A given account's vote in some confiscation motion.
* This requires the default value of the Vote enum to correspond to an abstention. */
mapping(address => mapping(uint => Vote)) public vote;
/* ========== CONSTRUCTOR ========== */
/**
* @dev Court Constructor.
*/
constructor(Havven _havven, Nomin _nomin, address _owner)
Owned(_owner)
public
{
havven = _havven;
nomin = _nomin;
}
/* ========== SETTERS ========== */
/**
* @notice Set the minimum required havven balance to have standing to bring a motion.
* @dev Only the contract owner may call this.
*/
function setMinStandingBalance(uint balance)
external
onlyOwner
{
/* No requirement on the standing threshold here;
* the foundation can set this value such that
* anyone or no one can actually start a motion. */
minStandingBalance = balance;
}
/**
* @notice Set the length of time a vote runs for.
* @dev Only the contract owner may call this. The proposed duration must fall
* within sensible bounds (3 days to 4 weeks), and must be no longer than a single fee period.
*/
function setVotingPeriod(uint duration)
external
onlyOwner
{
require(MIN_VOTING_PERIOD <= duration &&
duration <= MAX_VOTING_PERIOD);
/* Require that the voting period is no longer than a single fee period,
* So that a single vote can span at most two fee periods. */
require(duration <= havven.feePeriodDuration());
votingPeriod = duration;
}
/**
* @notice Set the confirmation period after a vote has concluded.
* @dev Only the contract owner may call this. The proposed duration must fall
* within sensible bounds (1 day to 2 weeks).
*/
function setConfirmationPeriod(uint duration)
external
onlyOwner
{
require(MIN_CONFIRMATION_PERIOD <= duration &&
duration <= MAX_CONFIRMATION_PERIOD);
confirmationPeriod = duration;
}
/**
* @notice Set the required fraction of all Havvens that need to be part of
* a vote for it to pass.
*/
function setRequiredParticipation(uint fraction)
external
onlyOwner
{
require(MIN_REQUIRED_PARTICIPATION <= fraction);
requiredParticipation = fraction;
}
/**
* @notice Set what portion of voting havvens need to be in the affirmative
* to allow it to pass.
*/
function setRequiredMajority(uint fraction)
external
onlyOwner
{
require(MIN_REQUIRED_MAJORITY <= fraction);
requiredMajority = fraction;
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice There is a motion in progress on the specified
* account, and votes are being accepted in that motion.
*/
function motionVoting(uint motionID)
public
view
returns (bool)
{
return motionStartTime[motionID] < now && now < motionStartTime[motionID] + votingPeriod;
}
/**
* @notice A vote on the target account has concluded, but the motion
* has not yet been approved, vetoed, or closed. */
function motionConfirming(uint motionID)
public
view
returns (bool)
{
/* These values are timestamps, they will not overflow
* as they can only ever be initialised to relatively small values.
*/
uint startTime = motionStartTime[motionID];
return startTime + votingPeriod <= now &&
now < startTime + votingPeriod + confirmationPeriod;
}
/**
* @notice A vote motion either not begun, or it has completely terminated.
*/
function motionWaiting(uint motionID)
public
view
returns (bool)
{
/* These values are timestamps, they will not overflow
* as they can only ever be initialised to relatively small values. */
return motionStartTime[motionID] + votingPeriod + confirmationPeriod <= now;
}
/**
* @notice If the motion was to terminate at this instant, it would pass.
* That is: there was sufficient participation and a sizeable enough majority.
*/
function motionPasses(uint motionID)
public
view
returns (bool)
{
uint yeas = votesFor[motionID];
uint nays = votesAgainst[motionID];
uint totalVotes = safeAdd(yeas, nays);
if (totalVotes == 0) {
return false;
}
uint participation = safeDiv_dec(totalVotes, havven.totalIssuanceLastAverageBalance());
uint fractionInFavour = safeDiv_dec(yeas, totalVotes);
/* We require the result to be strictly greater than the requirement
* to enforce a majority being "50% + 1", and so on. */
return participation > requiredParticipation &&
fractionInFavour > requiredMajority;
}
/**
* @notice Return if the specified account has voted on the specified motion
*/
function hasVoted(address account, uint motionID)
public
view
returns (bool)
{
return vote[account][motionID] != Vote.Abstention;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Begin a motion to confiscate the funds in a given nomin account.
* @dev Only the foundation, or accounts with sufficient havven balances
* may elect to start such a motion.
* @return Returns the ID of the motion that was begun.
*/
function beginMotion(address target)
external
returns (uint)
{
/* A confiscation motion must be mooted by someone with standing. */
require((havven.issuanceLastAverageBalance(msg.sender) >= minStandingBalance) ||
msg.sender == owner);
/* Require that the voting period is longer than a single fee period,
* So that a single vote can span at most two fee periods. */
require(votingPeriod <= havven.feePeriodDuration());
/* There must be no confiscation motion already running for this account. */
require(targetMotionID[target] == 0);
/* Disallow votes on accounts that are currently frozen. */
require(!nomin.frozen(target));
/* It is necessary to roll over the fee period if it has elapsed, or else
* the vote might be initialised having begun in the past. */
havven.rolloverFeePeriodIfElapsed();
uint motionID = nextMotionID++;
motionTarget[motionID] = target;
targetMotionID[target] = motionID;
/* Start the vote at the start of the next fee period */
uint startTime = havven.feePeriodStartTime() + havven.feePeriodDuration();
motionStartTime[motionID] = startTime;
emit MotionBegun(msg.sender, target, motionID, startTime);
return motionID;
}
/**
* @notice Shared vote setup function between voteFor and voteAgainst.
* @return Returns the voter's vote weight. */
function setupVote(uint motionID)
internal
returns (uint)
{
/* There must be an active vote for this target running.
* Vote totals must only change during the voting phase. */
require(motionVoting(motionID));
/* The voter must not have an active vote this motion. */
require(!hasVoted(msg.sender, motionID));
/* The voter may not cast votes on themselves. */
require(msg.sender != motionTarget[motionID]);
uint weight = havven.recomputeLastAverageBalance(msg.sender);
/* Users must have a nonzero voting weight to vote. */
require(weight > 0);
voteWeight[msg.sender][motionID] = weight;
return weight;
}
/**
* @notice The sender casts a vote in favour of confiscation of the
* target account's nomin balance.
*/
function voteFor(uint motionID)
external
{
uint weight = setupVote(motionID);
vote[msg.sender][motionID] = Vote.Yea;
votesFor[motionID] = safeAdd(votesFor[motionID], weight);
emit VotedFor(msg.sender, motionID, weight);
}
/**
* @notice The sender casts a vote against confiscation of the
* target account's nomin balance.
*/
function voteAgainst(uint motionID)
external
{
uint weight = setupVote(motionID);
vote[msg.sender][motionID] = Vote.Nay;
votesAgainst[motionID] = safeAdd(votesAgainst[motionID], weight);
emit VotedAgainst(msg.sender, motionID, weight);
}
/**
* @notice Cancel an existing vote by the sender on a motion
* to confiscate the target balance.
*/
function cancelVote(uint motionID)
external
{
/* An account may cancel its vote either before the confirmation phase
* when the motion is still open, or after the confirmation phase,
* when the motion has concluded.
* But the totals must not change during the confirmation phase itself. */
require(!motionConfirming(motionID));
Vote senderVote = vote[msg.sender][motionID];
/* If the sender has not voted then there is no need to update anything. */
require(senderVote != Vote.Abstention);
/* If we are not voting, there is no reason to update the vote totals. */
if (motionVoting(motionID)) {
if (senderVote == Vote.Yea) {
votesFor[motionID] = safeSub(votesFor[motionID], voteWeight[msg.sender][motionID]);
} else {
/* Since we already ensured that the vote is not an abstention,
* the only option remaining is Vote.Nay. */
votesAgainst[motionID] = safeSub(votesAgainst[motionID], voteWeight[msg.sender][motionID]);
}
/* A cancelled vote is only meaningful if a vote is running. */
emit VoteCancelled(msg.sender, motionID);
}
delete voteWeight[msg.sender][motionID];
delete vote[msg.sender][motionID];
}
/**
* @notice clear all data associated with a motionID for hygiene purposes.
*/
function _closeMotion(uint motionID)
internal
{
delete targetMotionID[motionTarget[motionID]];
delete motionTarget[motionID];
delete motionStartTime[motionID];
delete votesFor[motionID];
delete votesAgainst[motionID];
emit MotionClosed(motionID);
}
/**
* @notice If a motion has concluded, or if it lasted its full duration but not passed,
* then anyone may close it.
*/
function closeMotion(uint motionID)
external
{
require((motionConfirming(motionID) && !motionPasses(motionID)) || motionWaiting(motionID));
_closeMotion(motionID);
}
/**
* @notice The foundation may only confiscate a balance during the confirmation
* period after a motion has passed.
*/
function approveMotion(uint motionID)
external
onlyOwner
{
require(motionConfirming(motionID) && motionPasses(motionID));
address target = motionTarget[motionID];
nomin.freezeAndConfiscate(target);
_closeMotion(motionID);
emit MotionApproved(motionID);
}
/* @notice The foundation may veto a motion at any time. */
function vetoMotion(uint motionID)
external
onlyOwner
{
require(!motionWaiting(motionID));
_closeMotion(motionID);
emit MotionVetoed(motionID);
}
/* ========== EVENTS ========== */
event MotionBegun(address indexed initiator, address indexed target, uint indexed motionID, uint startTime);
event VotedFor(address indexed voter, uint indexed motionID, uint weight);
event VotedAgainst(address indexed voter, uint indexed motionID, uint weight);
event VoteCancelled(address indexed voter, uint indexed motionID);
event MotionClosed(uint indexed motionID);
event MotionVetoed(uint indexed motionID);
event MotionApproved(uint indexed motionID);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Nomin.sol
version: 1.2
author: Anton Jurisevic
Mike Spain
Dominic Romanowski
Kevin Brown
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven-backed nomin stablecoin contract.
This contract issues nomins, which are tokens worth 1 USD each.
Nomins are issuable by Havven holders who have to lock up some
value of their havvens to issue H * Cmax nomins. Where Cmax is
some value less than 1.
A configurable fee is charged on nomin transfers and deposited
into a common pot, which havven holders may withdraw from once
per fee period.
-----------------------------------------------------------------
*/
contract Nomin is FeeToken {
/* ========== STATE VARIABLES ========== */
// The address of the contract which manages confiscation votes.
Court public court;
Havven public havven;
// Accounts which have lost the privilege to transact in nomins.
mapping(address => bool) public frozen;
// Nomin transfers incur a 15 bp fee by default.
uint constant TRANSFER_FEE_RATE = 15 * UNIT / 10000;
string constant TOKEN_NAME = "Nomin USD";
string constant TOKEN_SYMBOL = "nUSD";
/* ========== CONSTRUCTOR ========== */
constructor(address _proxy, TokenState _tokenState, Havven _havven,
uint _totalSupply,
address _owner)
FeeToken(_proxy, _tokenState,
TOKEN_NAME, TOKEN_SYMBOL, _totalSupply,
TRANSFER_FEE_RATE,
_havven, // The havven contract is the fee authority.
_owner)
public
{
require(_proxy != 0 && address(_havven) != 0 && _owner != 0);
// It should not be possible to transfer to the fee pool directly (or confiscate its balance).
frozen[FEE_ADDRESS] = true;
havven = _havven;
}
/* ========== SETTERS ========== */
function setCourt(Court _court)
external
optionalProxy_onlyOwner
{
court = _court;
emitCourtUpdated(_court);
}
function setHavven(Havven _havven)
external
optionalProxy_onlyOwner
{
// havven should be set as the feeAuthority after calling this depending on
// havven's internal logic
havven = _havven;
setFeeAuthority(_havven);
emitHavvenUpdated(_havven);
}
/* ========== MUTATIVE FUNCTIONS ========== */
/* Override ERC20 transfer function in order to check
* whether the recipient account is frozen. Note that there is
* no need to check whether the sender has a frozen account,
* since their funds have already been confiscated,
* and no new funds can be transferred to it.*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transfer_byProxy(messageSender, to, value);
}
/* Override ERC20 transferFrom function in order to check
* whether the recipient account is frozen. */
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transferFrom_byProxy(messageSender, from, to, value);
}
function transferSenderPaysFee(address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transferSenderPaysFee_byProxy(messageSender, to, value);
}
function transferFromSenderPaysFee(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
require(!frozen[to]);
return _transferFromSenderPaysFee_byProxy(messageSender, from, to, value);
}
/* If a confiscation court motion has passed and reached the confirmation
* state, the court may transfer the target account's balance to the fee pool
* and freeze its participation in further transactions. */
function freezeAndConfiscate(address target)
external
onlyCourt
{
// A motion must actually be underway.
uint motionID = court.targetMotionID(target);
require(motionID != 0);
// These checks are strictly unnecessary,
// since they are already checked in the court contract itself.
require(court.motionConfirming(motionID));
require(court.motionPasses(motionID));
require(!frozen[target]);
// Confiscate the balance in the account and freeze it.
uint balance = tokenState.balanceOf(target);
tokenState.setBalanceOf(FEE_ADDRESS, safeAdd(tokenState.balanceOf(FEE_ADDRESS), balance));
tokenState.setBalanceOf(target, 0);
frozen[target] = true;
emitAccountFrozen(target, balance);
emitTransfer(target, FEE_ADDRESS, balance);
}
/* The owner may allow a previously-frozen contract to once
* again accept and transfer nomins. */
function unfreezeAccount(address target)
external
optionalProxy_onlyOwner
{
require(frozen[target] && target != FEE_ADDRESS);
frozen[target] = false;
emitAccountUnfrozen(target);
}
/* Allow havven to issue a certain number of
* nomins from an account. */
function issue(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeAdd(tokenState.balanceOf(account), amount));
totalSupply = safeAdd(totalSupply, amount);
emitTransfer(address(0), account, amount);
emitIssued(account, amount);
}
/* Allow havven to burn a certain number of
* nomins from an account. */
function burn(address account, uint amount)
external
onlyHavven
{
tokenState.setBalanceOf(account, safeSub(tokenState.balanceOf(account), amount));
totalSupply = safeSub(totalSupply, amount);
emitTransfer(account, address(0), amount);
emitBurned(account, amount);
}
/* ========== MODIFIERS ========== */
modifier onlyHavven() {
require(Havven(msg.sender) == havven);
_;
}
modifier onlyCourt() {
require(Court(msg.sender) == court);
_;
}
/* ========== EVENTS ========== */
event CourtUpdated(address newCourt);
bytes32 constant COURTUPDATED_SIG = keccak256("CourtUpdated(address)");
function emitCourtUpdated(address newCourt) internal {
proxy._emit(abi.encode(newCourt), 1, COURTUPDATED_SIG, 0, 0, 0);
}
event HavvenUpdated(address newHavven);
bytes32 constant HAVVENUPDATED_SIG = keccak256("HavvenUpdated(address)");
function emitHavvenUpdated(address newHavven) internal {
proxy._emit(abi.encode(newHavven), 1, HAVVENUPDATED_SIG, 0, 0, 0);
}
event AccountFrozen(address indexed target, uint balance);
bytes32 constant ACCOUNTFROZEN_SIG = keccak256("AccountFrozen(address,uint256)");
function emitAccountFrozen(address target, uint balance) internal {
proxy._emit(abi.encode(balance), 2, ACCOUNTFROZEN_SIG, bytes32(target), 0, 0);
}
event AccountUnfrozen(address indexed target);
bytes32 constant ACCOUNTUNFROZEN_SIG = keccak256("AccountUnfrozen(address)");
function emitAccountUnfrozen(address target) internal {
proxy._emit(abi.encode(), 2, ACCOUNTUNFROZEN_SIG, bytes32(target), 0, 0);
}
event Issued(address indexed account, uint amount);
bytes32 constant ISSUED_SIG = keccak256("Issued(address,uint256)");
function emitIssued(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, ISSUED_SIG, bytes32(account), 0, 0);
}
event Burned(address indexed account, uint amount);
bytes32 constant BURNED_SIG = keccak256("Burned(address,uint256)");
function emitBurned(address account, uint amount) internal {
proxy._emit(abi.encode(amount), 2, BURNED_SIG, bytes32(account), 0, 0);
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: LimitedSetup.sol
version: 1.1
author: Anton Jurisevic
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
A contract with a limited setup period. Any function modified
with the setup modifier will cease to work after the
conclusion of the configurable-length post-construction setup period.
-----------------------------------------------------------------
*/
/**
* @title Any function decorated with the modifier this contract provides
* deactivates after a specified setup period.
*/
contract LimitedSetup {
uint setupExpiryTime;
/**
* @dev LimitedSetup Constructor.
* @param setupDuration The time the setup period will last for.
*/
constructor(uint setupDuration)
public
{
setupExpiryTime = now + setupDuration;
}
modifier onlyDuringSetup
{
require(now < setupExpiryTime);
_;
}
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: HavvenEscrow.sol
version: 1.1
author: Anton Jurisevic
Dominic Romanowski
Mike Spain
date: 2018-05-29
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
This contract allows the foundation to apply unique vesting
schedules to havven funds sold at various discounts in the token
sale. HavvenEscrow gives users the ability to inspect their
vested funds, their quantities and vesting dates, and to withdraw
the fees that accrue on those funds.
The fees are handled by withdrawing the entire fee allocation
for all havvens inside the escrow contract, and then allowing
the contract itself to subdivide that pool up proportionally within
itself. Every time the fee period rolls over in the main Havven
contract, the HavvenEscrow fee pool is remitted back into the
main fee pool to be redistributed in the next fee period.
-----------------------------------------------------------------
*/
/**
* @title A contract to hold escrowed havvens and free them at given schedules.
*/
contract HavvenEscrow is SafeDecimalMath, Owned, LimitedSetup(8 weeks) {
/* The corresponding Havven contract. */
Havven public havven;
/* Lists of (timestamp, quantity) pairs per account, sorted in ascending time order.
* These are the times at which each given quantity of havvens vests. */
mapping(address => uint[2][]) public vestingSchedules;
/* An account's total vested havven balance to save recomputing this for fee extraction purposes. */
mapping(address => uint) public totalVestedAccountBalance;
/* The total remaining vested balance, for verifying the actual havven balance of this contract against. */
uint public totalVestedBalance;
uint constant TIME_INDEX = 0;
uint constant QUANTITY_INDEX = 1;
/* Limit vesting entries to disallow unbounded iteration over vesting schedules. */
uint constant MAX_VESTING_ENTRIES = 20;
/* ========== CONSTRUCTOR ========== */
constructor(address _owner, Havven _havven)
Owned(_owner)
public
{
havven = _havven;
}
/* ========== SETTERS ========== */
function setHavven(Havven _havven)
external
onlyOwner
{
havven = _havven;
emit HavvenUpdated(_havven);
}
/* ========== VIEW FUNCTIONS ========== */
/**
* @notice A simple alias to totalVestedAccountBalance: provides ERC20 balance integration.
*/
function balanceOf(address account)
public
view
returns (uint)
{
return totalVestedAccountBalance[account];
}
/**
* @notice The number of vesting dates in an account's schedule.
*/
function numVestingEntries(address account)
public
view
returns (uint)
{
return vestingSchedules[account].length;
}
/**
* @notice Get a particular schedule entry for an account.
* @return A pair of uints: (timestamp, havven quantity).
*/
function getVestingScheduleEntry(address account, uint index)
public
view
returns (uint[2])
{
return vestingSchedules[account][index];
}
/**
* @notice Get the time at which a given schedule entry will vest.
*/
function getVestingTime(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[TIME_INDEX];
}
/**
* @notice Get the quantity of havvens associated with a given schedule entry.
*/
function getVestingQuantity(address account, uint index)
public
view
returns (uint)
{
return getVestingScheduleEntry(account,index)[QUANTITY_INDEX];
}
/**
* @notice Obtain the index of the next schedule entry that will vest for a given user.
*/
function getNextVestingIndex(address account)
public
view
returns (uint)
{
uint len = numVestingEntries(account);
for (uint i = 0; i < len; i++) {
if (getVestingTime(account, i) != 0) {
return i;
}
}
return len;
}
/**
* @notice Obtain the next schedule entry that will vest for a given user.
* @return A pair of uints: (timestamp, havven quantity). */
function getNextVestingEntry(address account)
public
view
returns (uint[2])
{
uint index = getNextVestingIndex(account);
if (index == numVestingEntries(account)) {
return [uint(0), 0];
}
return getVestingScheduleEntry(account, index);
}
/**
* @notice Obtain the time at which the next schedule entry will vest for a given user.
*/
function getNextVestingTime(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[TIME_INDEX];
}
/**
* @notice Obtain the quantity which the next schedule entry will vest for a given user.
*/
function getNextVestingQuantity(address account)
external
view
returns (uint)
{
return getNextVestingEntry(account)[QUANTITY_INDEX];
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice Withdraws a quantity of havvens back to the havven contract.
* @dev This may only be called by the owner during the contract's setup period.
*/
function withdrawHavvens(uint quantity)
external
onlyOwner
onlyDuringSetup
{
havven.transfer(havven, quantity);
}
/**
* @notice Destroy the vesting information associated with an account.
*/
function purgeAccount(address account)
external
onlyOwner
onlyDuringSetup
{
delete vestingSchedules[account];
totalVestedBalance = safeSub(totalVestedBalance, totalVestedAccountBalance[account]);
delete totalVestedAccountBalance[account];
}
/**
* @notice Add a new vesting entry at a given time and quantity to an account's schedule.
* @dev A call to this should be accompanied by either enough balance already available
* in this contract, or a corresponding call to havven.endow(), to ensure that when
* the funds are withdrawn, there is enough balance, as well as correctly calculating
* the fees.
* This may only be called by the owner during the contract's setup period.
* Note; although this function could technically be used to produce unbounded
* arrays, it's only in the foundation's command to add to these lists.
* @param account The account to append a new vesting entry to.
* @param time The absolute unix timestamp after which the vested quantity may be withdrawn.
* @param quantity The quantity of havvens that will vest.
*/
function appendVestingEntry(address account, uint time, uint quantity)
public
onlyOwner
onlyDuringSetup
{
/* No empty or already-passed vesting entries allowed. */
require(now < time);
require(quantity != 0);
/* There must be enough balance in the contract to provide for the vesting entry. */
totalVestedBalance = safeAdd(totalVestedBalance, quantity);
require(totalVestedBalance <= havven.balanceOf(this));
/* Disallow arbitrarily long vesting schedules in light of the gas limit. */
uint scheduleLength = vestingSchedules[account].length;
require(scheduleLength <= MAX_VESTING_ENTRIES);
if (scheduleLength == 0) {
totalVestedAccountBalance[account] = quantity;
} else {
/* Disallow adding new vested havvens earlier than the last one.
* Since entries are only appended, this means that no vesting date can be repeated. */
require(getVestingTime(account, numVestingEntries(account) - 1) < time);
totalVestedAccountBalance[account] = safeAdd(totalVestedAccountBalance[account], quantity);
}
vestingSchedules[account].push([time, quantity]);
}
/**
* @notice Construct a vesting schedule to release a quantities of havvens
* over a series of intervals.
* @dev Assumes that the quantities are nonzero
* and that the sequence of timestamps is strictly increasing.
* This may only be called by the owner during the contract's setup period.
*/
function addVestingSchedule(address account, uint[] times, uint[] quantities)
external
onlyOwner
onlyDuringSetup
{
for (uint i = 0; i < times.length; i++) {
appendVestingEntry(account, times[i], quantities[i]);
}
}
/**
* @notice Allow a user to withdraw any havvens in their schedule that have vested.
*/
function vest()
external
{
uint numEntries = numVestingEntries(msg.sender);
uint total;
for (uint i = 0; i < numEntries; i++) {
uint time = getVestingTime(msg.sender, i);
/* The list is sorted; when we reach the first future time, bail out. */
if (time > now) {
break;
}
uint qty = getVestingQuantity(msg.sender, i);
if (qty == 0) {
continue;
}
vestingSchedules[msg.sender][i] = [0, 0];
total = safeAdd(total, qty);
}
if (total != 0) {
totalVestedBalance = safeSub(totalVestedBalance, total);
totalVestedAccountBalance[msg.sender] = safeSub(totalVestedAccountBalance[msg.sender], total);
havven.transfer(msg.sender, total);
emit Vested(msg.sender, now, total);
}
}
/* ========== EVENTS ========== */
event HavvenUpdated(address newHavven);
event Vested(address indexed beneficiary, uint time, uint value);
}
/*
-----------------------------------------------------------------
FILE INFORMATION
-----------------------------------------------------------------
file: Havven.sol
version: 1.2
author: Anton Jurisevic
Dominic Romanowski
date: 2018-05-15
-----------------------------------------------------------------
MODULE DESCRIPTION
-----------------------------------------------------------------
Havven token contract. Havvens are transferable ERC20 tokens,
and also give their holders the following privileges.
An owner of havvens may participate in nomin confiscation votes, they
may also have the right to issue nomins at the discretion of the
foundation for this version of the contract.
After a fee period terminates, the duration and fees collected for that
period are computed, and the next period begins. Thus an account may only
withdraw the fees owed to them for the previous period, and may only do
so once per period. Any unclaimed fees roll over into the common pot for
the next period.
== Average Balance Calculations ==
The fee entitlement of a havven holder is proportional to their average
issued nomin balance over the last fee period. This is computed by
measuring the area under the graph of a user's issued nomin balance over
time, and then when a new fee period begins, dividing through by the
duration of the fee period.
We need only update values when the balances of an account is modified.
This occurs when issuing or burning for issued nomin balances,
and when transferring for havven balances. This is for efficiency,
and adds an implicit friction to interacting with havvens.
A havven holder pays for his own recomputation whenever he wants to change
his position, which saves the foundation having to maintain a pot dedicated
to resourcing this.
A hypothetical user's balance history over one fee period, pictorially:
s ____
| |
| |___ p
|____|___|___ __ _ _
f t n
Here, the balance was s between times f and t, at which time a transfer
occurred, updating the balance to p, until n, when the present transfer occurs.
When a new transfer occurs at time n, the balance being p,
we must:
- Add the area p * (n - t) to the total area recorded so far
- Update the last transfer time to n
So if this graph represents the entire current fee period,
the average havvens held so far is ((t-f)*s + (n-t)*p) / (n-f).
The complementary computations must be performed for both sender and
recipient.
Note that a transfer keeps global supply of havvens invariant.
The sum of all balances is constant, and unmodified by any transfer.
So the sum of all balances multiplied by the duration of a fee period is also
constant, and this is equivalent to the sum of the area of every user's
time/balance graph. Dividing through by that duration yields back the total
havven supply. So, at the end of a fee period, we really do yield a user's
average share in the havven supply over that period.
A slight wrinkle is introduced if we consider the time r when the fee period
rolls over. Then the previous fee period k-1 is before r, and the current fee
period k is afterwards. If the last transfer took place before r,
but the latest transfer occurred afterwards:
k-1 | k
s __|_
| | |
| | |____ p
|__|_|____|___ __ _ _
|
f | t n
r
In this situation the area (r-f)*s contributes to fee period k-1, while
the area (t-r)*s contributes to fee period k. We will implicitly consider a
zero-value transfer to have occurred at time r. Their fee entitlement for the
previous period will be finalised at the time of their first transfer during the
current fee period, or when they query or withdraw their fee entitlement.
In the implementation, the duration of different fee periods may be slightly irregular,
as the check that they have rolled over occurs only when state-changing havven
operations are performed.
== Issuance and Burning ==
In this version of the havven contract, nomins can only be issued by
those that have been nominated by the havven foundation. Nomins are assumed
to be valued at $1, as they are a stable unit of account.
All nomins issued require a proportional value of havvens to be locked,
where the proportion is governed by the current issuance ratio. This
means for every $1 of Havvens locked up, $(issuanceRatio) nomins can be issued.
i.e. to issue 100 nomins, 100/issuanceRatio dollars of havvens need to be locked up.
To determine the value of some amount of havvens(H), an oracle is used to push
the price of havvens (P_H) in dollars to the contract. The value of H
would then be: H * P_H.
Any havvens that are locked up by this issuance process cannot be transferred.
The amount that is locked floats based on the price of havvens. If the price
of havvens moves up, less havvens are locked, so they can be issued against,
or transferred freely. If the price of havvens moves down, more havvens are locked,
even going above the initial wallet balance.
-----------------------------------------------------------------
*/
/**
* @title Havven ERC20 contract.
* @notice The Havven contracts does not only facilitate transfers and track balances,
* but it also computes the quantity of fees each havven holder is entitled to.
*/
contract Havven is ExternStateToken {
/* ========== STATE VARIABLES ========== */
/* A struct for handing values associated with average balance calculations */
struct IssuanceData {
/* Sums of balances*duration in the current fee period.
/* range: decimals; units: havven-seconds */
uint currentBalanceSum;
/* The last period's average balance */
uint lastAverageBalance;
/* The last time the data was calculated */
uint lastModified;
}
/* Issued nomin balances for individual fee entitlements */
mapping(address => IssuanceData) public issuanceData;
/* The total number of issued nomins for determining fee entitlements */
IssuanceData public totalIssuanceData;
/* The time the current fee period began */
uint public feePeriodStartTime;
/* The time the last fee period began */
uint public lastFeePeriodStartTime;
/* Fee periods will roll over in no shorter a time than this.
* The fee period cannot actually roll over until a fee-relevant
* operation such as withdrawal or a fee period duration update occurs,
* so this is just a target, and the actual duration may be slightly longer. */
uint public feePeriodDuration = 4 weeks;
/* ...and must target between 1 day and six months. */
uint constant MIN_FEE_PERIOD_DURATION = 1 days;
uint constant MAX_FEE_PERIOD_DURATION = 26 weeks;
/* The quantity of nomins that were in the fee pot at the time */
/* of the last fee rollover, at feePeriodStartTime. */
uint public lastFeesCollected;
/* Whether a user has withdrawn their last fees */
mapping(address => bool) public hasWithdrawnFees;
Nomin public nomin;
HavvenEscrow public escrow;
/* The address of the oracle which pushes the havven price to this contract */
address public oracle;
/* The price of havvens written in UNIT */
uint public price;
/* The time the havven price was last updated */
uint public lastPriceUpdateTime;
/* How long will the contract assume the price of havvens is correct */
uint public priceStalePeriod = 3 hours;
/* A quantity of nomins greater than this ratio
* may not be issued against a given value of havvens. */
uint public issuanceRatio = UNIT / 5;
/* No more nomins may be issued than the value of havvens backing them. */
uint constant MAX_ISSUANCE_RATIO = UNIT;
/* Whether the address can issue nomins or not. */
mapping(address => bool) public isIssuer;
/* The number of currently-outstanding nomins the user has issued. */
mapping(address => uint) public nominsIssued;
uint constant HAVVEN_SUPPLY = 1e8 * UNIT;
uint constant ORACLE_FUTURE_LIMIT = 10 minutes;
string constant TOKEN_NAME = "Havven";
string constant TOKEN_SYMBOL = "HAV";
/* ========== CONSTRUCTOR ========== */
/**
* @dev Constructor
* @param _tokenState A pre-populated contract containing token balances.
* If the provided address is 0x0, then a fresh one will be constructed with the contract owning all tokens.
* @param _owner The owner of this contract.
*/
constructor(address _proxy, TokenState _tokenState, address _owner, address _oracle,
uint _price, address[] _issuers, Havven _oldHavven)
ExternStateToken(_proxy, _tokenState, TOKEN_NAME, TOKEN_SYMBOL, HAVVEN_SUPPLY, _owner)
public
{
oracle = _oracle;
price = _price;
lastPriceUpdateTime = now;
uint i;
if (_oldHavven == address(0)) {
feePeriodStartTime = now;
lastFeePeriodStartTime = now - feePeriodDuration;
for (i = 0; i < _issuers.length; i++) {
isIssuer[_issuers[i]] = true;
}
} else {
feePeriodStartTime = _oldHavven.feePeriodStartTime();
lastFeePeriodStartTime = _oldHavven.lastFeePeriodStartTime();
uint cbs;
uint lab;
uint lm;
(cbs, lab, lm) = _oldHavven.totalIssuanceData();
totalIssuanceData.currentBalanceSum = cbs;
totalIssuanceData.lastAverageBalance = lab;
totalIssuanceData.lastModified = lm;
for (i = 0; i < _issuers.length; i++) {
address issuer = _issuers[i];
isIssuer[issuer] = true;
uint nomins = _oldHavven.nominsIssued(issuer);
if (nomins == 0) {
// It is not valid in general to skip those with no currently-issued nomins.
// But for this release, issuers with nonzero issuanceData have current issuance.
continue;
}
(cbs, lab, lm) = _oldHavven.issuanceData(issuer);
nominsIssued[issuer] = nomins;
issuanceData[issuer].currentBalanceSum = cbs;
issuanceData[issuer].lastAverageBalance = lab;
issuanceData[issuer].lastModified = lm;
}
}
}
/* ========== SETTERS ========== */
/**
* @notice Set the associated Nomin contract to collect fees from.
* @dev Only the contract owner may call this.
*/
function setNomin(Nomin _nomin)
external
optionalProxy_onlyOwner
{
nomin = _nomin;
emitNominUpdated(_nomin);
}
/**
* @notice Set the associated havven escrow contract.
* @dev Only the contract owner may call this.
*/
function setEscrow(HavvenEscrow _escrow)
external
optionalProxy_onlyOwner
{
escrow = _escrow;
emitEscrowUpdated(_escrow);
}
/**
* @notice Set the targeted fee period duration.
* @dev Only callable by the contract owner. The duration must fall within
* acceptable bounds (1 day to 26 weeks). Upon resetting this the fee period
* may roll over if the target duration was shortened sufficiently.
*/
function setFeePeriodDuration(uint duration)
external
optionalProxy_onlyOwner
{
require(MIN_FEE_PERIOD_DURATION <= duration &&
duration <= MAX_FEE_PERIOD_DURATION);
feePeriodDuration = duration;
emitFeePeriodDurationUpdated(duration);
rolloverFeePeriodIfElapsed();
}
/**
* @notice Set the Oracle that pushes the havven price to this contract
*/
function setOracle(address _oracle)
external
optionalProxy_onlyOwner
{
oracle = _oracle;
emitOracleUpdated(_oracle);
}
/**
* @notice Set the stale period on the updated havven price
* @dev No max/minimum, as changing it wont influence anything but issuance by the foundation
*/
function setPriceStalePeriod(uint time)
external
optionalProxy_onlyOwner
{
priceStalePeriod = time;
}
/**
* @notice Set the issuanceRatio for issuance calculations.
* @dev Only callable by the contract owner.
*/
function setIssuanceRatio(uint _issuanceRatio)
external
optionalProxy_onlyOwner
{
require(_issuanceRatio <= MAX_ISSUANCE_RATIO);
issuanceRatio = _issuanceRatio;
emitIssuanceRatioUpdated(_issuanceRatio);
}
/**
* @notice Set whether the specified can issue nomins or not.
*/
function setIssuer(address account, bool value)
external
optionalProxy_onlyOwner
{
isIssuer[account] = value;
emitIssuersUpdated(account, value);
}
/* ========== VIEWS ========== */
function issuanceCurrentBalanceSum(address account)
external
view
returns (uint)
{
return issuanceData[account].currentBalanceSum;
}
function issuanceLastAverageBalance(address account)
external
view
returns (uint)
{
return issuanceData[account].lastAverageBalance;
}
function issuanceLastModified(address account)
external
view
returns (uint)
{
return issuanceData[account].lastModified;
}
function totalIssuanceCurrentBalanceSum()
external
view
returns (uint)
{
return totalIssuanceData.currentBalanceSum;
}
function totalIssuanceLastAverageBalance()
external
view
returns (uint)
{
return totalIssuanceData.lastAverageBalance;
}
function totalIssuanceLastModified()
external
view
returns (uint)
{
return totalIssuanceData.lastModified;
}
/* ========== MUTATIVE FUNCTIONS ========== */
/**
* @notice ERC20 transfer function.
*/
function transfer(address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[sender] == 0 || value <= transferableHavvens(sender));
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transfer_byProxy(sender, to, value);
return true;
}
/**
* @notice ERC20 transferFrom function.
*/
function transferFrom(address from, address to, uint value)
public
optionalProxy
returns (bool)
{
address sender = messageSender;
require(nominsIssued[from] == 0 || value <= transferableHavvens(from));
/* Perform the transfer: if there is a problem,
* an exception will be thrown in this call. */
_transferFrom_byProxy(sender, from, to, value);
return true;
}
/**
* @notice Compute the last period's fee entitlement for the message sender
* and then deposit it into their nomin account.
*/
function withdrawFees()
external
optionalProxy
{
address sender = messageSender;
rolloverFeePeriodIfElapsed();
/* Do not deposit fees into frozen accounts. */
require(!nomin.frozen(sender));
/* Check the period has rolled over first. */
updateIssuanceData(sender, nominsIssued[sender], nomin.totalSupply());
/* Only allow accounts to withdraw fees once per period. */
require(!hasWithdrawnFees[sender]);
uint feesOwed;
uint lastTotalIssued = totalIssuanceData.lastAverageBalance;
if (lastTotalIssued > 0) {
/* Sender receives a share of last period's collected fees proportional
* with their average fraction of the last period's issued nomins. */
feesOwed = safeDiv_dec(
safeMul_dec(issuanceData[sender].lastAverageBalance, lastFeesCollected),
lastTotalIssued
);
}
hasWithdrawnFees[sender] = true;
if (feesOwed != 0) {
nomin.withdrawFees(sender, feesOwed);
}
emitFeesWithdrawn(messageSender, feesOwed);
}
/**
* @notice Update the havven balance averages since the last transfer
* or entitlement adjustment.
* @dev Since this updates the last transfer timestamp, if invoked
* consecutively, this function will do nothing after the first call.
* Also, this will adjust the total issuance at the same time.
*/
function updateIssuanceData(address account, uint preBalance, uint lastTotalSupply)
internal
{
/* update the total balances first */
totalIssuanceData = computeIssuanceData(lastTotalSupply, totalIssuanceData);
if (issuanceData[account].lastModified < feePeriodStartTime) {
hasWithdrawnFees[account] = false;
}
issuanceData[account] = computeIssuanceData(preBalance, issuanceData[account]);
}
/**
* @notice Compute the new IssuanceData on the old balance
*/
function computeIssuanceData(uint preBalance, IssuanceData preIssuance)
internal
view
returns (IssuanceData)
{
uint currentBalanceSum = preIssuance.currentBalanceSum;
uint lastAverageBalance = preIssuance.lastAverageBalance;
uint lastModified = preIssuance.lastModified;
if (lastModified < feePeriodStartTime) {
if (lastModified < lastFeePeriodStartTime) {
/* The balance was last updated before the previous fee period, so the average
* balance in this period is their pre-transfer balance. */
lastAverageBalance = preBalance;
} else {
/* The balance was last updated during the previous fee period. */
/* No overflow or zero denominator problems, since lastFeePeriodStartTime < feePeriodStartTime < lastModified.
* implies these quantities are strictly positive. */
uint timeUpToRollover = feePeriodStartTime - lastModified;
uint lastFeePeriodDuration = feePeriodStartTime - lastFeePeriodStartTime;
uint lastBalanceSum = safeAdd(currentBalanceSum, safeMul(preBalance, timeUpToRollover));
lastAverageBalance = lastBalanceSum / lastFeePeriodDuration;
}
/* Roll over to the next fee period. */
currentBalanceSum = safeMul(preBalance, now - feePeriodStartTime);
} else {
/* The balance was last updated during the current fee period. */
currentBalanceSum = safeAdd(
currentBalanceSum,
safeMul(preBalance, now - lastModified)
);
}
return IssuanceData(currentBalanceSum, lastAverageBalance, now);
}
/**
* @notice Recompute and return the given account's last average balance.
*/
function recomputeLastAverageBalance(address account)
external
returns (uint)
{
updateIssuanceData(account, nominsIssued[account], nomin.totalSupply());
return issuanceData[account].lastAverageBalance;
}
/**
* @notice Issue nomins against the sender's havvens.
* @dev Issuance is only allowed if the havven price isn't stale and the sender is an issuer.
*/
function issueNomins(uint amount)
public
optionalProxy
requireIssuer(messageSender)
/* No need to check if price is stale, as it is checked in issuableNomins. */
{
address sender = messageSender;
require(amount <= remainingIssuableNomins(sender));
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
nomin.issue(sender, amount);
nominsIssued[sender] = safeAdd(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
function issueMaxNomins()
external
optionalProxy
{
issueNomins(remainingIssuableNomins(messageSender));
}
/**
* @notice Burn nomins to clear issued nomins/free havvens.
*/
function burnNomins(uint amount)
/* it doesn't matter if the price is stale or if the user is an issuer, as non-issuers have issued no nomins.*/
external
optionalProxy
{
address sender = messageSender;
uint lastTot = nomin.totalSupply();
uint preIssued = nominsIssued[sender];
/* nomin.burn does a safeSub on balance (so it will revert if there are not enough nomins). */
nomin.burn(sender, amount);
/* This safe sub ensures amount <= number issued */
nominsIssued[sender] = safeSub(preIssued, amount);
updateIssuanceData(sender, preIssued, lastTot);
}
/**
* @notice Check if the fee period has rolled over. If it has, set the new fee period start
* time, and record the fees collected in the nomin contract.
*/
function rolloverFeePeriodIfElapsed()
public
{
/* If the fee period has rolled over... */
if (now >= feePeriodStartTime + feePeriodDuration) {
lastFeesCollected = nomin.feePool();
lastFeePeriodStartTime = feePeriodStartTime;
feePeriodStartTime = now;
emitFeePeriodRollover(now);
}
}
/* ========== Issuance/Burning ========== */
/**
* @notice The maximum nomins an issuer can issue against their total havven quantity. This ignores any
* already issued nomins.
*/
function maxIssuableNomins(address issuer)
view
public
priceNotStale
returns (uint)
{
if (!isIssuer[issuer]) {
return 0;
}
if (escrow != HavvenEscrow(0)) {
uint totalOwnedHavvens = safeAdd(tokenState.balanceOf(issuer), escrow.balanceOf(issuer));
return safeMul_dec(HAVtoUSD(totalOwnedHavvens), issuanceRatio);
} else {
return safeMul_dec(HAVtoUSD(tokenState.balanceOf(issuer)), issuanceRatio);
}
}
/**
* @notice The remaining nomins an issuer can issue against their total havven quantity.
*/
function remainingIssuableNomins(address issuer)
view
public
returns (uint)
{
uint issued = nominsIssued[issuer];
uint max = maxIssuableNomins(issuer);
if (issued > max) {
return 0;
} else {
return safeSub(max, issued);
}
}
/**
* @notice The total havvens owned by this account, both escrowed and unescrowed,
* against which nomins can be issued.
* This includes those already being used as collateral (locked), and those
* available for further issuance (unlocked).
*/
function collateral(address account)
public
view
returns (uint)
{
uint bal = tokenState.balanceOf(account);
if (escrow != address(0)) {
bal = safeAdd(bal, escrow.balanceOf(account));
}
return bal;
}
/**
* @notice The collateral that would be locked by issuance, which can exceed the account's actual collateral.
*/
function issuanceDraft(address account)
public
view
returns (uint)
{
uint issued = nominsIssued[account];
if (issued == 0) {
return 0;
}
return USDtoHAV(safeDiv_dec(issued, issuanceRatio));
}
/**
* @notice Collateral that has been locked due to issuance, and cannot be
* transferred to other addresses. This is capped at the account's total collateral.
*/
function lockedCollateral(address account)
public
view
returns (uint)
{
uint debt = issuanceDraft(account);
uint collat = collateral(account);
if (debt > collat) {
return collat;
}
return debt;
}
/**
* @notice Collateral that is not locked and available for issuance.
*/
function unlockedCollateral(address account)
public
view
returns (uint)
{
uint locked = lockedCollateral(account);
uint collat = collateral(account);
return safeSub(collat, locked);
}
/**
* @notice The number of havvens that are free to be transferred by an account.
* @dev If they have enough available Havvens, it could be that
* their havvens are escrowed, however the transfer would then
* fail. This means that escrowed havvens are locked first,
* and then the actual transferable ones.
*/
function transferableHavvens(address account)
public
view
returns (uint)
{
uint draft = issuanceDraft(account);
uint collat = collateral(account);
// In the case where the issuanceDraft exceeds the collateral, nothing is free
if (draft > collat) {
return 0;
}
uint bal = balanceOf(account);
// In the case where the draft exceeds the escrow, but not the whole collateral
// return the fraction of the balance that remains free
if (draft > safeSub(collat, bal)) {
return safeSub(collat, draft);
}
// In the case where the draft doesn't exceed the escrow, return the entire balance
return bal;
}
/**
* @notice The value in USD for a given amount of HAV
*/
function HAVtoUSD(uint hav_dec)
public
view
priceNotStale
returns (uint)
{
return safeMul_dec(hav_dec, price);
}
/**
* @notice The value in HAV for a given amount of USD
*/
function USDtoHAV(uint usd_dec)
public
view
priceNotStale
returns (uint)
{
return safeDiv_dec(usd_dec, price);
}
/**
* @notice Access point for the oracle to update the price of havvens.
*/
function updatePrice(uint newPrice, uint timeSent)
external
onlyOracle /* Should be callable only by the oracle. */
{
/* Must be the most recently sent price, but not too far in the future.
* (so we can't lock ourselves out of updating the oracle for longer than this) */
require(lastPriceUpdateTime < timeSent && timeSent < now + ORACLE_FUTURE_LIMIT);
price = newPrice;
lastPriceUpdateTime = timeSent;
emitPriceUpdated(newPrice, timeSent);
/* Check the fee period rollover within this as the price should be pushed every 15min. */
rolloverFeePeriodIfElapsed();
}
/**
* @notice Check if the price of havvens hasn't been updated for longer than the stale period.
*/
function priceIsStale()
public
view
returns (bool)
{
return safeAdd(lastPriceUpdateTime, priceStalePeriod) < now;
}
/* ========== MODIFIERS ========== */
modifier requireIssuer(address account)
{
require(isIssuer[account]);
_;
}
modifier onlyOracle
{
require(msg.sender == oracle);
_;
}
modifier priceNotStale
{
require(!priceIsStale());
_;
}
/* ========== EVENTS ========== */
event PriceUpdated(uint newPrice, uint timestamp);
bytes32 constant PRICEUPDATED_SIG = keccak256("PriceUpdated(uint256,uint256)");
function emitPriceUpdated(uint newPrice, uint timestamp) internal {
proxy._emit(abi.encode(newPrice, timestamp), 1, PRICEUPDATED_SIG, 0, 0, 0);
}
event IssuanceRatioUpdated(uint newRatio);
bytes32 constant ISSUANCERATIOUPDATED_SIG = keccak256("IssuanceRatioUpdated(uint256)");
function emitIssuanceRatioUpdated(uint newRatio) internal {
proxy._emit(abi.encode(newRatio), 1, ISSUANCERATIOUPDATED_SIG, 0, 0, 0);
}
event FeePeriodRollover(uint timestamp);
bytes32 constant FEEPERIODROLLOVER_SIG = keccak256("FeePeriodRollover(uint256)");
function emitFeePeriodRollover(uint timestamp) internal {
proxy._emit(abi.encode(timestamp), 1, FEEPERIODROLLOVER_SIG, 0, 0, 0);
}
event FeePeriodDurationUpdated(uint duration);
bytes32 constant FEEPERIODDURATIONUPDATED_SIG = keccak256("FeePeriodDurationUpdated(uint256)");
function emitFeePeriodDurationUpdated(uint duration) internal {
proxy._emit(abi.encode(duration), 1, FEEPERIODDURATIONUPDATED_SIG, 0, 0, 0);
}
event FeesWithdrawn(address indexed account, uint value);
bytes32 constant FEESWITHDRAWN_SIG = keccak256("FeesWithdrawn(address,uint256)");
function emitFeesWithdrawn(address account, uint value) internal {
proxy._emit(abi.encode(value), 2, FEESWITHDRAWN_SIG, bytes32(account), 0, 0);
}
event OracleUpdated(address newOracle);
bytes32 constant ORACLEUPDATED_SIG = keccak256("OracleUpdated(address)");
function emitOracleUpdated(address newOracle) internal {
proxy._emit(abi.encode(newOracle), 1, ORACLEUPDATED_SIG, 0, 0, 0);
}
event NominUpdated(address newNomin);
bytes32 constant NOMINUPDATED_SIG = keccak256("NominUpdated(address)");
function emitNominUpdated(address newNomin) internal {
proxy._emit(abi.encode(newNomin), 1, NOMINUPDATED_SIG, 0, 0, 0);
}
event EscrowUpdated(address newEscrow);
bytes32 constant ESCROWUPDATED_SIG = keccak256("EscrowUpdated(address)");
function emitEscrowUpdated(address newEscrow) internal {
proxy._emit(abi.encode(newEscrow), 1, ESCROWUPDATED_SIG, 0, 0, 0);
}
event IssuersUpdated(address indexed account, bool indexed value);
bytes32 constant ISSUERSUPDATED_SIG = keccak256("IssuersUpdated(address,bool)");
function emitIssuersUpdated(address account, bool value) internal {
proxy._emit(abi.encode(), 3, ISSUERSUPDATED_SIG, bytes32(account), bytes32(value ? 1 : 0), 0);
}
}
|
Cancel an existing vote by the sender on a motion to confiscate the target balance./ An account may cancel its vote either before the confirmation phase when the motion is still open, or after the confirmation phase, when the motion has concluded. But the totals must not change during the confirmation phase itself. / If the sender has not voted then there is no need to update anything. / If we are not voting, there is no reason to update the vote totals. /
|
function cancelVote(uint motionID)
external
{
require(!motionConfirming(motionID));
Vote senderVote = vote[msg.sender][motionID];
require(senderVote != Vote.Abstention);
if (motionVoting(motionID)) {
if (senderVote == Vote.Yea) {
votesFor[motionID] = safeSub(votesFor[motionID], voteWeight[msg.sender][motionID]);
votesAgainst[motionID] = safeSub(votesAgainst[motionID], voteWeight[msg.sender][motionID]);
}
delete voteWeight[msg.sender][motionID];
delete vote[msg.sender][motionID];
}
| 6,482,239
|
pragma solidity ^0.5.0;
// Safe math
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
//not a SafeMath function
function max(uint a, uint b) private pure returns (uint) {
return a > b ? a : b;
}
}
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md
contract ERC20Interface {
function totalSupply() public view returns (uint);
function balanceOf(address tokenOwner) public view returns (uint balance);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// Owned contract
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
/// @title A test contract to store and exchange Dai, Ether, and test INCH tokens.
/// @author Decentralized
/// @notice Use the 4 withdrawel and deposit functions in your this contract to short and long ETH. ETH/Dai price is
/// pegged at 300 to 1. INCH burn rate is 1% per deposit
/// Because there is no UI for this contract, KEEP IN MIND THAT ALL VALUES ARE IN MINIMUM DENOMINATIONS
/// IN OTHER WORDS ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AND INPUT AS 10^-18 * THE BASE UNIT OF CURRENCY
/// Other warnings: This is a test contract. Do not risk any significant value. You are not guaranteed a
/// refund, even if it's my fault. Do not send any tokens or assets directly to the contract.
/// DO NOT SEND ANY TOKENS OR ASSETS DIRECTLY TO THE CONTRACT. Use only the withdrawel and deposit functions
/// @dev Addresses and 'deployership' must be initialized before use. INCH must be deposited in contract
/// Ownership will be set to 0x0 after initialization
contract VaultPOC is Owned {
using SafeMath for uint;
uint public constant initialSupply = 1000000000000000000000;
uint public constant etherPeg = 300;
uint8 public constant burnRate = 1;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
ERC20Interface inchWormContract;
ERC20Interface daiContract;
address deployer; //retains ability to transfer mistaken ERC20s after ownership is revoked
//____________________________________________________________________________________
// Inititialization functions
/// @notice Sets the address for the INCH and Dai tokens, as well as the deployer
function initialize(address _inchwormAddress, address _daiAddress) external onlyOwner {
inchWormContract = ERC20Interface(_inchwormAddress);
daiContract = ERC20Interface(_daiAddress);
deployer = owner;
}
//____________________________________________________________________________________
//____________________________________________________________________________________
// Deposit and withdrawel functions
/* @notice Make a deposit by including payment in function call
Wei deposited will be rewarded with INCH tokens. Exchange rate changes over time
Call will fail with insufficient Wei balance from sender or INCH balance in vault
ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AND INPUT AS 10^-18 * THE BASE UNIT OF CURRENCY
@dev Function will fail if totalSupply < 0.01 * initialSupply.To be fixed
Exchange rate is 1 Wei : 300 * totalSupply/initialSupply *10**-18
*/
function depositWeiForInch() external payable {
uint _percentOfInchRemaining = inchWormContract.totalSupply().mul(100).div(initialSupply);
uint _tokensToWithdraw = msg.value.mul(etherPeg);
_tokensToWithdraw = _tokensToWithdraw.mul(_percentOfInchRemaining).div(100);
inchWormContract.transfer(msg.sender, _tokensToWithdraw);
}
/* @param Dai to deposit in contract, denomination 1*10**-18 Dai
@notice Dai deposited will be rewarded with INCH tokens. Exchange rate changes over time
Call will fail with insufficient Dai balance from sender or INCH balance in vault
ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AND INPUT AS 10^-18 * THE BASE UNIT OF CURRENCY
@dev Exchange rate is 1*10**-18 Dai : totalSupply/initialSupply
*/
function depositDaiForInch(uint _daiToDeposit) external {
uint _percentOfInchRemaining = inchWormContract.totalSupply().mul(100).div(initialSupply);
uint _tokensToWithdraw = _daiToDeposit.mul(_percentOfInchRemaining).div(100);
inchWormContract.transfer(msg.sender, _tokensToWithdraw);
daiContract.transferFrom(msg.sender, address(this), _daiToDeposit);
}
/* @param Wei to withdraw from contract
@notice INCH must be deposited in exchange for the withdrawel. Exchange rate changes over time
Call will fail with insufficient INCH balance from sender or insufficient Wei balance in the vault
1% of INCH deposited is burned
ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AND INPUT AS 10^-18 * THE BASE UNIT OF CURRENCY
@dev Exchange rate is 1 Wei : 300 * totalSupply/initialSupply *10**-18
*/
function withdrawWei(uint _weiToWithdraw) external {
uint _inchToDeposit = _weiToWithdraw.mul(etherPeg).mul((initialSupply.div(inchWormContract.totalSupply())));
inchWormContract.transferFrom(msg.sender, address(this), _inchToDeposit);
uint _inchToBurn = _inchToDeposit.mul(burnRate).div(100);
inchWormContract.transfer(address(0), _inchToBurn);
msg.sender.transfer(1 wei * _weiToWithdraw);
}
/* @param Dai to withdraw from contract, denomination 1*10**-18 Dai
@notice INCH must be deposited in exchange for the withdrawel. Exchange rate changes over time
Call will fail with insufficient INCH balance from sender or insufficient Dai balance in the vault
1% of INCH deposited is burned
ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AND INPUT AS 10^-18 * THE BASE UNIT OF CURRENCY
@dev Exchange rate is 1*10**-18 Dai : totalSupply/initialSupply
*/
function withdrawDai(uint _daiToWithdraw) external {
uint _inchToDeposit = _daiToWithdraw.mul(initialSupply.div(inchWormContract.totalSupply()));
inchWormContract.transferFrom(msg.sender, address(this), _inchToDeposit);
uint _inchToBurn = _inchToDeposit.mul(burnRate).div(100);
inchWormContract.transfer(address(0), _inchToBurn);
daiContract.transfer(msg.sender, _daiToWithdraw);
}
//____________________________________________________________________________________
//____________________________________________________________________________________
// view functions
/// @notice Returns the number of INCH recieved per Dai,
/// ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AS 10^-18 * THE BASE UNIT OF CURRENCY
function getInchDaiRate() public view returns(uint) {
return initialSupply.div(inchWormContract.totalSupply());
}
/// @notice Returns the number of INCH recieved per Eth
/// ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AS 10^-18 * THE BASE UNIT OF CURRENCY
function getInchEthRate() public view returns(uint) {
etherPeg.mul((initialSupply.div(inchWormContract.totalSupply())));
}
/// @notice Returns the Wei balance of the vault contract
/// ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AS 10^-18 * THE BASE UNIT OF CURRENCY
function getEthBalance() public view returns(uint) {
return address(this).balance;
}
/// @notice Returns the INCH balance of the vault contract
/// ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AS 10^-18 * THE BASE UNIT OF CURRENCY
function getInchBalance() public view returns(uint) {
return inchWormContract.balanceOf(address(this));
}
/// @notice Returns the Dai balance of the vault contract
/// ALL TOKENS UNCLUDING ETHER ARE DISPLAYED AS 10^-18 * THE BASE UNIT OF CURRENCY
function getDaiBalance() public view returns(uint) {
return daiContract.balanceOf(address(this));
}
/// @notice Returns the percent of INCH that has not been burned (sent to 0X0)
/// @dev Implicitly floors the result
/// INCH sent to burn addresses other than 0x0 are not currently included in calculation
function getPercentOfInchRemaining() external view returns(uint) {
return inchWormContract.totalSupply().mul(100).div(initialSupply);
}
//____________________________________________________________________________________
//____________________________________________________________________________________
// emergency and fallback functions
/// @notice original deployer can transfer out tokens other than Dai and INCH
function transferAccidentalERC20Tokens(address tokenAddress, uint tokens) external returns (bool success) {
require(msg.sender == deployer);
require(tokenAddress != address(inchWormContract));
require(tokenAddress != address(daiContract));
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
// fallback function
function () external payable {
revert();
}
//____________________________________________________________________________________
}
|
Returns the percent of INCH that has not been burned (sent to 0X0) Implicitly floors the result INCH sent to burn addresses other than 0x0 are not currently included in calculation
|
function getPercentOfInchRemaining() external view returns(uint) {
return inchWormContract.totalSupply().mul(100).div(initialSupply);
}
| 893,042
|
pragma solidity ^0.6.2;
// Aave LendingPool interface
interface ILendingPool {
function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external payable;
function withdraw(address asset, uint256 amount, address to) external;
function getReserveData(address asset) external view returns(
uint256 configuration,
uint128 liquidityIndex,
uint128 variableBorrowIndex,
uint128 currentLiquidityRate,
uint128 currentVariableBorrowRate,
uint128 currentStableBorrowRate,
uint40 lastUpdateTimestamp,
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress,
address interestRateStrategyAddress,
uint8 id
);
}
|
Aave LendingPool interface
|
interface ILendingPool {
function deposit(address asset, uint256 amount, address onBehalfOf, uint16 referralCode) external payable;
function withdraw(address asset, uint256 amount, address to) external;
function getReserveData(address asset) external view returns(
uint256 configuration,
uint128 liquidityIndex,
uint128 variableBorrowIndex,
uint128 currentLiquidityRate,
uint128 currentVariableBorrowRate,
uint128 currentStableBorrowRate,
uint40 lastUpdateTimestamp,
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress,
address interestRateStrategyAddress,
uint8 id
);
}
| 12,987,940
|
pragma solidity >=0.5.10;
import 'ROOT/trading/IOrders.sol';
import 'ROOT/libraries/math/SafeMathUint256.sol';
import 'ROOT/libraries/math/SafeMathInt256.sol';
import 'ROOT/trading/Order.sol';
import 'ROOT/reporting/IMarket.sol';
import 'ROOT/libraries/Initializable.sol';
import 'ROOT/libraries/token/IERC20.sol';
import 'ROOT/trading/IAugurTrading.sol';
import 'ROOT/trading/IProfitLoss.sol';
/**
* @title Orders
* @notice Storage of all data associated with orders
*/
contract Orders is IOrders, Initializable {
using Order for Order.Data;
using SafeMathUint256 for uint256;
struct MarketOrders {
uint256 totalEscrowed;
mapping(uint256 => uint256) prices;
}
mapping(bytes32 => Order.Data) private orders;
mapping(address => MarketOrders) private marketOrderData;
mapping(bytes32 => bytes32) private bestOrder;
mapping(bytes32 => bytes32) private worstOrder;
IAugurTrading public augurTrading;
ICash public cash;
address public trade;
address public fillOrder;
address public cancelOrder;
address public createOrder;
IProfitLoss public profitLoss;
function initialize(IAugur _augur, IAugurTrading _augurTrading) public beforeInitialized {
endInitialization();
cash = ICash(_augur.lookup("Cash"));
augurTrading = _augurTrading;
createOrder = _augurTrading.lookup("CreateOrder");
fillOrder = _augurTrading.lookup("FillOrder");
cancelOrder = _augurTrading.lookup("CancelOrder");
trade = _augurTrading.lookup("Trade");
profitLoss = IProfitLoss(_augurTrading.lookup("ProfitLoss"));
}
/**
* @param _orderId The id of the order
* @return The market associated with the order id
*/
function getMarket(bytes32 _orderId) public view returns (IMarket) {
return orders[_orderId].market;
}
/**
* @param _orderId The id of the order
* @return The order type (BID==0,ASK==1) associated with the order
*/
function getOrderType(bytes32 _orderId) public view returns (Order.Types) {
return orders[_orderId].orderType;
}
/**
* @param _orderId The id of the order
* @return The outcome associated with the order
*/
function getOutcome(bytes32 _orderId) public view returns (uint256) {
return orders[_orderId].outcome;
}
/**
* @param _orderId The id of the order
* @return The KYC token associated with the order
*/
function getKYCToken(bytes32 _orderId) public view returns (IERC20) {
return orders[_orderId].kycToken;
}
/**
* @param _orderId The id of the order
* @return The remaining amount of the order
*/
function getAmount(bytes32 _orderId) public view returns (uint256) {
return orders[_orderId].amount;
}
/**
* @param _orderId The id of the order
* @return The price of the order
*/
function getPrice(bytes32 _orderId) public view returns (uint256) {
return orders[_orderId].price;
}
/**
* @param _orderId The id of the order
* @return The creator of the order
*/
function getOrderCreator(bytes32 _orderId) public view returns (address) {
return orders[_orderId].creator;
}
/**
* @param _orderId The id of the order
* @return The remaining shares escrowed in the order
*/
function getOrderSharesEscrowed(bytes32 _orderId) public view returns (uint256) {
return orders[_orderId].sharesEscrowed;
}
/**
* @param _orderId The id of the order
* @return The remaining Cash tokens escrowed in the order
*/
function getOrderMoneyEscrowed(bytes32 _orderId) public view returns (uint256) {
return orders[_orderId].moneyEscrowed;
}
function getOrderDataForCancel(bytes32 _orderId) public view returns (uint256 _moneyEscrowed, uint256 _sharesEscrowed, Order.Types _type, IMarket _market, uint256 _outcome, address _creator) {
Order.Data storage _order = orders[_orderId];
_moneyEscrowed = _order.moneyEscrowed;
_sharesEscrowed = _order.sharesEscrowed;
_type = _order.orderType;
_market = _order.market;
_outcome = _order.outcome;
_creator = _order.creator;
}
function getOrderDataForLogs(bytes32 _orderId) public view returns (Order.Types _type, address[] memory _addressData, uint256[] memory _uint256Data) {
Order.Data storage _order = orders[_orderId];
_addressData = new address[](3);
_uint256Data = new uint256[](10);
_addressData[0] = address(_order.kycToken);
_addressData[1] = _order.creator;
_uint256Data[0] = _order.price;
_uint256Data[1] = _order.amount;
_uint256Data[2] = _order.outcome;
_uint256Data[8] = _order.sharesEscrowed;
_uint256Data[9] = _order.moneyEscrowed;
return (_order.orderType, _addressData, _uint256Data);
}
/**
* @param _market The address of the market
* @return The amount of Cash escrowed for all orders for the specified market
*/
function getTotalEscrowed(IMarket _market) public view returns (uint256) {
return marketOrderData[address(_market)].totalEscrowed;
}
/**
* @param _market The address of the market
* @param _outcome The outcome number
* @return The price for the last completed trade for the specified market and outcome
*/
function getLastOutcomePrice(IMarket _market, uint256 _outcome) public view returns (uint256) {
return marketOrderData[address(_market)].prices[_outcome];
}
/**
* @param _orderId The id of the order
* @return The id (if there is one) of the next order better than the provided one
*/
function getBetterOrderId(bytes32 _orderId) public view returns (bytes32) {
return orders[_orderId].betterOrderId;
}
/**
* @param _orderId The id of the order
* @return The id (if there is one) of the next order worse than the provided one
*/
function getWorseOrderId(bytes32 _orderId) public view returns (bytes32) {
return orders[_orderId].worseOrderId;
}
/**
* @param _type The type of order. Either BID==0, or ASK==1
* @param _market The market of the order
* @param _outcome The outcome of the order
* @param _kycToken The KYC token of the order
* @return The id (if there is one) of the best order that satisfies the given parameters
*/
function getBestOrderId(Order.Types _type, IMarket _market, uint256 _outcome, IERC20 _kycToken) public view returns (bytes32) {
return bestOrder[getBestOrderWorstOrderHash(_market, _outcome, _type, _kycToken)];
}
/**
* @param _type The type of order. Either BID==0, or ASK==1
* @param _market The market of the order
* @param _outcome The outcome of the order
* @param _kycToken The KYC token of the order
* @return The id (if there is one) of the worst order that satisfies the given parameters
*/
function getWorstOrderId(Order.Types _type, IMarket _market, uint256 _outcome, IERC20 _kycToken) public view returns (bytes32) {
return worstOrder[getBestOrderWorstOrderHash(_market, _outcome, _type, _kycToken)];
}
/**
* @param _type The type of order. Either BID==0, or ASK==1
* @param _market The market of the order
* @param _amount The amount of the order
* @param _price The price of the order
* @param _sender The creator of the order
* @param _blockNumber The blockNumber which the order was created in
* @param _outcome The outcome of the order
* @param _moneyEscrowed The amount of Cash tokens escrowed in the order
* @param _sharesEscrowed The outcome Share tokens escrowed in the order
* @param _kycToken The KYC token of the order
* @return The order id that satisfies the given parameters
*/
function getOrderId(Order.Types _type, IMarket _market, uint256 _amount, uint256 _price, address _sender, uint256 _blockNumber, uint256 _outcome, uint256 _moneyEscrowed, uint256 _sharesEscrowed, IERC20 _kycToken) public pure returns (bytes32) {
return Order.calculateOrderId(_type, _market, _amount, _price, _sender, _blockNumber, _outcome, _moneyEscrowed, _sharesEscrowed, _kycToken);
}
function isBetterPrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool) {
if (_type == Order.Types.Bid) {
return (_price > orders[_orderId].price);
} else if (_type == Order.Types.Ask) {
return (_price < orders[_orderId].price);
}
}
function isWorsePrice(Order.Types _type, uint256 _price, bytes32 _orderId) public view returns (bool) {
if (_type == Order.Types.Bid) {
return (_price <= orders[_orderId].price);
} else {
return (_price >= orders[_orderId].price);
}
}
function assertIsNotBetterPrice(Order.Types _type, uint256 _price, bytes32 _betterOrderId) public view returns (bool) {
require(!isBetterPrice(_type, _price, _betterOrderId), "Orders.assertIsNotBetterPrice: Is better price");
return true;
}
function assertIsNotWorsePrice(Order.Types _type, uint256 _price, bytes32 _worseOrderId) public returns (bool) {
require(!isWorsePrice(_type, _price, _worseOrderId), "Orders.assertIsNotWorsePrice: Is worse price");
return true;
}
function insertOrderIntoList(Order.Data storage _order, bytes32 _betterOrderId, bytes32 _worseOrderId) private returns (bool) {
bytes32 _bestOrderWorstOrderHash = getBestOrderWorstOrderHash(_order.market, _order.outcome, _order.orderType, _order.kycToken);
bytes32 _bestOrderId = bestOrder[_bestOrderWorstOrderHash];
bytes32 _worstOrderId = worstOrder[_bestOrderWorstOrderHash];
(_betterOrderId, _worseOrderId) = findBoundingOrders(_order.orderType, _order.price, _bestOrderId, _worstOrderId, _betterOrderId, _worseOrderId);
if (_order.orderType == Order.Types.Bid) {
_bestOrderId = updateBestBidOrder(_order.id, _order.price, _order.outcome, _order.kycToken, _bestOrderWorstOrderHash, _bestOrderId);
_worstOrderId = updateWorstBidOrder(_order.id, _order.price, _order.outcome, _order.kycToken, _bestOrderWorstOrderHash, _worstOrderId);
} else {
_bestOrderId = updateBestAskOrder(_order.id, _order.price, _order.outcome, _order.kycToken, _bestOrderWorstOrderHash, _bestOrderId);
_worstOrderId = updateWorstAskOrder(_order.id, _order.price, _order.outcome, _order.kycToken, _bestOrderWorstOrderHash, _worstOrderId);
}
if (_bestOrderId == _order.id) {
_betterOrderId = bytes32(0);
}
if (_worstOrderId == _order.id) {
_worseOrderId = bytes32(0);
}
if (_betterOrderId != bytes32(0)) {
orders[_betterOrderId].worseOrderId = _order.id;
_order.betterOrderId = _betterOrderId;
}
if (_worseOrderId != bytes32(0)) {
orders[_worseOrderId].betterOrderId = _order.id;
_order.worseOrderId = _worseOrderId;
}
return true;
}
// _amount = _uints[0]
// _price = _uints[1]
// _outcome = _uints[2]
// _moneyEscrowed = _uints[3]
// _sharesEscrowed = _uints[4]
// _betterOrderId = _bytes32s[0]
// _worseOrderId = _bytes32s[1]
// _tradeGroupId = _bytes32s[2]
// _orderId = _bytes32s[3]
function saveOrder(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender, IERC20 _kycToken) external returns (bytes32 _orderId) {
require(msg.sender == createOrder || msg.sender == address(this));
require(_uints[2] < _market.getNumberOfOutcomes(), "Orders.saveOrder: Outcome not in market range");
_orderId = _bytes32s[3];
Order.Data storage _order = orders[_orderId];
_order.market = _market;
_order.id = _orderId;
_order.orderType = _type;
_order.outcome = _uints[2];
_order.price = _uints[1];
_order.amount = _uints[0];
_order.creator = _sender;
_order.kycToken = _kycToken;
_order.moneyEscrowed = _uints[3];
marketOrderData[address(_market)].totalEscrowed += _uints[3];
_order.sharesEscrowed = _uints[4];
insertOrderIntoList(_order, _bytes32s[0], _bytes32s[1]);
augurTrading.logOrderCreated(_order.market.getUniverse(), _orderId, _bytes32s[2]);
return _orderId;
}
function removeOrder(bytes32 _orderId) external returns (bool) {
require(msg.sender == cancelOrder || msg.sender == address(this));
removeOrderFromList(_orderId);
Order.Data storage _order = orders[_orderId];
marketOrderData[address(_order.market)].totalEscrowed -= _order.moneyEscrowed;
delete orders[_orderId];
return true;
}
function recordFillOrder(bytes32 _orderId, uint256 _sharesFilled, uint256 _tokensFilled, uint256 _fill) external returns (bool) {
require(msg.sender == fillOrder || msg.sender == address(this));
Order.Data storage _order = orders[_orderId];
require(_order.outcome < _order.market.getNumberOfOutcomes(), "Orders.recordFillOrder: Outcome is not in market range");
require(_orderId != bytes32(0), "Orders.recordFillOrder: orderId is 0x0");
require(_sharesFilled <= _order.sharesEscrowed, "Orders.recordFillOrder: shares filled higher than order amount");
require(_tokensFilled <= _order.moneyEscrowed, "Orders.recordFillOrder: tokens filled higher than order amount");
require(_order.price <= _order.market.getNumTicks(), "Orders.recordFillOrder: Price outside of market range");
require(_fill <= _order.amount, "Orders.recordFillOrder: Fill higher than order amount");
_order.amount -= _fill;
_order.moneyEscrowed -= _tokensFilled;
marketOrderData[address(_order.market)].totalEscrowed -= _tokensFilled;
_order.sharesEscrowed -= _sharesFilled;
if (_order.amount == 0) {
require(_order.moneyEscrowed == 0, "Orders.recordFillOrder: Money left in filled order");
require(_order.sharesEscrowed == 0, "Orders.recordFillOrder: Shares left in filled order");
removeOrderFromList(_orderId);
_order.price = 0;
_order.creator = address(0);
_order.betterOrderId = bytes32(0);
_order.worseOrderId = bytes32(0);
}
return true;
}
function setPrice(IMarket _market, uint256 _outcome, uint256 _price) external returns (bool) {
require(msg.sender == trade);
marketOrderData[address(_market)].prices[_outcome] = _price;
return true;
}
function removeOrderFromList(bytes32 _orderId) private returns (bool) {
Order.Data storage _order = orders[_orderId];
bytes32 _betterOrderId = _order.betterOrderId;
bytes32 _worseOrderId = _order.worseOrderId;
bytes32 _bestOrderWorstOrderHash = getBestOrderWorstOrderHash(_order.market, _order.outcome, _order.orderType, _order.kycToken);
if (bestOrder[_bestOrderWorstOrderHash] == _orderId) {
bestOrder[_bestOrderWorstOrderHash] = _worseOrderId;
}
if (worstOrder[_bestOrderWorstOrderHash] == _orderId) {
worstOrder[_bestOrderWorstOrderHash] = _betterOrderId;
}
if (_betterOrderId != bytes32(0)) {
orders[_betterOrderId].worseOrderId = _worseOrderId;
}
if (_worseOrderId != bytes32(0)) {
orders[_worseOrderId].betterOrderId = _betterOrderId;
}
_order.betterOrderId = bytes32(0);
_order.worseOrderId = bytes32(0);
return true;
}
/**
* @dev If best bid is not set or price higher than best bid price, this order is the new best bid.
*/
function updateBestBidOrder(bytes32 _orderId, uint256 _price, uint256 _outcome, IERC20 _kycToken, bytes32 _bestOrderWorstOrderHash, bytes32 _bestBidOrderId) private returns (bytes32) {
if (_bestBidOrderId == bytes32(0) || _price > orders[_bestBidOrderId].price) {
bestOrder[_bestOrderWorstOrderHash] = _orderId;
return _orderId;
} else {
return _bestBidOrderId;
}
}
/**
* @dev If worst bid is not set or price lower than worst bid price, this order is the new worst bid.
*/
function updateWorstBidOrder(bytes32 _orderId, uint256 _price, uint256 _outcome, IERC20 _kycToken, bytes32 _bestOrderWorstOrderHash, bytes32 _worstBidOrderId) private returns (bytes32) {
if (_worstBidOrderId == bytes32(0) || _price <= orders[_worstBidOrderId].price) {
worstOrder[_bestOrderWorstOrderHash] = _orderId;
return _orderId;
} else {
return _worstBidOrderId;
}
}
/**
* @dev If best ask is not set or price lower than best ask price, this order is the new best ask.
*/
function updateBestAskOrder(bytes32 _orderId, uint256 _price, uint256 _outcome, IERC20 _kycToken, bytes32 _bestOrderWorstOrderHash, bytes32 _bestAskOrderId) private returns (bytes32) {
if (_bestAskOrderId == bytes32(0) || _price < orders[_bestAskOrderId].price) {
bestOrder[_bestOrderWorstOrderHash] = _orderId;
return _orderId;
} else {
return _bestAskOrderId;
}
}
/**
* @dev If worst ask is not set or price higher than worst ask price, this order is the new worst ask.
*/
function updateWorstAskOrder(bytes32 _orderId, uint256 _price, uint256 _outcome, IERC20 _kycToken, bytes32 _bestOrderWorstOrderHash, bytes32 _worstAskOrderId) private returns (bytes32) {
if (_worstAskOrderId == bytes32(0) || _price >= orders[_worstAskOrderId].price) {
worstOrder[_bestOrderWorstOrderHash] = _orderId;
return _orderId;
} else {
return _worstAskOrderId;
}
}
function getBestOrderWorstOrderHash(IMarket _market, uint256 _outcome, Order.Types _type, IERC20 _kycToken) private pure returns (bytes32) {
return sha256(abi.encodePacked(_market, _outcome, _type, _kycToken));
}
function ascendOrderList(Order.Types _type, uint256 _price, bytes32 _lowestOrderId) public view returns (bytes32 _betterOrderId, bytes32 _worseOrderId) {
_worseOrderId = _lowestOrderId;
bool _isWorstPrice;
if (_type == Order.Types.Bid) {
_isWorstPrice = _price <= getPrice(_worseOrderId);
} else if (_type == Order.Types.Ask) {
_isWorstPrice = _price >= getPrice(_worseOrderId);
}
if (_isWorstPrice) {
return (_worseOrderId, getWorseOrderId(_worseOrderId));
}
bool _isBetterPrice = isBetterPrice(_type, _price, _worseOrderId);
while (_isBetterPrice && getBetterOrderId(_worseOrderId) != 0 && _price != getPrice(getBetterOrderId(_worseOrderId))) {
_betterOrderId = getBetterOrderId(_worseOrderId);
_isBetterPrice = isBetterPrice(_type, _price, _betterOrderId);
if (_isBetterPrice) {
_worseOrderId = getBetterOrderId(_worseOrderId);
}
}
_betterOrderId = getBetterOrderId(_worseOrderId);
return (_betterOrderId, _worseOrderId);
}
function descendOrderList(Order.Types _type, uint256 _price, bytes32 _highestOrderId) public view returns (bytes32 _betterOrderId, bytes32 _worseOrderId) {
_betterOrderId = _highestOrderId;
bool _isBestPrice;
if (_type == Order.Types.Bid) {
_isBestPrice = _price > getPrice(_betterOrderId);
} else if (_type == Order.Types.Ask) {
_isBestPrice = _price < getPrice(_betterOrderId);
}
if (_isBestPrice) {
return (0, _betterOrderId);
}
bool _isWorsePrice = isWorsePrice(_type, _price, _betterOrderId);
while (_isWorsePrice && getWorseOrderId(_betterOrderId) != 0) {
_worseOrderId = getWorseOrderId(_betterOrderId);
_isWorsePrice = isWorsePrice(_type, _price, _worseOrderId);
if (_isWorsePrice || _price == getPrice(getWorseOrderId(_betterOrderId))) {
_betterOrderId = getWorseOrderId(_betterOrderId);
}
}
_worseOrderId = getWorseOrderId(_betterOrderId);
return (_betterOrderId, _worseOrderId);
}
function findBoundingOrders(Order.Types _type, uint256 _price, bytes32 _bestOrderId, bytes32 _worstOrderId, bytes32 _betterOrderId, bytes32 _worseOrderId) public returns (bytes32 betterOrderId, bytes32 worseOrderId) {
if (_bestOrderId == _worstOrderId) {
if (_bestOrderId == bytes32(0)) {
return (bytes32(0), bytes32(0));
} else if (isBetterPrice(_type, _price, _bestOrderId)) {
return (bytes32(0), _bestOrderId);
} else {
return (_bestOrderId, bytes32(0));
}
}
if (_betterOrderId != bytes32(0)) {
if (getPrice(_betterOrderId) == 0) {
_betterOrderId = bytes32(0);
} else {
assertIsNotBetterPrice(_type, _price, _betterOrderId);
}
}
if (_worseOrderId != bytes32(0)) {
if (getPrice(_worseOrderId) == 0) {
_worseOrderId = bytes32(0);
} else {
assertIsNotWorsePrice(_type, _price, _worseOrderId);
}
}
if (_betterOrderId == bytes32(0) && _worseOrderId == bytes32(0)) {
return (descendOrderList(_type, _price, _bestOrderId));
} else if (_betterOrderId == bytes32(0)) {
return (ascendOrderList(_type, _price, _worseOrderId));
} else if (_worseOrderId == bytes32(0)) {
return (descendOrderList(_type, _price, _betterOrderId));
}
if (getWorseOrderId(_betterOrderId) != _worseOrderId) {
return (descendOrderList(_type, _price, _betterOrderId));
} else if (getBetterOrderId(_worseOrderId) != _betterOrderId) {
// Coverage: This condition is likely unreachable or at least seems to be. Rather than remove it I'm keeping it for now just to be paranoid
return (ascendOrderList(_type, _price, _worseOrderId));
}
return (_betterOrderId, _worseOrderId);
}
}
|
_amount = _uints[0] _price = _uints[1] _outcome = _uints[2] _moneyEscrowed = _uints[3] _sharesEscrowed = _uints[4] _betterOrderId = _bytes32s[0] _worseOrderId = _bytes32s[1] _tradeGroupId = _bytes32s[2] _orderId = _bytes32s[3]
|
function saveOrder(uint256[] calldata _uints, bytes32[] calldata _bytes32s, Order.Types _type, IMarket _market, address _sender, IERC20 _kycToken) external returns (bytes32 _orderId) {
require(msg.sender == createOrder || msg.sender == address(this));
require(_uints[2] < _market.getNumberOfOutcomes(), "Orders.saveOrder: Outcome not in market range");
_orderId = _bytes32s[3];
Order.Data storage _order = orders[_orderId];
_order.market = _market;
_order.id = _orderId;
_order.orderType = _type;
_order.outcome = _uints[2];
_order.price = _uints[1];
_order.amount = _uints[0];
_order.creator = _sender;
_order.kycToken = _kycToken;
_order.moneyEscrowed = _uints[3];
marketOrderData[address(_market)].totalEscrowed += _uints[3];
_order.sharesEscrowed = _uints[4];
insertOrderIntoList(_order, _bytes32s[0], _bytes32s[1]);
augurTrading.logOrderCreated(_order.market.getUniverse(), _orderId, _bytes32s[2]);
return _orderId;
}
| 1,012,403
|
pragma solidity 0.4.22;
import "./zeppelin-solidity/contracts/math/SafeMath.sol";
import "./OttolottoDaoRules.sol";
/**
* @title Ottolotto Distributed Autonomus Organization.
*
* The ottolotto platform is curated by Decentralized Autonomous Organization,
* this means nobody has direct access to funds or Jackpot and all processes
* are set by token owners. All platform commissions are sent to DAO and system
* is curating transactions due to the rules. Each token holder’s wallet receives
* dividends from platform commission once in 90 days. All token holders,
* who own 3% or more are able to set new rules for the platform.
**/
contract OttolottoDao is OttolottoDaoRules {
using SafeMath for uint256;
/**
* @dev Guaranteed percent.
*/
uint8 constant GUARANTED_INTEREST = 30;
/**
* @dev The minimal amount of wei for distribution.
*/
uint256 constant MINIMAL_WEI = 50000000000000000;
/**
* @dev Variable store last interest time.
*/
uint256 public lastInterestTime;
/**
* @dev Variable store interest period.
*/
uint256 public interestPeriod = 7776000;
/**
* @dev Total interest amount.
*/
uint256 public totalInterest;
/**
* @dev Total interest amount after withdraws.
*/
uint256 public totalInterestWithWithdraws;
/**
* @dev Available DAO Funds.
*/
uint256 public availableDAOfunds;
/**
* @dev Not distributed wei by rules.
*/
uint256 public notDistributedWei;
// Events
/**
* @dev Write to log info about new interest period.
*
* @param totalInterest Amount of ether that will be distributed between token holder.
* @param time A time when period started.
*/
event DivideUpInterest(uint256 totalInterest, uint256 time);
/**
* @dev Write to log info about interest withdraw.
*
* @param tokenHolder Address of token holder.
* @param amount Interest amount (in wei).
* @param time The time when token holder withdraws his interest.
*/
event WithdrawInterest(address indexed tokenHolder, uint256 amount, uint256 time);
/**
* @dev Write info to log about ether distribution between rules.
*
* @param amount Amount of ether in wei.
* @param time The time when it happens.
*/
event DistributionBetweenRules(uint256 amount, uint256 time);
/**
* @dev Write to log info about withdraw from rule balance.
*
* @param index Proposal index.
* @param amount Amount of ether in wei.
* @param initiator Address of withdrawing initiator.
* @param time Time.
*/
event WithdrawFromRule(
uint256 indexed index,
uint256 amount,
address indexed initiator,
uint256 time
);
/**
* @dev Write to log info about rule balance replenishment.
*
* @param index Proposal index.
* @param amount Amount of ether in wei.
* @param time Time.
*/
event RuleBalanceReplenishment(uint256 indexed index, uint256 amount, uint256 time);
/**
* @dev Initialize default rule.
*/
constructor() public {
lastInterestTime = 1512604800;
}
/**
* @dev Transfer coins and fix balance update time.
*
* @param receiver The address to transfer to.
* @param amount The amount to be transferred.
*/
function transfer(address receiver, uint256 amount) public returns (bool) {
beforeBalanceChanges(msg.sender);
beforeBalanceChanges(receiver);
holders[receiver].balanceUpdateTimeForVoting = now;
return super.transfer(receiver, amount);
}
/**
* @dev Transfer coins and fix balance update time.
*
* @param from Address from which will be withdrawn tokens.
* @param to The address to transfer to.
* @param value The amount to be transferred.
*/
function transferFrom(address from, address to, uint256 value)
public
returns (bool)
{
beforeBalanceChanges(from);
beforeBalanceChanges(to);
holders[to].balanceUpdateTimeForVoting = now;
return super.transferFrom(from, to, value);
}
/**
* @dev Provides functionality for voting.
*
* @param proposal Proposal on which token holder send votes.
* @param votes Amount of votes.
* @param pCategory Proposal category.
*/
function vote(uint256 proposal, uint256 votes, bytes1 pCategory) public {
super.vote(proposal, votes, pCategory);
if (pCategory == PC_DELETE && deleteProposals[proposal].status == P_ACCEPTED) {
// Move ether from rule to dao funds.
uint256 index = deleteProposals[proposal].proposalId;
if (proposals[index].status == P_DELETED && proposals[index].balance > 0) {
availableDAOfunds += proposals[index].balance;
proposals[index].balance = 0;
}
}
}
/**
* @dev Fixes the time of balance change.
* And copied its value if it happens after interest period.
*
* @param tokenHolder Address of the token holder.
*/
function beforeBalanceChanges(address tokenHolder) internal {
if (holders[tokenHolder].balanceUpdateTimeForInterest <= lastInterestTime) {
holders[tokenHolder].balanceUpdateTimeForInterest = now;
holders[tokenHolder].balance = balanceOf(tokenHolder);
}
}
/**
* @dev Calculate token holder interest amount.
*/
function getHolderInterestAmount() public view returns (uint256) {
if (holders[msg.sender].interestWithdrawTime >= lastInterestTime) {
return 0;
}
uint256 balance;
if (holders[msg.sender].balanceUpdateTimeForInterest <= lastInterestTime) {
balance = balanceOf(msg.sender);
} else {
balance = holders[msg.sender].balance;
}
return totalInterest * balance / INITIAL_SUPPLY;
}
/**
* @dev Allow token holder to get his interest.
*/
function withdrawInterest() public {
uint value = getHolderInterestAmount();
require(value != 0);
// Transfer ether to the token holder.
msg.sender.transfer(value);
if (balanceOf(msg.sender) == 0) {
delete holders[msg.sender];
} else {
holders[msg.sender].interestWithdrawTime = now;
}
totalInterestWithWithdraws -= value;
// Write info to log about withdraw.
emit WithdrawInterest(msg.sender, value, now);
}
/**
* @dev Allow divide up interest and make it accessible for withdrawing.
*/
function divideUpIterest() public {
require(lastInterestTime + interestPeriod <= now);
lastInterestTime = now;
// All available funds moved to interests.
totalInterest = availableDAOfunds;
totalInterest += totalInterestWithWithdraws;
totalInterestWithWithdraws = totalInterest;
availableDAOfunds = 0;
// Write info to log about interest period starts.
emit DivideUpInterest(totalInterest, now);
}
/**
* @dev Get last token holder interest withdraw time.
*
* @return the last interest withdraws time.
*/
function getHolderInterestWithdrawTime() public view returns (uint256) {
return holders[msg.sender].interestWithdrawTime;
}
/*
* @dev Accept funds.
*/
function acceptFunds() public payable {
notDistributedWei += msg.value;
}
/**
* @dev Distribute not distributed ether between rules.
*/
function distributeBetweenRules() public {
require(notDistributedWei >= MINIMAL_WEI);
// Calculate guarantee interest for token holders.
// Other ether will be distributed between rules first,
// what will remain for interest.
uint256 guaranted = notDistributedWei.mul(GUARANTED_INTEREST).div(100);
notDistributedWei -= guaranted;
uint256 toDistribute = notDistributedWei;
for (uint256 i = 0; i < rules.length; i++) {
if (i != 0 && rules[i] == 0) {
continue;
}
uint256 toRule = distributeFundToRule(i);
toDistribute -= toRule;
}
// Write info to log about ether distribution.
emit DistributionBetweenRules(notDistributedWei, now);
notDistributedWei = 0;
availableDAOfunds += toDistribute + guaranted;
}
/**
* @dev Distribute funds to rules.
*
* @param i Index of the rule.
*/
function distributeFundToRule(uint256 i) internal returns (uint256) {
uint256 toRule = notDistributedWei.mul(proposals[rules[i]].percent).div(100);
// check rule
uint256 nextBalance = proposals[rules[i]].balance + toRule;
if (proposals[rules[i]].proposalType == P_TYPE_PERCENTS || proposals[rules[i]].value > nextBalance) {
proposals[rules[i]].balance += toRule;
emit RuleBalanceReplenishment(rules[i], toRule, now);
return toRule;
}
proposals[rules[i]].balance = proposals[rules[i]].value;
toRule -= nextBalance - proposals[rules[i]].value;
if (toRule != 0) {
emit RuleBalanceReplenishment(rules[i], toRule, now);
}
return toRule;
}
/**
* @dev Withdraw available ether from proposal balance to executor.
*
* @param index Proposal index.
*/
function withdrawFromProposal(uint256 index) public returns (bool) {
require(proposals[index].balance > 0);
// Execute logic that depends on proposal type.
if (proposals[index].proposalType == P_TYPE_PERCENTS) {
withdrawFromProposalBalance(index);
return true;
}
require(proposals[index].balance == proposals[index].value);
withdrawFromProposalBalance(index);
super.removeProposalFromRules(index, 0);
return true;
}
/**
* @dev Withdraw from proposal balance.
*
* @param index Proposal index.
*/
function withdrawFromProposalBalance(uint256 index) internal {
proposals[index].executor.transfer(proposals[index].balance);
// Write to log info about withdraw.
emit WithdrawFromRule(
index,
proposals[index].balance,
msg.sender,
now
);
proposals[index].balance = 0;
}
}
|
Accept funds./
|
function acceptFunds() public payable {
notDistributedWei += msg.value;
}
| 968,042
|
./full_match/1/0x3f4DD25BA6Fb6441Bfd1a869Cbda6a511966456D/sources/src/HoneyJar.sol
|
burn the honeyjar tokens. Nothing will have the burn role upon initialization This will be used for future game-mechanics only callable by the BURNER role
|
function burn(uint256 _id) external override onlyRole(Constants.BURNER) {
_burn(_id);
}
| 3,093,384
|
//
// Made by: Omicron Blockchain Solutions
// https://omicronblockchain.com
//
// SPDX-License-Identifier: MIT
pragma solidity =0.8.10;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
import "@openzeppelin/contracts/interfaces/IERC721.sol";
import "../interfaces/IMintableERC721.sol";
/**
* @title Reedemable ERC721 Giveaway
* @author Omicron Blockchain Solutions
*
* @notice Reedemable ERC721 Giveaway is a smart contract that allow accounts that own a specific ERC721 token
* to get another ERC721 token for free, in a fixed period of time; the smart contract
* is generic and can support any type of mintable NFT (see MintableERC721 interface).
* For instance, suppose that users already own NFTs named A. Then, for each minted NFT A, the owner
* can also mint another NFT called B. The releationship is one-to-one and it can be only one NFT of type B
* minted for a distinct NFT of type A.
*
* @dev All the "fixed" parameters can be changed on the go after smart contract is deployed
* and operational, but this ability is reserved for quick fix-like adjustments, and to provide
* an ability to restart and run a giveaway after the previous one ends.
*
* Note that both the `giveawayTokenContract` and `baseTokenContract` contracts must be mintble NFTS
* for this to work.
*
* When redeem an NFT token by this contract, the token is minted by the recipient.
*
* To successfully redeem a token, the caller must:
* 1) Own NFTs minted using the `baseTokenContract`
* 2) The NFTs minted using the `baseTokenContract` should already not been used to redeem NFTs
* of the `giveawayTokenContract`.
*
* Deployment and setup:
* 1. Deploy smart contract, specify the giveawat smart contract address during the deployment:
* - Mintable ER721 deployed instance address
* 2. Execute `initialize` function and set up the giveaway parameters;
* giveaway is not active until it's initialized and a valid `baseTokenContract` address is provided.
*/
contract RedeemableGiveaway is Ownable {
/**
* @dev Next token ID to mint;
* initially this is the first available ID which can be minted;
* at any point in time this should point to a available, mintable ID
* for the token.
*
* `nextId` cannot be zero, we do not ever mint NFTs with zero IDs.
*/
uint256 public nextId = 1;
/**
* @dev Last token ID to mint;
* once `nextId` exceeds `finalId` the giveaway pauses.
*/
uint256 public finalId;
// ----- SLOT.1 (96/256)
/**
* @notice Giveaway start at unix timestamp; the giveaway is active after the start (inclusive)
*/
uint32 public giveawayStart;
/**
* @notice Giveaway end unix timestamp; the giveaway is active before the end (exclusive)
*/
uint32 public giveawayEnd;
/**
* @notice Counter of the tokens gifted (minted) by this sale smart contract.
*/
uint32 public giveawayCounter;
/**
* @notice The contract address of the giveaway token.
*/
address public immutable giveawayTokenContract;
/**
* @notice The contract address of the base token.
*/
address public baseTokenContract;
/**
* @notice Track redeemed base tokens.
* @dev This is usefull to prevent same tokens to be used again after redeem.
*/
mapping(uint256 => bool) redeemedBaseTokens;
/**
* @dev Fired in initialize()
*
* @param _by an address which executed the initialization
* @param _nextId next ID of the giveaway token to mint
* @param _finalId final ID of the giveaway token to mint
* @param _giveawayStart start of the giveaway, unix timestamp
* @param _giveawayEnd end of the giveaway, unix timestamp
* @param _baseTokenContract base token contract address used for redeeming
*/
event Initialized(
address indexed _by,
uint256 _nextId,
uint256 _finalId,
uint32 _giveawayStart,
uint32 _giveawayEnd,
address _baseTokenContract
);
/**
* @dev Fired in redeem(), redeemTo(), redeemSingle(), and redeemSingleTo()
*
* @param _by an address which executed the transaction, probably a base NFT owner
* @param _to an address which received token(s) minted
* @param _giveawayTokens array with IDS of the minted tokens
*/
event Redeemed(address indexed _by, address indexed _to, uint256[] _giveawayTokens);
/**
* @dev Creates/deploys RedeemableERC721Giveaway and binds it to Mintable ERC721
* smart contract on construction
*
* @param _giveawayTokenContract deployed Mintable ERC721 smart contract; giveaway will mint ERC721
* tokens of that type to the recipient
*/
constructor(address _giveawayTokenContract) {
// Verify the input is set.
require(_giveawayTokenContract != address(0), "giveaway token contract is not set");
// Verify input is valid smart contract of the expected interfaces.
require(
IERC165(_giveawayTokenContract).supportsInterface(type(IMintableERC721).interfaceId) &&
IERC165(_giveawayTokenContract).supportsInterface(type(IMintableERC721).interfaceId),
"unexpected token contract type"
);
// Assign the addresses.
giveawayTokenContract = _giveawayTokenContract;
}
/**
* @notice Number of tokens left on giveaway.
*
* @dev Doesn't take into account if giveway is active or not,
* if `nextId - finalId < 1` returns zero.
*
* @return Number of tokens left on giveway.
*/
function itemsOnGiveaway() public view returns (uint256) {
// Calculate items left on givewaway, taking into account that
// `finalId` is givewaway (inclusive bound).
return finalId >= nextId ? finalId + 1 - nextId : 0;
}
/**
* @notice Number of tokens available on giveaway.
*
* @dev Takes into account if giveaway is active or not, doesn't throw,
* returns zero if giveaway is inactive
*
* @return Number of tokens available on giveaway.
*/
function itemsAvailable() public view returns (uint256) {
// Delegate to itemsOnSale() if giveaway is active, returns zero otherwise.
return isActive() ? itemsOnGiveaway() : 0;
}
/**
* @notice Active giveaway is an operational giveaway capable of minting tokens.
*
* @dev The giveaway is active when all the requirements below are met:
* 1. `baseTokenContract` is set
* 2. `finalId` is not reached (`nextId <= finalId`)
* 3. current timestamp is between `giveawayStart` (inclusive) and `giveawayEnd` (exclusive)
*
* Function is marked as virtual to be overridden in the helper test smart contract (mock)
* in order to test how it affects the giveaway process
*
* @return true if giveaway is active (operational) and can mint tokens, false otherwise.
*/
function isActive() public view virtual returns (bool) {
// Evaluate giveaway state based on the internal state variables and return.
return
baseTokenContract != address(0) &&
nextId <= finalId &&
giveawayStart <= block.timestamp &&
giveawayEnd > block.timestamp;
}
/**
* @dev Restricted access function to set up giveaway parameters, all at once,
* or any subset of them.
*
* To skip parameter initialization, set it to the biggest number for the corresponding type;
* for `_baseTokenContract`, use address(0) or '0x0000000000000000000000000000000000000000' from Javascript.
*
* Example: The following initialization will update only _giveawayStart and _giveawayEnd,
* leaving the rest of the fields unchanged:
*
* initialize(
* type(uint256).max,
* type(uint256).max,
* 1637080155850,
* 1639880155950,
* address(0)
* )
*
* Requires next ID to be greater than zero (strict): `_nextId > 0`
*
* Requires transaction sender to be the deployer of this contract.
*
* @param _nextId next ID of the token to mint, will be increased
* in smart contract storage after every successful giveaway
* @param _finalId final ID of the token to mint; giveaway is capable of producing
* `_finalId - _nextId + 1` tokens
* @param _giveawayStart start of the giveaway, unix timestamp
* @param _giveawayEnd end of the giveaway, unix timestamp; sale is active only
* when current time is within _giveawayStart (inclusive) and _giveawayEnd (exclusive)
* @param _baseTokenContract end of the sale, unix timestamp; sale is active only
* when current time is within _giveawayStart (inclusive) and _giveawayEnd (exclusive)
*/
function initialize(
uint256 _nextId, // <<<--- keep type in sync with the body type(uint256).max !!!
uint256 _finalId, // <<<--- keep type in sync with the body type(uint256).max !!!
uint32 _giveawayStart, // <<<--- keep type in sync with the body type(uint32).max !!!
uint32 _giveawayEnd, // <<<--- keep type in sync with the body type(uint32).max !!!
address _baseTokenContract // <<<--- keep type in sync with the body address(0) !!!
) public onlyOwner {
// Verify the inputs.
// No need to verify extra parameters - "incorrect" values will deactivate the sale.
require(_nextId > 0, "zero nextId");
// Initialize contract state based on the values supplied.
// Take into account our convention that value `-1` means "do not set"
if (_nextId != type(uint256).max) {
nextId = _nextId;
}
if (_finalId != type(uint256).max) {
finalId = _finalId;
}
if (_giveawayStart != type(uint32).max) {
giveawayStart = _giveawayStart;
}
if (_giveawayEnd != type(uint32).max) {
giveawayEnd = _giveawayEnd;
}
if (_baseTokenContract != address(0)) {
// The base contract must implement the Mintable NFT interface.
require(
IERC165(_baseTokenContract).supportsInterface(type(IMintableERC721).interfaceId) &&
IERC165(_baseTokenContract).supportsInterface(type(IMintableERC721).interfaceId),
"unexpected token contract type"
);
baseTokenContract = _baseTokenContract;
}
// Emit initialize event - read values from the storage since not all of them might be set.
emit Initialized(msg.sender, nextId, finalId, giveawayStart, giveawayEnd, baseTokenContract);
}
/**
* @notice Given an array of base tokens, check if any of the tokens were previously redeemed.
* @param _baseTokens Array with base tokens ID.
* @return true if any base token was previously redeemed, false otherwise.
*/
function areRedeemed(uint256[] calldata _baseTokens) external view returns (bool[] memory) {
bool[] memory redeemed = new bool[](_baseTokens.length);
for (uint256 i = 0; i < _baseTokens.length; i++) {
redeemed[i] = redeemedBaseTokens[_baseTokens[i]];
}
return redeemed;
}
/**
* @notice Redeem several tokens using the caller address. This function will fail if the provided `_baseTokens`
* are not owned by the caller or have previously redeemed.
*
* @param _baseTokens Array with base tokens ID.
*/
function redeem(uint256[] memory _baseTokens) public {
redeemTo(msg.sender, _baseTokens);
}
/**
* @notice Redeem several tokens into the address specified by `_to`. This function will fail
* if the provided `_baseTokens` are not owned by the caller or have previously redeemed.
*
* @param _to Address where the minted tokens will be assigned.
* @param _baseTokens Array with base tokens ID.
*/
function redeemTo(address _to, uint256[] memory _baseTokens) public {
// Verify the recipient's address.
require(_to != address(0), "recipient not set");
// Verify more than 1 tokens were provided, else the caller can use
// the single variants of the redeem functions.
require(_baseTokens.length > 1, "incorrect amount");
// Verify that all the specified base tokens IDs are owned by the transaction caller
// and does not have already been redeemed.
for (uint256 i = 0; i < _baseTokens.length; i++) {
require(IERC721(baseTokenContract).ownerOf(_baseTokens[i]) == msg.sender, "wrong owner");
require(!redeemedBaseTokens[_baseTokens[i]], "token already redeemed");
}
// Verify there is enough items available to giveaway.
// Verifies giveaway is in active state under the hood.
require(itemsAvailable() >= _baseTokens.length, "inactive giveaway or not enough items available");
// Store the minted giveaway tokens.
uint256[] memory giveawayTokens = new uint256[](_baseTokens.length);
// For each base token provided, mint a giveaway token.
for (uint256 i = 0; i < _baseTokens.length; i++) {
// Mint token to to the recipient.
IMintableERC721(giveawayTokenContract).mint(_to, nextId);
// Save the minted token ID.
giveawayTokens[i] = nextId;
// Set the next token ID to mint.
nextId += 1;
// Increase the giveaway counter.
giveawayCounter += 1;
// Record the base token, so that it cannot be used again for redeeming.
redeemedBaseTokens[_baseTokens[i]] = true;
}
// All the tokens were redeemed, emit the corresponding event.
emit Redeemed(msg.sender, _to, giveawayTokens);
}
/**
* @notice Redeem a single token using the caller address. This function will fail if the provided `_baseToken`
* is not owned by the caller or have previously redeemed.
*
* @param _baseToken Base token ID to redeem.
*/
function redeemSingle(uint256 _baseToken) public {
redeemSingleTo(msg.sender, _baseToken);
}
/**
* @notice Redeem a single token into the address specified by `_to`. This function will fail
* if the provided `_baseToken` is not owned by the caller or have previously redeemed.
*
* @param _to Address where the minted token will be assigned.
* @param _baseToken Base token ID to redeem.
*/
function redeemSingleTo(address _to, uint256 _baseToken) public {
// Verify the recipient's address.
require(_to != address(0), "recipient not set");
// Verify that the specified base tokens ID is owned by the transaction caller
// and does not have already been redeemed.
require(IERC721(baseTokenContract).ownerOf(_baseToken) == msg.sender, "wrong owner");
require(!redeemedBaseTokens[_baseToken], "token already redeemed");
// Verify there is enough items available to giveaway.
// Verifies giveaway is in active state under the hood.
require(itemsAvailable() >= 1, "inactive giveaway or not enough items available");
// Store the minted giveaway token.
uint256[] memory giveawayTokens = new uint256[](1);
// Mint token to to the recipient.
IMintableERC721(giveawayTokenContract).mint(_to, nextId);
// Save the minted token ID.
giveawayTokens[0] = nextId;
// Set the next token ID to mint.
nextId += 1;
// Increase the giveaway counter.
giveawayCounter += 1;
// Record the base token, so that it cannot be used again for redeeming.
redeemedBaseTokens[_baseToken] = true;
// All the tokens were redeemed, emit the corresponding event.
emit Redeemed(msg.sender, _to, giveawayTokens);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/introspection/IERC165.sol";
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../token/ERC721/IERC721.sol";
// SPDX-License-Identifier: MIT
pragma solidity 0.8.10;
interface IMintableERC721 {
/**
* @notice Checks if specified token exists
*
* @dev Returns whether the specified token ID has an ownership
* information associated with it
*
* @param _tokenId ID of the token to query existence for
* @return whether the token exists (true - exists, false - doesn't exist)
*/
function exists(uint256 _tokenId) external view returns(bool);
/**
* @dev Creates new token with token ID specified
* and assigns an ownership `_to` for this token
*
* @dev Unsafe: doesn't execute `onERC721Received` on the receiver.
* Prefer the use of `saveMint` instead of `mint`.
*
* @dev Should have a restricted access handled by the implementation
*
* @param _to an address to mint token to
* @param _tokenId ID of the token to mint
*/
function mint(address _to, uint256 _tokenId) external;
/**
* @dev Creates new tokens starting with token ID specified
* and assigns an ownership `_to` for these tokens
*
* @dev Token IDs to be minted: [_tokenId, _tokenId + n)
*
* @dev n must be greater or equal 2: `n > 1`
*
* @dev Unsafe: doesn't execute `onERC721Received` on the receiver.
* Prefer the use of `saveMintBatch` instead of `mintBatch`.
*
* @dev Should have a restricted access handled by the implementation
*
* @param _to an address to mint tokens to
* @param _tokenId ID of the first token to mint
* @param n how many tokens to mint, sequentially increasing the _tokenId
*/
function mintBatch(address _to, uint256 _tokenId, uint256 n) external;
/**
* @dev Creates new token with token ID specified
* and assigns an ownership `_to` for this token
*
* @dev 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)"))`.
*
* @dev Should have a restricted access handled by the implementation
*
* @param _to an address to mint token to
* @param _tokenId ID of the token to mint
*/
function safeMint(address _to, uint256 _tokenId) external;
/**
* @dev Creates new token with token ID specified
* and assigns an ownership `_to` for this token
*
* @dev 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)"))`.
*
* @dev Should have a restricted access handled by the implementation
*
* @param _to an address to mint token to
* @param _tokenId ID of the token to mint
* @param _data additional data with no specified format, sent in call to `_to`
*/
function safeMint(address _to, uint256 _tokenId, bytes memory _data) external;
/**
* @dev Creates new tokens starting with token ID specified
* and assigns an ownership `_to` for these tokens
*
* @dev Token IDs to be minted: [_tokenId, _tokenId + n)
*
* @dev n must be greater or equal 2: `n > 1`
*
* @dev 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)"))`.
*
* @dev Should have a restricted access handled by the implementation
*
* @param _to an address to mint token to
* @param _tokenId ID of the token to mint
* @param n how many tokens to mint, sequentially increasing the _tokenId
*/
function safeMintBatch(address _to, uint256 _tokenId, uint256 n) external;
/**
* @dev Creates new tokens starting with token ID specified
* and assigns an ownership `_to` for these tokens
*
* @dev Token IDs to be minted: [_tokenId, _tokenId + n)
*
* @dev n must be greater or equal 2: `n > 1`
*
* @dev 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)"))`.
*
* @dev Should have a restricted access handled by the implementation
*
* @param _to an address to mint token to
* @param _tokenId ID of the token to mint
* @param n how many tokens to mint, sequentially increasing the _tokenId
* @param _data additional data with no specified format, sent in call to `_to`
*/
function safeMintBatch(address _to, uint256 _tokenId, uint256 n, bytes memory _data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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 "../../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;
}
|
Given an array of base tokens, check if any of the tokens were previously redeemed. _baseTokens Array with base tokens ID. return true if any base token was previously redeemed, false otherwise./
|
function areRedeemed(uint256[] calldata _baseTokens) external view returns (bool[] memory) {
bool[] memory redeemed = new bool[](_baseTokens.length);
for (uint256 i = 0; i < _baseTokens.length; i++) {
redeemed[i] = redeemedBaseTokens[_baseTokens[i]];
}
return redeemed;
}
| 14,093,757
|
pragma solidity ^0.4.24;
pragma experimental ABIEncoderV2;
import "./Table.sol";
//存证合约
contract EvidenceConV1 {
// event
event RegisterEvent(string serviceId,string sn,string rid,string ts,string remarkJsonValue,address account,uint256 timeStamp);
event SetPermitUserEvent(uint256 state,address msgAddress,address userAddress,bool setPermitState,uint256 timeStamp, string remark);
event InsertDbErrorEvent(string serviceId,string sn,string rid,string ts,string remarkJsonValue,address account,uint256 timeStamp);
//设定管理者
address private _manager;
//授权许可用户集合
mapping(address=>bool) public permitUserMapping;
//Modifier 定义一个修饰器,所有继承该修饰器的方法进行管理者验证
modifier onlyManager(){
require(msg.sender == _manager, "你不是管理者,无法进行对应操作!");
_;
}
constructor() public {
// 构造函数中创建t_LawLetter表
createTable();
_manager = msg.sender;
}
//修改授权,address userAddress 用户地址 .bool permitState 授权状态 true 开启,false关闭
function changePermitUser(address userAddress,bool permitState) public onlyManager returns(uint256){
uint256 state=0;
string memory stateMessage="";
permitUserMapping[userAddress]=permitState;
if(permitUserMapping[userAddress]==permitState){
state=1;
stateMessage="授权状态修改成功!";
}else{
stateMessage="授权状态修改失败!";
}
emit SetPermitUserEvent(state,msg.sender,userAddress,permitState,now,stateMessage);
return state;
}
function createTable() private {
TableFactory tf = TableFactory(0x1001);
// 存证数据管理表, key : serviceId(业务Id),
//field : typeName(业务类别), dataValue(json业务上链数据)
// 创建表
tf.createTable("tb_TraceEvidence_pro", "serviceId","typeName,dataValue");
}
function openTable() private returns(Table) {
TableFactory tf = TableFactory(0x1001);
Table table = tf.openTable("tb_TraceEvidence_pro");
return table;
}
/*
描述 : 根据业务Id查询业务上链数据
参数 :
返回值:
//field : typeName(业务类别), dataValue(json业务上链数据)
*/
function getServiceList(string serviceId) public view returns(int256,string[] memory, string[] memory) {
// 打开表
Table table = openTable();
Condition condition= table.newCondition();
condition.EQ("serviceId",serviceId);
// 查询
Entries entries = table.select(serviceId, condition);
string[] memory data_list = new string[](
uint256(entries.size())
);
string[] memory typeName_list = new string[](
uint256(entries.size())
);
if (0 == uint256(entries.size())) {
return (0, typeName_list,data_list);
} else {
for (int256 i = 0; i < entries.size(); ++i) {
Entry entry = entries.get(i);
data_list[uint256(i)] = entry.getString("dataValue");
typeName_list[uint256(i)] = entry.getString("typeName");
}
return (entries.size(),typeName_list, data_list);
}
}
/*
描述 : 数据上链
参数 :
//field : typeName(业务类别), dataValue(json业务上链数据)
返回值:
1 数据上链成功
0 数据上链失败
*/
function registerServiceData(string serviceId, string typeName,string dataValue) public returns(int256,string){
//require(permitUserMapping[msg.sender]==true,"未授权用户,禁止存证上链操作!");
int256 ret_code = 0;
// 打开表
Table table = openTable();
Condition condition= table.newCondition();
condition.EQ("dataValue",dataValue);
// 查询
Entries entries = table.select(serviceId, condition);
if (0 != uint256(entries.size())) {
return (0,"存证数据已存在,请确认后再上传!");
} else{
Entry entry = table.newEntry();
entry.set("serviceId", serviceId);
entry.set("typeName", typeName);
entry.set("dataValue",dataValue);
// 插入
int count = table.insert(serviceId, entry);
if (count == 1) {
// 成功
ret_code = 1;
return (ret_code,"存证数据上链,插入数据成功!");
} else {
// 失败? 无权限或者其他错误
ret_code =0;
return (ret_code,"存证数据上链,插入数据失败!");
}
}
}
}
|
修改授权,address userAddress 用户地址 .bool permitState 授权状态 true 开启,false关闭
|
function changePermitUser(address userAddress,bool permitState) public onlyManager returns(uint256){
uint256 state=0;
string memory stateMessage="";
permitUserMapping[userAddress]=permitState;
if(permitUserMapping[userAddress]==permitState){
state=1;
stateMessage="授权状态修改成功!";
stateMessage="授权状态修改失败!";
}
emit SetPermitUserEvent(state,msg.sender,userAddress,permitState,now,stateMessage);
return state;
}
| 7,284,526
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol";
import "../interfaces/ITokenExchange.sol";
import "../connectors/curve/interfaces/IRewardOnlyGauge.sol";
contract A3Crv2A3CrvGaugeTokenExchange is ITokenExchange {
IRewardOnlyGauge public rewardGauge;
IERC20 public a3CrvToken;
IERC20 public a3CrvGaugeToken;
constructor(address _curveGauge) {
require(_curveGauge != address(0), "Zero address not allowed");
rewardGauge = IRewardOnlyGauge(_curveGauge);
a3CrvToken = IERC20(rewardGauge.lp_token());
a3CrvGaugeToken = IERC20(_curveGauge);
}
function exchange(
address spender,
IERC20 from,
address receiver,
IERC20 to,
uint256 amount
) external override {
require(
(from == a3CrvToken && to == a3CrvGaugeToken) ||
(from == a3CrvGaugeToken && to == a3CrvToken),
"A3Crv2A3CrvGaugeTokenExchange: Some token not compatible"
);
if (amount == 0) {
from.transfer(spender, from.balanceOf(address(this)));
return;
}
if (from == a3CrvToken && to == a3CrvGaugeToken) {
//TODO: denominator usage
uint256 denominator = 10**(18 - IERC20Metadata(address(a3CrvToken)).decimals());
amount = amount / denominator;
uint256 a3CrvBalance = a3CrvToken.balanceOf(address(this));
require(
a3CrvBalance >= amount,
"A3Crv2A3CrvGaugeTokenExchange: Not enough a3CrvToken"
);
// check after denormilization
if (amount == 0) {
a3CrvToken.transfer(spender, a3CrvBalance);
return;
}
// gauge need approve on deposit cause by transferFrom inside deposit
a3CrvToken.approve(address(rewardGauge), amount);
rewardGauge.deposit(amount, receiver, false);
} else {
//TODO: denominator usage
uint256 denominator = 10**(18 - IERC20Metadata(address(a3CrvGaugeToken)).decimals());
amount = amount / denominator;
uint256 a3CrvGaugeBalance = a3CrvGaugeToken.balanceOf(address(this));
require(
a3CrvGaugeBalance >= amount,
"A3Crv2A3CrvGaugeTokenExchange: Not enough a3CrvGaugeToken"
);
// check after denormilization
if (amount == 0) {
a3CrvGaugeToken.transfer(spender, a3CrvGaugeBalance);
return;
}
// gauge doesn't need approve on withdraw, but we should have amount token
// on tokenExchange
rewardGauge.withdraw(amount, false);
uint256 a3CrvBalance = a3CrvToken.balanceOf(address(this));
require(
a3CrvBalance >= amount,
"A3Crv2A3CrvGaugeTokenExchange: Not enough a3CrvToken after withdraw"
);
// reward gauge transfer tokens to msg.sender, so transfer to receiver
a3CrvToken.transfer(receiver, a3CrvBalance);
}
}
}
|
TODO: denominator usage check after denormilization check after denormilization
|
function exchange(
address spender,
IERC20 from,
address receiver,
IERC20 to,
uint256 amount
) external override {
require(
(from == a3CrvToken && to == a3CrvGaugeToken) ||
(from == a3CrvGaugeToken && to == a3CrvToken),
"A3Crv2A3CrvGaugeTokenExchange: Some token not compatible"
);
if (amount == 0) {
from.transfer(spender, from.balanceOf(address(this)));
return;
}
if (from == a3CrvToken && to == a3CrvGaugeToken) {
uint256 denominator = 10**(18 - IERC20Metadata(address(a3CrvToken)).decimals());
amount = amount / denominator;
uint256 a3CrvBalance = a3CrvToken.balanceOf(address(this));
require(
a3CrvBalance >= amount,
"A3Crv2A3CrvGaugeTokenExchange: Not enough a3CrvToken"
);
if (amount == 0) {
a3CrvToken.transfer(spender, a3CrvBalance);
return;
}
rewardGauge.deposit(amount, receiver, false);
amount = amount / denominator;
uint256 a3CrvGaugeBalance = a3CrvGaugeToken.balanceOf(address(this));
require(
a3CrvGaugeBalance >= amount,
"A3Crv2A3CrvGaugeTokenExchange: Not enough a3CrvGaugeToken"
);
if (amount == 0) {
a3CrvGaugeToken.transfer(spender, a3CrvGaugeBalance);
return;
}
uint256 a3CrvBalance = a3CrvToken.balanceOf(address(this));
require(
a3CrvBalance >= amount,
"A3Crv2A3CrvGaugeTokenExchange: Not enough a3CrvToken after withdraw"
);
}
}
| 7,242,274
|
pragma solidity ^0.5.0;
/**
* @title SafeMath
* @dev Unsigned math operations with safety checks that revert on error
*/
library SafeMath {
/**
* @dev Multiplies two unsigned integers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two unsigned integers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract ERC20 {
// Get the total token supply
function totalSupply() public view returns (uint256);
// Get the account balance of another account with address _owner
function balanceOf(address who) public view returns (uint256);
// Send _value amount of tokens to address _to
function transfer(address to, uint256 value) public returns (bool);
// Send _value amount of tokens from address _from to address _to
function transferFrom(address from, address to, uint256 value) public returns (bool);
// Allow _spender to withdraw from your account, multiple times, up to the _value amount.
// If this function is called again it overwrites the current allowance with _value.
// this function is required for some DEX functionality
function approve(address spender, uint256 value) public returns (bool);
// Returns the amount which _spender is still allowed to withdraw from _owner
function allowance(address owner, address spender) public view returns (uint256);
// Triggered when tokens are transferred.
event Transfer(address indexed from, address indexed to, uint256 value);
// Triggered whenever approve(address _spender, uint256 _value) is called.
event Approval(address indexed owner,address indexed spender,uint256 value);
}
/// @title Implementation of basic ERC20 function.
/// @notice The only difference from most other ERC20 contracts is that we introduce 2 superusers - the founder and the admin.
contract _Base20 is ERC20 {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) internal allowed;
mapping(address => uint256) internal accounts;
address internal admin;
address payable internal founder;
uint256 internal __totalSupply;
constructor(uint256 _totalSupply,
address payable _founder,
address _admin) public {
__totalSupply = _totalSupply;
admin = _admin;
founder = _founder;
accounts[founder] = __totalSupply;
emit Transfer(address(0), founder, accounts[founder]);
}
// define onlyAdmin
modifier onlyAdmin {
require(admin == msg.sender);
_;
}
// define onlyFounder
modifier onlyFounder {
require(founder == msg.sender);
_;
}
// Change founder
function changeFounder(address payable who) onlyFounder public {
founder = who;
}
// show founder address
function getFounder() onlyFounder public view returns (address) {
return founder;
}
// Change admin
function changeAdmin(address who) public {
require(who == founder || who == admin);
admin = who;
}
// show admin address
function getAdmin() public view returns (address) {
require(msg.sender == founder || msg.sender == admin);
return admin;
}
//
// ERC20 spec.
//
function totalSupply() public view returns (uint256) {
return __totalSupply;
}
// ERC20 spec.
function balanceOf(address _owner) public view returns (uint256) {
return accounts[_owner];
}
function _transfer(address _from, address _to, uint256 _value)
internal returns (bool) {
require(_to != address(0));
require(_value <= accounts[_from]);
// This should go first. If SafeMath.add fails, the sender's balance is not changed
accounts[_to] = accounts[_to].add(_value);
accounts[_from] = accounts[_from].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
// ERC20 spec.
function transfer(address _to, uint256 _value) public returns (bool) {
return _transfer(msg.sender, _to, _value);
}
// ERC20 spec.
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool) {
require(_value <= allowed[_from][msg.sender]);
// _transfer is either successful, or throws.
_transfer(_from, _to, _value);
allowed[_from][msg.sender] -= _value;
emit Approval(_from, msg.sender, allowed[_from][msg.sender]);
return true;
}
// ERC20 spec.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
// ERC20 spec.
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
}
/// @title Admin can suspend specific wallets in cases of misbehaving or theft.
/// @notice This contract implements methods to lock tranfers, either globally or for specific accounts.
contract _Suspendable is _Base20 {
/// @dev flag whether transfers are allowed on global scale.
/// When `isTransferable` is `false`, all transfers between wallets are blocked.
bool internal isTransferable = false;
/// @dev set of suspended wallets.
/// When `suspendedAddresses[wallet]` is `true`, the `wallet` can't both send and receive COLs.
mapping(address => bool) internal suspendedAddresses;
/// @notice Sets total supply and the addresses of super users - founder and admin.
/// @param _totalSupply Total amount of Color Coin tokens available.
/// @param _founder Address of the founder wallet
/// @param _admin Address of the admin wallet
constructor(uint256 _totalSupply,
address payable _founder,
address _admin) public _Base20(_totalSupply, _founder, _admin)
{
}
/// @dev specifies that the marked method could be used only when transfers are enabled.
/// Founder can always transfer
modifier transferable {
require(isTransferable || msg.sender == founder);
_;
}
/// @notice Getter for the global flag `isTransferable`.
/// @dev Everyone is allowed to view it.
function isTransferEnabled() public view returns (bool) {
return isTransferable;
}
/// @notice Enable tranfers globally.
/// Note that suspended acccounts remain to be suspended.
/// @dev Sets the global flag `isTransferable` to `true`.
function enableTransfer() onlyAdmin public {
isTransferable = true;
}
/// @notice Disable tranfers globally.
/// All transfers between wallets are blocked.
/// @dev Sets the global flag `isTransferable` to `false`.
function disableTransfer() onlyAdmin public {
isTransferable = false;
}
/// @notice Check whether an address is suspended.
/// @dev Everyone can check any address they want.
/// @param _address wallet to check
/// @return returns `true` if the wallet `who` is suspended.
function isSuspended(address _address) public view returns(bool) {
return suspendedAddresses[_address];
}
/// @notice Suspend an individual wallet.
/// @dev Neither the founder nor the admin could be suspended.
/// @param who address of the wallet to suspend.
function suspend(address who) onlyAdmin public {
if (who == founder || who == admin) {
return;
}
suspendedAddresses[who] = true;
}
/// @notice Unsuspend an individual wallet
/// @param who address of the wallet to unsuspend.
function unsuspend(address who) onlyAdmin public {
suspendedAddresses[who] = false;
}
//
// Update of ERC20 functions
//
/// @dev Internal function for transfers updated.
/// Neither source nor destination of the transfer can be suspended.
function _transfer(address _from, address _to, uint256 _value) internal returns (bool) {
require(!isSuspended(_to));
require(!isSuspended(_from));
return super._transfer(_from, _to, _value);
}
/// @notice `transfer` can't happen when transfers are disabled globally
/// @dev added modifier `transferable`.
function transfer(address _to, uint256 _value) public transferable returns (bool) {
return _transfer(msg.sender, _to, _value);
}
/// @notice `transferFrom` can't happen when transfers are disabled globally
/// @dev added modifier `transferable`.
function transferFrom(address _from, address _to, uint256 _value) public transferable returns (bool) {
require(!isSuspended(msg.sender));
return super.transferFrom(_from, _to, _value);
}
// ERC20 spec.
/// @notice `approve` can't happen when transfers disabled globally
/// Suspended users are not allowed to do approvals as well.
/// @dev Added modifier `transferable`.
function approve(address _spender, uint256 _value) public transferable returns (bool) {
require(!isSuspended(msg.sender));
return super.approve(_spender, _value);
}
/// @notice Change founder. New founder must not be suspended.
function changeFounder(address payable who) onlyFounder public {
require(!isSuspended(who));
super.changeFounder(who);
}
/// @notice Change admin. New admin must not be suspended.
function changeAdmin(address who) public {
require(!isSuspended(who));
super.changeAdmin(who);
}
}
/// @title Advanced functions for Color Coin token smart contract.
/// @notice Implements functions for private ICO and super users.
/// @dev Not intended for reuse.
contract ColorCoinBase is _Suspendable {
/// @dev Represents a lock-up period.
struct LockUp {
/// @dev end of the period, in seconds since the epoch.
uint256 unlockDate;
/// @dev amount of coins to be unlocked at the end of the period.
uint256 amount;
}
/// @dev Represents a wallet with lock-up periods.
struct Investor {
/// @dev initial amount of locked COLs
uint256 initialAmount;
/// @dev current amount of locked COLs
uint256 lockedAmount;
/// @dev current lock-up period, index in the array `lockUpPeriods`
uint256 currentLockUpPeriod;
/// @dev the list of lock-up periods
LockUp[] lockUpPeriods;
}
/// @dev Entry in the `adminTransferLog`, that stores the history of admin operations.
struct AdminTransfer {
/// @dev the wallet, where COLs were withdrawn from
address from;
/// @dev the wallet, where COLs were deposited to
address to;
/// @dev amount of coins transferred
uint256 amount;
/// @dev the reason, why super user made this transfer
string reason;
}
/// @notice The event that is fired when a lock-up period expires for a certain wallet.
/// @param who the wallet where the lock-up period expired
/// @param period the number of the expired period
/// @param amount amount of unlocked coins.
event Unlock(address who, uint256 period, uint256 amount);
/// @notice The event that is fired when a super user makes transfer.
/// @param from the wallet, where COLs were withdrawn from
/// @param to the wallet, where COLs were deposited to
/// @param requestedAmount amount of coins, that the super user requested to transfer
/// @param returnedAmount amount of coins, that were actually transferred
/// @param reason the reason, why super user made this transfer
event SuperAction(address from, address to, uint256 requestedAmount, uint256 returnedAmount, string reason);
/// @dev set of wallets with lock-up periods
mapping (address => Investor) internal investors;
/// @dev wallet with the supply of Color Coins.
/// It is used to calculate circulating supply.
address internal supply;
/// @dev amount of Color Coins locked in lock-up wallets.
/// It is used to calculate circulating supply.
uint256 internal totalLocked;
/// @dev the list of transfers performed by super users
AdminTransfer[] internal adminTransferLog;
/// @notice Sets total supply and the addresses of super users - founder and admin.
/// @param _totalSupply Total amount of Color Coin tokens available.
/// @param _founder Address of the founder wallet
/// @param _admin Address of the admin wallet
constructor(uint256 _totalSupply,
address payable _founder,
address _admin
) public _Suspendable (_totalSupply, _founder, _admin)
{
supply = founder;
}
//
// ERC20 spec.
//
/// @notice Returns the balance of a wallet.
/// For wallets with lock-up the result of this function inludes both free floating and locked COLs.
/// @param _owner The address of a wallet.
function balanceOf(address _owner) public view returns (uint256) {
return accounts[_owner] + investors[_owner].lockedAmount;
}
/// @dev Performs transfer from one wallet to another.
/// The maximum amount of COLs to transfer equals to `balanceOf(_from) - getLockedAmount(_from)`.
/// This function unlocks COLs if any of lock-up periods expired at the moment
/// of the transaction execution.
/// Calls `Suspendable._transfer` to do the actual transfer.
/// This function is used by ERC20 `transfer` function.
/// @param _from wallet from which tokens are withdrawn.
/// @param _to wallet to which tokens are deposited.
/// @param _value amount of COLs to transfer.
function _transfer(address _from, address _to, uint256 _value)
internal returns (bool) {
if (hasLockup(_from)) {
tryUnlock(_from);
}
super._transfer(_from, _to, _value);
}
/// @notice The founder sends COLs to early investors and sets lock-up periods.
/// Initially all distributed COL's are locked.
/// @dev Only founder can call this function.
/// @param _to address of the wallet that receives the COls.
/// @param _value amount of COLs that founder sends to the investor's wallet.
/// @param unlockDates array of lock-up period dates.
/// Each date is in seconds since the epoch. After `unlockDates[i]` is expired,
/// the corresponding `amounts[i]` amount of COLs gets unlocked.
/// After expiring the last date in this array all COLs become unlocked.
/// @param amounts array of COL amounts to unlock.
function distribute(address _to, uint256 _value,
uint256[] memory unlockDates, uint256[] memory amounts
) onlyFounder public returns (bool) {
// We distribute invested coins to new wallets only
require(balanceOf(_to) == 0);
require(_value <= accounts[founder]);
require(unlockDates.length == amounts.length);
// We don't check that unlock dates strictly increase.
// That doesn't matter. It will work out in tryUnlock function.
// We don't check that amounts in total equal to _value.
// tryUnlock unlocks no more that _value anyway.
investors[_to].initialAmount = _value;
investors[_to].lockedAmount = _value;
investors[_to].currentLockUpPeriod = 0;
for (uint256 i=0; i<unlockDates.length; i++) {
investors[_to].lockUpPeriods.push(LockUp(unlockDates[i], amounts[i]));
}
// ensureLockUp(_to);
accounts[founder] -= _value;
emit Transfer(founder, _to, _value);
totalLocked = totalLocked.add(_value);
// Check the lock-up periods. If the leading periods are 0 or already expired
// unlock corresponding coins.
tryUnlock(_to);
return true;
}
/// @notice Returns `true` if the wallet has locked COLs
/// @param _address address of the wallet.
/// @return `true` if the wallet has locked COLs and `false` otherwise.
function hasLockup(address _address) public view returns(bool) {
return (investors[_address].lockedAmount > 0);
}
//
// Unlock operations
//
/// @dev tells whether the wallet still has lockup and number of seconds until unlock date.
/// @return locked if `locked` is true, the wallet still has a lockup period, otherwise all lockups expired.
/// @return seconds amount of time in seconds until unlock date. Zero means that it has expired,
/// and the user can invoke `doUnlock` to release corresponding coins.
function _nextUnlockDate(address who) internal view returns (bool, uint256) {
if (!hasLockup(who)) {
return (false, 0);
}
uint256 i = investors[who].currentLockUpPeriod;
// This must not happen! but still...
// If all lockup periods have expired, but there are still locked coins,
// tell the user to unlock.
if (i == investors[who].lockUpPeriods.length) return (true, 0);
if (now < investors[who].lockUpPeriods[i].unlockDate) {
// If the next unlock date is in the future, return the number of seconds left
return (true, investors[who].lockUpPeriods[i].unlockDate - now);
} else {
// The current unlock period has expired.
return (true, 0);
}
}
/// @notice tells the wallet owner whether the wallet still has lockup and number of seconds until unlock date.
/// @return locked if `locked` is true, the wallet still has a lockup period, otherwise all lockups expired.
/// @return seconds amount of time in seconds until unlock date. Zero means that it has expired,
/// and the user can invoke `doUnlock` to release corresponding coins.
function nextUnlockDate() public view returns (bool, uint256) {
return _nextUnlockDate(msg.sender);
}
/// @notice tells to the admin whether the wallet still has lockup and number of seconds until unlock date.
/// @return locked if `locked` is true, the wallet still has a lockup period, otherwise all lockups expired.
/// @return seconds amount of time in seconds until unlock date. Zero means that it has expired,
/// and the user can invoke `doUnlock` to release corresponding coins.
function nextUnlockDate_Admin(address who) public view onlyAdmin returns (bool, uint256) {
return _nextUnlockDate(who);
}
/// @notice the wallet owner signals that the next unlock period has passed, and some coins could be unlocked
function doUnlock() public {
tryUnlock(msg.sender);
}
/// @notice admin unlocks coins in the wallet, if any
/// @param who the wallet to unlock coins
function doUnlock_Admin(address who) public onlyAdmin {
tryUnlock(who);
}
/// @notice Returns the amount of locked coins in the wallet.
/// This function tells the amount of coins to the wallet owner only.
/// @return amount of locked COLs by `now`.
function getLockedAmount() public view returns (uint256) {
return investors[msg.sender].lockedAmount;
}
/// @notice Returns the amount of locked coins in the wallet.
/// @return amount of locked COLs by `now`.
function getLockedAmount_Admin(address who) public view onlyAdmin returns (uint256) {
return investors[who].lockedAmount;
}
function tryUnlock(address _address) internal {
if (!hasLockup(_address)) {
return ;
}
uint256 amount = 0;
uint256 i;
uint256 start = investors[_address].currentLockUpPeriod;
uint256 end = investors[_address].lockUpPeriods.length;
for ( i = start;
i < end;
i++)
{
if (investors[_address].lockUpPeriods[i].unlockDate <= now) {
amount += investors[_address].lockUpPeriods[i].amount;
} else {
break;
}
}
if (i == investors[_address].lockUpPeriods.length) {
// all unlock periods expired. Unlock all
amount = investors[_address].lockedAmount;
} else if (amount > investors[_address].lockedAmount) {
amount = investors[_address].lockedAmount;
}
if (amount > 0 || i > start) {
investors[_address].lockedAmount = investors[_address].lockedAmount.sub(amount);
investors[_address].currentLockUpPeriod = i;
accounts[_address] = accounts[_address].add(amount);
emit Unlock(_address, i, amount);
totalLocked = totalLocked.sub(amount);
}
}
//
// Admin privileges - return coins in the case of errors or theft
//
modifier superuser {
require(msg.sender == admin || msg.sender == founder);
_;
}
/// @notice Super user (founder or admin) unconditionally transfers COLs from one account to another.
/// This function is designed as the last resort in the case of mistake or theft.
/// Superuser provides verbal description of the reason to perform this operation.
/// @dev Only superuser can call this function.
/// @param from the wallet, where COLs were withdrawn from
/// @param to the wallet, where COLs were deposited to
/// @param amount amount of coins transferred
/// @param reason description of the reason, why super user invokes this transfer
function adminTransfer(address from, address to, uint256 amount, string memory reason) public superuser {
if (amount == 0) return;
uint256 requested = amount;
// Revert as much as possible
if (accounts[from] < amount) {
amount = accounts[from];
}
accounts[from] -= amount;
accounts[to] = accounts[to].add(amount);
emit SuperAction(from, to, requested, amount, reason);
adminTransferLog.push(AdminTransfer(from, to, amount, reason));
}
/// @notice Returns size of the history of super user actions
/// @return the number of elements in the log
function getAdminTransferLogSize() public view superuser returns (uint256) {
return adminTransferLog.length;
}
/// @notice Returns an element from the history of super user actions
/// @param pos index of element in the log, the oldest element has index `0`
/// @return tuple `(from, to, amount, reason)`. See description of `adminTransfer` function.
function getAdminTransferLogItem(uint32 pos) public view superuser
returns (address from, address to, uint256 amount, string memory reason)
{
require(pos < adminTransferLog.length);
AdminTransfer storage item = adminTransferLog[pos];
return (item.from, item.to, item.amount, item.reason);
}
//
// Circulating supply
//
/// @notice Returns the circulating supply of Color Coins.
/// It consists of all unlocked coins in user wallets.
function circulatingSupply() public view returns(uint256) {
return __totalSupply.sub(accounts[supply]).sub(totalLocked);
}
//
// Release contract
//
/// @notice Calls `selfdestruct` operator and transfers all Ethers to the founder (if any)
function destroy() public onlyAdmin {
selfdestruct(founder);
}
}
/// @title Dedicated methods for Pixel program
/// @notice Pixels are a type of “airdrop” distributed to all Color Coin wallet holders,
/// five Pixels a day. They are awarded on a periodic basis. Starting from Sunday GMT 0:00,
/// the Pixels have a lifespan of 24 hours. Pixels in their original form do not have any value.
/// The only way Pixels have value is by sending them to other wallet holders.
/// Pixels must be sent to another person’s account within 24 hours or they will become void.
/// Each user can send up to five Pixels to a single account per week. Once a wallet holder receives Pixels,
/// the Pixels will become Color Coins. The received Pixels may be converted to Color Coins
/// on weekly basis, after Saturday GMT 24:00.
/// @dev Pixel distribution might require thousands and tens of thousands transactions.
/// The methods in this contract consume less gas compared to batch transactions.
contract ColorCoinWithPixel is ColorCoinBase {
address internal pixelAccount;
/// @dev The rate to convert pixels to Color Coins
uint256 internal pixelConvRate;
/// @dev Methods could be called by either the founder of the dedicated account.
modifier pixelOrFounder {
require(msg.sender == founder || msg.sender == pixelAccount);
_;
}
function circulatingSupply() public view returns(uint256) {
uint256 result = super.circulatingSupply();
return result - balanceOf(pixelAccount);
}
/// @notice Initialises a newly created instance.
/// @dev Initialises Pixel-related data and transfers `_pixelCoinSupply` COLs
/// from the `_founder` to `_pixelAccount`.
/// @param _totalSupply Total amount of Color Coin tokens available.
/// @param _founder Address of the founder wallet
/// @param _admin Address of the admin wallet
/// @param _pixelCoinSupply Amount of tokens dedicated for Pixel program
/// @param _pixelAccount Address of the account that keeps coins for the Pixel program
constructor(uint256 _totalSupply,
address payable _founder,
address _admin,
uint256 _pixelCoinSupply,
address _pixelAccount
) public ColorCoinBase (_totalSupply, _founder, _admin)
{
require(_pixelAccount != _founder);
require(_pixelAccount != _admin);
pixelAccount = _pixelAccount;
accounts[pixelAccount] = _pixelCoinSupply;
accounts[_founder] = accounts[_founder].sub(_pixelCoinSupply);
emit Transfer(founder, pixelAccount, accounts[pixelAccount]);
}
/// @notice Founder or the pixel account set the pixel conversion rate.
/// Pixel team first sets this conversion rate and then start sending COLs
/// in exchange of pixels that people have received.
/// @dev This rate is used in `sendCoinsForPixels` functions to calculate the amount
/// COLs to transfer to pixel holders.
function setPixelConversionRate(uint256 _pixelConvRate) public pixelOrFounder {
pixelConvRate = _pixelConvRate;
}
/// @notice Get the conversion rate that was used in the most recent exchange of pixels to COLs.
function getPixelConversionRate() public view returns (uint256) {
return pixelConvRate;
}
/// @notice Distribute COL coins for pixels
/// COLs are spent from `pixelAccount` wallet. The amount of COLs is equal to `getPixelConversionRate() * pixels`
/// @dev Only founder and pixel account can invoke this function.
/// @param pixels Amount of pixels to exchange into COLs
/// @param destination The wallet that holds the pixels.
function sendCoinsForPixels(
uint32 pixels, address destination
) public pixelOrFounder {
uint256 coins = pixels*pixelConvRate;
if (coins == 0) return;
require(coins <= accounts[pixelAccount]);
accounts[destination] = accounts[destination].add(coins);
accounts[pixelAccount] -= coins;
}
/// @notice Distribute COL coins for pixels to multiple users.
/// This function consumes less gas compared to a batch transaction of `sendCoinsForPixels`.
/// `pixels[i]` specifies the amount of pixels belonging to `destinations[i]` wallet.
/// COLs are spent from `pixelAccount` wallet. The amount of COLs sent to i-th wallet is equal to `getPixelConversionRate() * pixels[i]`
/// @dev Only founder and pixel account can invoke this function.
/// @param pixels Array of pixel amounts to exchange into COLs
/// @param destinations Array of addresses of wallets that hold pixels.
function sendCoinsForPixels_Batch(
uint32[] memory pixels,
address[] memory destinations
) public pixelOrFounder {
require(pixels.length == destinations.length);
uint256 total = 0;
for (uint256 i = 0; i < pixels.length; i++) {
uint256 coins = pixels[i]*pixelConvRate;
address dst = destinations[i];
accounts[dst] = accounts[dst].add(coins);
total += coins;
}
require(total <= accounts[pixelAccount]);
accounts[pixelAccount] -= total;
}
/// @notice Distribute COL coins for pixels to multiple users.
/// COLs are spent from `pixelAccount` wallet. The amount of COLs sent to each wallet is equal to `getPixelConversionRate() * pixels`
/// @dev The difference between `sendCoinsForPixels_Array` and `sendCoinsForPixels_Batch`
/// is that all destination wallets hold the same amount of pixels.
/// This optimization saves about 10% of gas compared to `sendCoinsForPixels_Batch`
/// with the same amount of recipients.
/// @param pixels Amount of pixels to exchange. All of `recipients` hold the same amount of pixels.
/// @param recipients Addresses of wallets, holding `pixels` amount of pixels.
function sendCoinsForPixels_Array(
uint32 pixels, address[] memory recipients
) public pixelOrFounder {
uint256 coins = pixels*pixelConvRate;
uint256 total = coins * recipients.length;
if (total == 0) return;
require(total <= accounts[pixelAccount]);
for (uint256 i; i < recipients.length; i++) {
address dst = recipients[i];
accounts[dst] = accounts[dst].add(coins);
}
accounts[pixelAccount] -= total;
}
}
/// @title Smart contract for Color Coin token.
/// @notice Color is the next generation platform for high-performance sophisticated decentralized applications (dApps). https://www.colors.org/
/// @dev Not intended for reuse.
contract ColorCoin is ColorCoinWithPixel {
/// @notice Token name
string public constant name = "Color Coin";
/// @notice Token symbol
string public constant symbol = "COL";
/// @notice Precision in fixed point arithmetics
uint8 public constant decimals = 18;
/// @notice Initialises a newly created instance
/// @param _totalSupply Total amount of Color Coin tokens available.
/// @param _founder Address of the founder wallet
/// @param _admin Address of the admin wallet
/// @param _pixelCoinSupply Amount of tokens dedicated for Pixel program
/// @param _pixelAccount Address of the account that keeps coins for the Pixel program
constructor(uint256 _totalSupply,
address payable _founder,
address _admin,
uint256 _pixelCoinSupply,
address _pixelAccount
) public ColorCoinWithPixel (_totalSupply, _founder, _admin, _pixelCoinSupply, _pixelAccount)
{
}
}
|
Founder or the pixel account set the pixel conversion rate. Pixel team first sets this conversion rate and then start sending COLs in exchange of pixels that people have received. This rate is used in `sendCoinsForPixels` functions to calculate the amount COLs to transfer to pixel holders.
|
function setPixelConversionRate(uint256 _pixelConvRate) public pixelOrFounder {
pixelConvRate = _pixelConvRate;
}
| 6,455,007
|
/**
*Submitted for verification at FtmScan.com on 2021-11-17
*/
// SPDX-License-Identifier: MIT
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: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint256 value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint256 value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferFTM(address to, uint256 value) internal {
(bool success, ) = to.call{value: value}(new bytes(0));
require(success, 'TransferHelper: FTM_TRANSFER_FAILED');
}
}
library Address {
function isContract(address account) internal view returns (bool) {
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
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");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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);
}
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
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);
}
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
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);
}
}
}
}
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);
constructor() {
_setOwner(_msgSender());
}
function owner() public view virtual returns (address) {
return _owner;
}
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
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 IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC20Metadata is IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function decimals() public view virtual override returns (uint8) {
return 18;
}
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
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);
}
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: contracts/DevWallet.sol
contract DevWallet is Ownable {
uint public totalAllocPoints;
uint private _totalReleased;
IERC20 public immutable soul = IERC20(0xe2fb177009FF39F52C0134E8007FA0e4BaAcBd07);
mapping(address => uint) private allocation;
mapping(address => uint) private released;
address[] private users;
event UserAdded(address account, uint allocation);
event SharesUpdated(uint index, address account, uint allocation);
event PaymentReleased(address to, uint amount);
event PaymentReceived(address from, uint amount);
// `users` assigned # allocation matching indexed position in the `allocation` array
constructor() payable {
addUser(0xFd63Bf84471Bc55DD9A83fdFA293CCBD27e1F4C8, 5500);
addUser(0xdcD49C36E69bF85FA9c5a25dEA9455602C0B289e, 4500);
addUser(0x027a3F533149584ae6b33f1D2eA1CFa3dc8ddf84, 1250);
addUser(0xfdf676a740574Df045A97Fe7476e2584DA6CD309, 750);
addUser(0x81Dd37687c74Df8F957a370A9A4435D873F5e5A9, 1000);
transferOwnership(0x81Dd37687c74Df8F957a370A9A4435D873F5e5A9);
}
// shows the available SOUL balance of contract
function available() public view returns (uint) {
return soul.balanceOf(address(this));
}
// getter for the total allocation held by payees
function totalShares() public view returns (uint) {
return totalAllocPoints;
}
// getter for the total amount of SOUL already released
function totalReleased() public view returns (uint amountReleased) {
return _totalReleased;
}
// getter for the amount of allocation held by an account
function userShares(uint index) public view returns (uint amountShares) {
address account = users[index];
return allocation[account];
}
// getter for the amount of SOUL already released to a payee
function userReleased(uint index) public view returns (uint amountReleased) {
address account = users[index];
return released[account];
}
// getter for the address of the payee number `index`.
function userAddress(uint index) public view returns (address account) {
return users[index];
}
// transfers `account` amount of SOUL owed, according to their % and ttl withdrawals
function release(uint index) public {
address account = users[index];
require(allocation[account] > 0, 'release: account has no allocation');
// acquires the adjusted ttl received and calcs payment
available();
uint totalReceived = soul.balanceOf(address(this)) + _totalReleased;
uint payment = (totalReceived * allocation[account]) / totalAllocPoints - released[account];
// requires account is due payment
require(payment != 0, 'release: account is not due payment');
// releases payment and increments released
released[account] += payment;
_totalReleased += payment;
// sends SOUL to user
soul.transfer(account, payment);
emit PaymentReleased(account, payment);
}
// adds a new payee to the contract with their corresponding allocation
function addUser(address account, uint _allocPoints) public onlyOwner {
require(account != address(0), 'addUser: account is the zero address');
require(_allocPoints > 0, 'addUser: allocation are 0');
require(allocation[account] == 0, 'addUser: account already has allocation');
// pushes new address, updates allocation, updates ttl allocation
users.push(account);
allocation[account] = _allocPoints;
totalAllocPoints += _allocPoints;
emit UserAdded(account, _allocPoints);
}
// updates allocation allocated to an indexed user
function updateAllocation(uint index, uint _allocPoints) public onlyOwner {
address account = users[index];
require(allocation[account] >= 0, 'updateAllocation: user does not exist');
// [[-]] removes previous user[i] `allocation`
totalAllocPoints -= allocation[account];
// updates user[i] `allocation`
allocation[account] = _allocPoints;
// [[+]] updated `allocation` to `total allocation`
totalAllocPoints += _allocPoints;
emit SharesUpdated(index, account, _allocPoints);
}
// displays `account` amount of SOUL owed, according to their % and ttl withdrawals
function userBalance(uint index) public view returns (uint) {
address account = users[index];
require(allocation[account] >= 0, 'userBalance: user does not exist');
uint totalReceived = soul.balanceOf(address(this)) + _totalReleased;
uint userAllocation = enWei(allocation[account]);
// ttl SOUL `released` to user
uint userClaimed = released[account];
uint userAllocated = // share of the total allocaton belonging to user
fromWei( // scales down by factor of 1e18
totalReceived // ttl SOUL ever `received` by contract
* userAllocation // user's allocation points
/ totalAllocPoints // ttl alloc points
);
uint userUnclaimed = userAllocated - userClaimed;
// returns the remaining share of total (balance) received for given user
return userUnclaimed;
}
// converts to wei
function enWei(uint amount) public pure returns (uint) { return amount * 1e18; }
function fromWei(uint amount) public pure returns (uint) { return (amount / 1e18); }
}
|
getter for the total amount of SOUL already released
|
function totalReleased() public view returns (uint amountReleased) {
return _totalReleased;
}
| 12,998,291
|
pragma solidity >=0.4.21 <0.6.0;
import "openzeppelin-solidity/contracts/introspection/IERC1820Registry.sol";
import "openzeppelin-solidity/contracts/utils/Address.sol";
import "../interfaces/IDDAI.sol";
// Dollar cost averaging manager
// Account should be operator and stack manager
contract DCA {
using Address for address;
address public ddai;
bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
address payable internal msgSender;
struct UserData {
uint256 amount;
uint256 next;
uint256 interval;
uint256 amountLeft;
uint256 feePerInterval;
}
mapping(address => UserData) public dataOf;
constructor(address _ddai) public {
ddai = _ddai;
_erc1820.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
}
function set(uint256 _amount, uint256 _next, uint256 _interval, uint256 _totalAmount, uint256 _feePerInterval) external {
dataOf[_msgSender()] = UserData({
amount: _amount,
next: _next,
interval: _interval,
amountLeft: _totalAmount,
feePerInterval: _feePerInterval
});
if(_next < block.timestamp) {
poke(_msgSender(), 0);
}
}
function poke(address _account, uint256 _minFee) public returns(bool) {
UserData storage userData = dataOf[_account];
// If its not yet time to do dollar cost averaging or fee is too low do nothing
// Not reverting to not break batches
if(userData.next > block.timestamp) {
return false;
}
uint256 intervalsAmount = 1;
// Check if we should do more than one buy interval
if(userData.next < block.timestamp) {
intervalsAmount += (block.timestamp - userData.next) / userData.interval;
}
uint256 totalFee = userData.feePerInterval * intervalsAmount;
if(_minFee > totalFee) {
return false;
}
IDDAI ddaiContract = IDDAI(ddai);
uint256 dcaAmount = userData.amount * intervalsAmount;
ddaiContract.setStack(_account, dcaAmount);
ddaiContract.distributeStack(_account);
// transfer fee
if(_account != _msgSender()){
ddaiContract.operatorSend(_account, _msgSender(), totalFee, "", "");
}
return true;
}
function pokeBatch(address[] calldata _accounts, uint256 _minFee) external {
for(uint256 i = 0; i < _accounts.length; i ++) {
poke(_accounts[i], _minFee);
}
}
function tokensReceived(
address _operator,
address _from,
address _to,
uint256 _amount,
bytes calldata _userData,
bytes calldata _operatorData
) external {
require(msg.sender == ddai, "DCA.tokensReceived: MSG_SENDER_INVALID");
require(_amount == 0, "DCA.tokensReceived: AMOUNT_SHOULD_BE_ZERO");
require(_to == address(this), "DCA.tokensReceived: TO_SHOULD_BE_THIS");
msgSender = _from.toPayable();
address(this).call(_userData);
delete(msgSender);
}
function _msgSender() internal returns (address payable) {
// if being called from self msgSender is saved in storage
if(msg.sender != address(this)) {
return msgSender;
}
return msg.sender;
}
}
|
if being called from self msgSender is saved in storage
|
function _msgSender() internal returns (address payable) {
if(msg.sender != address(this)) {
return msgSender;
}
return msg.sender;
}
| 14,072,959
|
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "sol-datastructs/src/contracts/PolymorphicDictionaryLib.sol";
import "./structs/TableLib.sol";
import "./structs/ColumnLib.sol";
contract ORMBase {
//Libraries
using PolymorphicDictionaryLib for PolymorphicDictionaryLib.PolymorphicDictionary;
using TableLib for TableLib.Table;
using TableLib for bytes;
using ColumnLib for ColumnLib.Column;
using ColumnLib for bytes;
//Constants
//schemas
//bytes32 constant schemas = 0x736368656d617300000000000000000000000000000000000000000000000000;
//schemas.public
//bytes32 constant schemasPublic = 0x736368656d61732e7075626c6963000000000000000000000000000000000000;
//schemas.public.tables
bytes32 constant schemasPublicTables = 0x736368656d61732e7075626c69632e7461626c65730000000000000000000000;
//Storage
PolymorphicDictionaryLib.PolymorphicDictionary internal dictionary;
//Create default tables
//Override this for OpenZepelin initializer
function initialize() public returns (bool) {
_initialize();
}
function _initialize() internal returns (bool) {
bool s1 = dictionary.addKey(
schemasPublicTables,
PolymorphicDictionaryLib.DictionaryType.OneToManyFixed
);
return s1;
}
// ****************************** TABLE OPERATIONS ******************************
function createTable(
bytes32 _name,
bytes32[] memory _columnName,
bytes32[] memory _columnDtype
) public returns (bool) {
TableLib.Table memory table = TableLib.create(
_name,
_columnName,
_columnDtype
);
return createTable(table);
}
//TO DO name hash
function createTable(TableLib.Table memory _table) internal returns (bool) {
//Add definition
//bytes32 label = keccak256(keccak256(schemasPublicTables), _table.name);
bool s2 = dictionary.addValueForKey(schemasPublicTables, _table.name);
bytes memory encoded = _table.encode();
bool s1 = dictionary.setValueForKey(_table.name, encoded);
//Add data store key
//(default fixed)
//dictionary.addKey(_table, PolymorphicDictionaryLib.DictionaryType.OneToManyFixed);
return s1 && s2;
}
// EXPERIMENTAL
function getTable(bytes32 _name)
public
view
returns (TableLib.Table memory)
{
bytes memory encoded = dictionary.getBytesForKey(_name);
return encoded.decodeTable();
}
// ****************************** DICTIONARY OPERATIONS ******************************
// ****************************** ENUMERATE OPERATIONS ******************************
/**
* @dev Enumerate all dictionary keys. O(n).
* @return bytes32[] dictionary keys.
*/
function enumerate() public view returns (bytes32[] memory) {
return dictionary.enumerate();
}
/**
* @dev Enumerate dictionary keys based on storage type. O(n).
* @param _type The dictionary type. OneToManyFixed/OneToManyVariable/OneToOneFixed/OneToOneVariable
* @return bytes32[] dictionary keys.
*/
function enumerate(PolymorphicDictionaryLib.DictionaryType _type)
public
view
returns (bytes32[] memory)
{
return dictionary.enumerate(_type);
}
/**
* @dev Enumerate dictionary set fixed values at dictionary[_key]. O(n).
* @param _key The bytes32 key.
* @return bytes32[] values at key.
*/
function enumerateForKeyOneToManyFixed(bytes32 _key)
public
view
returns (bytes32[] memory)
{
return dictionary.enumerateForKeyOneToManyFixed(_key);
}
/**
* @dev Enumerate dictionary set variable values at dictionary[_key]. O(n).
* @param _key The bytes32 key.
* @return bytes[] values at key.
*/
// EXPERIMENTAL
function enumerateForKeyOneToManyVariable(bytes32 _key)
public
view
returns (bytes[] memory)
{
return dictionary.enumerateForKeyOneToManyVariable(_key);
}
// ****************************** CONTAINS OPERATIONS ******************************
/**
* @dev Check if dictionary contains key. O(1).
* @param _key The bytes32 key.
* @return true if key exists.
*/
function containsKey(bytes32 _key) public view returns (bool) {
return dictionary.containsKey(_key);
}
/**
* @dev Check if dictionary contains key based on storage type. O(1).
* @param _key The bytes32 key.
* @param _type The dictionary type. OneToManyFixed/OneToManyVariable/OneToOneFixed/OneToOneVariable
* @return true if key exists.
*/
function containsKey(
bytes32 _key,
PolymorphicDictionaryLib.DictionaryType _type
) public view returns (bool) {
return dictionary.containsKey(_key, _type);
}
/**
* @dev Check if dictionary contains fixed value at key. O(1).
* @param _key The bytes32 key.
* @param _value The bytes32 value.
* @return true if value exists at key.
*/
function containsValueForKey(bytes32 _key, bytes32 _value)
public
view
returns (bool)
{
return dictionary.containsValueForKey(_key, _value);
}
/**
* @dev Check if dictionary contains variable value at key. O(1).
* @param _key The bytes32 key.
* @param _value The bytes value.
* @return true if value exists at key.
*/
function containsValueForKey(bytes32 _key, bytes memory _value)
public
view
returns (bool)
{
return dictionary.containsValueForKey(_key, _value);
}
// ****************************** LENGTH OPERATIONS ******************************
/**
* @dev Get the number of keys in the dictionary. O(1).
* @return uint256 length.
*/
function length() public view returns (uint256) {
return dictionary.length();
}
/**
* @dev Get the number of values at dictionary[_key]. O(1).
* @param _key The bytes32 key.
* @return uint256 length.
*/
function lengthForKey(bytes32 _key) public view returns (uint256) {
return dictionary.lengthForKey(_key);
}
// ****************************** READ OPERATIONS ******************************
/**
* @dev Get fixed value at dictionary[_key]. O(1).
* @param key The bytes32 key.
* @return bytes32 value.
*/
function getBytes32ForKey(bytes32 key) public view returns (bytes32) {
return dictionary.getBytes32ForKey(key);
}
/**
* @dev Get bool value at dictionary[_key]. O(1).
* @param key The bytes32 key.
* @return bool value.
*/
function getBoolForKey(bytes32 key) public view returns (bool) {
return dictionary.getBoolForKey(key);
}
/**
* @dev Get uint256 value at dictionary[_key]. O(1).
* @param key The bytes32 key.
* @return uint256 value.
*/
function getUInt256ForKey(bytes32 key) public view returns (uint256) {
return dictionary.getUInt256ForKey(key);
}
/**
* @dev Get int256 value at dictionary[_key]. O(1).
* @param key The bytes32 key.
* @return int256 value.
*/
function getInt256ForKey(bytes32 key) public view returns (int256) {
return dictionary.getInt256ForKey(key);
}
/**
* @dev Get address value at dictionary[_key]. O(1).
* @param key The bytes32 key.
* @return address value.
*/
function getAddressForKey(bytes32 key) public view returns (address) {
return dictionary.getAddressForKey(key);
}
/**
* @dev Get variable value at dictionary[_key]. O(1).
* @param key The bytes32 key.
* @return bytes value.
*/
function getBytesForKey(bytes32 key) public view returns (bytes memory) {
return dictionary.getBytesForKey(key);
}
/**
* @dev Get Bytes32Set value set at dictionary[_key]. O(1).
* @param key The bytes32 key.
* @return Bytes32Set value set.
*/
function getBytes32SetForKey(bytes32 key)
internal
view
returns (Bytes32SetLib.Bytes32Set memory)
{
return dictionary.getBytes32SetForKey(key);
}
/**
* @dev Get BytesSet value set at dictionary[_key]. O(1).
* @param key The bytes32 key.
* @return BytesSet value set.
*/
function getBytesSetForKey(bytes32 key)
internal
view
returns (BytesSetLib.BytesSet memory)
{
return dictionary.getBytesSetForKey(key);
}
/**
* @dev Get bytes32[] value array at dictionary[key]. O(dictionary[key].length()).
* @param key The bytes32 key.
* @return bytes32[] value array.
*/
function getBytes32ArrayForKey(bytes32 key)
public
view
returns (bytes32[] memory)
{
return dictionary.getBytes32ArrayForKey(key);
}
/**
* @dev Get bool[] value array at dictionary[key]. O(dictionary[key].length()).
* @param key The bytes32 key.
* @return bool[] value array.
*/
function getBoolArrayForKey(bytes32 key)
public
view
returns (bool[] memory)
{
return dictionary.getBoolArrayForKey(key);
}
/**
* @dev Get uint256[] value array at dictionary[key]. O(dictionary[key].length()).
* @param key The bytes32 key.
* @return uint256[] value array.
*/
function getUIntArrayForKey(bytes32 key)
public
view
returns (uint256[] memory)
{
return dictionary.getUIntArrayForKey(key);
}
/**
* @dev Get int256[] value array at dictionary[key]. O(dictionary[key].length()).
* @param key The bytes32 key.
* @return int256[] value array.
*/
function getIntArrayForKey(bytes32 key)
public
view
returns (int256[] memory)
{
return dictionary.getIntArrayForKey(key);
}
/**
* @dev Get address[] value array at dictionary[key]. O(dictionary[key].length()).
* @param key The bytes32 key.
* @return address[] value array.
*/
function getAddressArrayForKey(bytes32 key)
public
view
returns (address[] memory)
{
return dictionary.getAddressArrayForKey(key);
}
// ****************************** WRITE OPERATIONS ******************************
// ****************************** SET VALUE ******************************
/**
* @dev Set fixed value at dictionary[key]. O(1).
* @param _key The bytes32 key.
* @param _value The bytes32 value.
* @return bool true if succeeded (no conflicts).
*/
function setValueForKey(bytes32 _key, bytes32 _value)
public
returns (bool)
{
return dictionary.setValueForKey(_key, _value);
}
/**
* @dev Set bool value at dictionary[key]. O(1).
* @param _key The bytes32 key.
* @param _value The bool value.
* @return bool true if succeeded (no conflicts).
*/
function setBoolForKey(bytes32 _key, bool _value) public returns (bool) {
dictionary.setBoolForKey(_key, _value);
}
/**
* @dev Set uint value at dictionary[key]. O(1).
* @param _key The bytes32 key.
* @param _value The uint value.
* @return bool true if succeeded (no conflicts).
*/
function setUIntForKey(bytes32 _key, uint256 _value) public returns (bool) {
return dictionary.setUIntForKey(_key, _value);
}
/**
* @dev Set int value at dictionary[key]. O(1).
* @param _key The bytes32 key.
* @param _value The int value.
* @return bool true if succeeded (no conflicts).
*/
function setIntForKey(bytes32 _key, int256 _value) public returns (bool) {
return dictionary.setIntForKey(_key, _value);
}
/**
* @dev Set address value at dictionary[key]. O(1).
* @param _key The bytes32 key.
* @param _value The address value.
* @return bool true if succeeded (no conflicts).
*/
function setAddressForKey(bytes32 _key, address _value)
public
returns (bool)
{
return dictionary.setAddressForKey(_key, _value);
}
/**
* @dev Set variable value at dictionary[key]. O(1).
* @param _key The bytes32 key.
* @param _value The bytes value.
* @return bool true if succeeded (no conflicts).
*/
function setValueForKey(bytes32 _key, bytes memory _value)
public
returns (bool)
{
return dictionary.setValueForKey(_key, _value);
}
// ****************************** ADD VALUE ******************************
/**
* @dev Add fixed value to set at dictionary[key]. O(1).
* @param _key The bytes32 key.
* @param _value The bytes32 value.
* @return bool true if succeeded (no conflicts).
*/
function addValueForKey(bytes32 _key, bytes32 _value)
public
returns (bool)
{
return dictionary.addValueForKey(_key, _value);
}
/**
* @dev Add bool value to set at dictionary[key]. O(1).
* @param _key The bytes32 key.
* @param _value The bool value.
* @return bool true if succeeded (no conflicts).
*/
function addBoolForKey(bytes32 _key, bool _value) public returns (bool) {
return dictionary.addBoolForKey(_key, _value);
}
/**
* @dev Add uint value to set at dictionary[key]. O(1).
* @param _key The bytes32 key.
* @param _value The uint value.
* @return bool true if succeeded (no conflicts).
*/
function addUIntForKey(bytes32 _key, uint256 _value) public returns (bool) {
return dictionary.addUIntForKey(_key, _value);
}
/**
* @dev Add int value to set at dictionary[key]. O(1).
* @param _key The bytes32 key.
* @param _value The int value.
* @return bool true if succeeded (no conflicts).
*/
function addIntForKey(bytes32 _key, int256 _value) public returns (bool) {
return dictionary.addIntForKey(_key, _value);
}
/**
* @dev Add address value to set at dictionary[key]. O(1).
* @param _key The bytes32 key.
* @param _value The address value.
* @return bool true if succeeded (no conflicts).
*/
function addAddressForKey(bytes32 _key, address _value)
public
returns (bool)
{
return dictionary.addAddressForKey(_key, _value);
}
/**
* @dev Add variable value to set at dictionary[key]. O(1).
* @param _key The bytes32 key.
* @param _value The variable value.
* @return bool true if succeeded (no conflicts).
*/
function addValueForKey(bytes32 _key, bytes memory _value)
public
returns (bool)
{
return dictionary.addValueForKey(_key, _value);
}
// ****************************** ADD/REMOVE KEYS ******************************
/**
* @dev Add key (no value) to dictionary[key]. O(1).
* @param _key The bytes32 key.
* @param _type The dictionary type. OneToManyFixed/OneToManyVariable/OneToOneFixed/OneToOneVariable
* @return bool true if succeeded (no conflicts).
*/
function addKey(bytes32 _key, PolymorphicDictionaryLib.DictionaryType _type)
public
returns (bool)
{
return dictionary.addKey(_key, _type);
}
/**
* @dev Remove key from dictionary[key]. O(1).
* @param _key The bytes32 key.
* @return bool true if succeeded (no conflicts).
*/
function removeKey(bytes32 _key) public returns (bool) {
return dictionary.removeKey(_key);
}
/**
* @dev Remove fixed value from set at dictionary[key].
* @param _key The bytes32 key.
* @param _value The bytes32 value.
* @return bool true if succeeded (no conflicts).
*/
function removeValueForKey(bytes32 _key, bytes32 _value)
public
returns (bool)
{
return dictionary.removeValueForKey(_key, _value);
}
/**
* @dev Remove variable value from set at dictionary[key].
* @param _key The bytes32 key.
* @param _value The bytes value.
* @return bool true if succeeded (no conflicts).
*/
function removeValueForKey(bytes32 _key, bytes memory _value)
public
returns (bool)
{
return dictionary.removeValueForKey(_key, _value);
}
}
|
Add uint value to set at dictionary[key]. O(1). _key The bytes32 key. _value The uint value. return bool true if succeeded (no conflicts)./
|
function addUIntForKey(bytes32 _key, uint256 _value) public returns (bool) {
return dictionary.addUIntForKey(_key, _value);
}
| 12,583,151
|
pragma solidity ^0.5.0;
contract Token {
uint256 public totalSupply;
/* This generates a public event on the blockchain that will notify clients */
event Transfer(address indexed from, address indexed to, uint256 value);
function getHolderContract(address a) internal view returns (Holder) {
bytes32 holder_init_code_hash = 0x17bf60e63d4e2cc380fc7b8d419f6ebf015f77b0916680115f61cc123093468f;
address payable holder_address = address(uint256(keccak256(abi.encodePacked(byte(0xff),factory,bytes32(uint256(a)),holder_init_code_hash))));
uint256 codeLength;
assembly {codeLength := extcodesize(holder_address)}
require(codeLength > 0); // Not creating a new holder contract here, because if it does have ETH for rent, it can get evicted
return Holder(holder_address);
}
/* Send tokens */
function transfer(address _to, uint256 _value) public returns (bool) {
Holder fromContract = getHolderContract(msg.sender);
Holder toContract = getHolderContract(_to);
uint256 fromBalance = fromContract.getBalance();
uint256 toBalance = toContract.getBalance();
require(fromBalance >= _value); // Check if the sender has enough
require(toBalance + _value >= toBalance); // Check for overflows
fromContract.setBalance(fromBalance - _value); // Subtract from the sender
toContract.setBalance(toBalance + _value); // Add the same to the recipient
emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint256 _value) public returns (bool) {
Holder fromContract = getHolderContract(msg.sender);
fromContract.setAllowance(_spender, _value);
return true;
}
/* A contract attempts to get the tokens */
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
Holder fromContract = getHolderContract(_from);
Holder toContract = getHolderContract(_to);
uint256 fromBalance = fromContract.getBalance();
uint256 toBalance = toContract.getBalance();
uint256 fromAllowance = fromContract.getAllowance(msg.sender);
require(fromBalance >= _value); // Check if the sender has enough
require(toBalance + _value >= toBalance); // Check for overflows
require(_value <= fromAllowance); // Check allowance
fromContract.setBalance(fromBalance - _value); // Subtract from the sender
toContract.setBalance(toBalance + _value); // Add the same to the recipient
fromContract.setAllowance(msg.sender, fromAllowance - _value);
emit Transfer(_from, _to, _value);
return true;
}
function balanceOf(address a) public view returns (uint256) {
Holder c = getHolderContract(a);
return c.getBalance();
}
function allowance(address a, address _spender) public view returns (uint256) {
Holder c = getHolderContract(a);
return c.getAllowance(_spender);
}
address public minter;
address public factory;
constructor(address _minter, address _factory) public {
minter = _minter;
factory = _factory;
}
// Needs to accept ETH to pay rent
function() external payable {
}
/* Allows the owner to mint more tokens */
function mint(address _to, uint256 _value) public returns (bool) {
require(msg.sender == minter); // Only the minter is allowed to mint
Holder toContract = getHolderContract(_to);
uint256 toBalance = toContract.getBalance();
require(toBalance + _value >= toBalance); // Check for overflows
toContract.setBalance(toBalance + _value);
totalSupply += _value;
return true;
}
}
contract Holder {
address public constant SENTINEL_TOKEN_CONTRACTS = address(0x1);
mapping(address => address) internal tokenContracts;
address payable internal owner;
address internal factory; // This will be non-zero only until setOwner is successfully invoked
mapping(address => uint256) internal balances;
mapping(address => mapping(address => uint256)) internal allowances;
constructor() public {
factory = msg.sender;
tokenContracts[SENTINEL_TOKEN_CONTRACTS] = SENTINEL_TOKEN_CONTRACTS;
}
function setOwner(address payable _owner, bytes32 init_code_hash) public {
require(address(uint256(keccak256(abi.encodePacked(byte(0xff),factory,bytes32(uint256(_owner)),init_code_hash)))) == address(this));
owner = _owner;
factory = address(0);
}
// Needs to accept ETH to pay rent
function() external payable {
}
function addTokenContract(address tokenContract) public {
require(owner != address(0));
require(msg.sender == owner);
require(tokenContract != address(0) && tokenContract != SENTINEL_TOKEN_CONTRACTS);
require(tokenContracts[tokenContract] == address(0)); // Not yet in the list
tokenContracts[tokenContract] = tokenContracts[SENTINEL_TOKEN_CONTRACTS];
tokenContracts[SENTINEL_TOKEN_CONTRACTS] = tokenContract;
}
function removeTokenContract(address tokenContract, address prev) public {
require(owner != address(0));
require(msg.sender == owner);
require(tokenContract != address(0) && tokenContract != SENTINEL_TOKEN_CONTRACTS);
require(tokenContracts[prev] == tokenContract);
tokenContracts[prev] = tokenContracts[tokenContract];
tokenContracts[tokenContract] = address(0);
}
// Removes all the tokens and returns ETH balance to the owner
function destroy() public {
require(owner != address(0));
require(msg.sender == owner);
//TODO: Notify all the contracts so they can reduce supply accordingly - these tokens are gone forever!!!
selfdestruct(owner);
}
function getBalance() public view returns (uint256) {
require(msg.sender != SENTINEL_TOKEN_CONTRACTS);
require(tokenContracts[msg.sender] != address(0));
return balances[msg.sender];
}
function setBalance(uint256 value) public {
require(msg.sender != SENTINEL_TOKEN_CONTRACTS);
require(tokenContracts[msg.sender] != address(0));
balances[msg.sender] = value;
}
function getAllowance(address _spender) public view returns (uint256) {
require(msg.sender != SENTINEL_TOKEN_CONTRACTS);
require(tokenContracts[msg.sender] != address(0));
return allowances[msg.sender][_spender];
}
function setAllowance(address _spender, uint256 value) public {
require(msg.sender != SENTINEL_TOKEN_CONTRACTS);
require(tokenContracts[msg.sender] != address(0));
allowances[msg.sender][_spender] = value;
}
}
contract Factory {
event HolderCreated(Holder holder, address owner);
event TokenCreated(Token token, address minter);
function createToken(address _minter) public returns (Token) {
Token token = new Token(_minter, address(this));
emit TokenCreated(token, _minter);
return token;
}
function createHolder(address payable _owner) public returns (Holder) {
bytes memory holder_init_code = hex"608060405234801561001057600080fd5b5033600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506001600080600173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555061118c806100e06000396000f3fe608060405260043610610099576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806312065fe01461009b5780632a847f46146100c6578063310ec4a7146101175780634df4d0391461017257806383197ef0146101c95780638852671e146101e057806399d3c20414610251578063eb5a662e146102ac578063fb1669ca14610311575b005b3480156100a757600080fd5b506100b061034c565b6040518082815260200191505060405180910390f35b3480156100d257600080fd5b50610115600480360360208110156100e957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610469565b005b34801561012357600080fd5b506101706004803603604081101561013a57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061078e565b005b34801561017e57600080fd5b506101876108e9565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156101d557600080fd5b506101de6108ee565b005b3480156101ec57600080fd5b5061024f6004803603604081101561020357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506109e3565b005b34801561025d57600080fd5b506102aa6004803603604081101561027457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610d07565b005b3480156102b857600080fd5b506102fb600480360360208110156102cf57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610ee7565b6040518082815260200191505060405180910390f35b34801561031d57600080fd5b5061034a6004803603602081101561033457600080fd5b8101908080359060200190929190505050611043565b005b6000600173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415151561038a57600080fd5b600073ffffffffffffffffffffffffffffffffffffffff166000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415151561042457600080fd5b600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905090565b600073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141515156104c757600080fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561052357600080fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415801561058d5750600173ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614155b151561059857600080fd5b600073ffffffffffffffffffffffffffffffffffffffff166000808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614151561063157600080fd5b600080600173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166000808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555080600080600173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515156107ca57600080fd5b600073ffffffffffffffffffffffffffffffffffffffff166000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415151561086457600080fd5b80600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505050565b600181565b600073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415151561094c57600080fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415156109a857600080fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16ff5b600073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614151515610a4157600080fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515610a9d57600080fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614158015610b075750600173ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614155b1515610b1257600080fd5b8173ffffffffffffffffffffffffffffffffffffffff166000808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141515610baa57600080fd5b6000808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166000808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060008060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505050565b3073ffffffffffffffffffffffffffffffffffffffff1660ff7f010000000000000000000000000000000000000000000000000000000000000002600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff166001028460405160200180857effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff191681526001018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c01000000000000000000000000028152601401838152602001828152602001945050505050604051602081830303815290604052805190602001206001900473ffffffffffffffffffffffffffffffffffffffff16141515610e6057600080fd5b81600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505050565b6000600173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151515610f2557600080fd5b600073ffffffffffffffffffffffffffffffffffffffff166000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614151515610fbf57600080fd5b600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b600173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415151561107f57600080fd5b600073ffffffffffffffffffffffffffffffffffffffff166000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415151561111957600080fd5b80600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505056fea165627a7a72305820fcc4fbded726882960a22fcbb868fbd0701133626d09eab23d55ffc330bfdda60029";
bytes32 holder_init_code_hash = 0x17bf60e63d4e2cc380fc7b8d419f6ebf015f77b0916680115f61cc123093468f;
// The following line can be commented out to save gas
require(holder_init_code_hash == keccak256(holder_init_code));
address payable h;
assembly{
h := create2(0, add(holder_init_code, 32), mload(holder_init_code), _owner)
}
require(h != address(0));
Holder holder = Holder(h);
holder.setOwner(_owner, holder_init_code_hash);
emit HolderCreated(holder, _owner);
return holder;
}
}
|
The following line can be commented out to save gas
|
function createHolder(address payable _owner) public returns (Holder) {
bytes memory holder_init_code = hex"608060405234801561001057600080fd5b5033600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506001600080600173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555061118c806100e06000396000f3fe608060405260043610610099576000357c0100000000000000000000000000000000000000000000000000000000900463ffffffff16806312065fe01461009b5780632a847f46146100c6578063310ec4a7146101175780634df4d0391461017257806383197ef0146101c95780638852671e146101e057806399d3c20414610251578063eb5a662e146102ac578063fb1669ca14610311575b005b3480156100a757600080fd5b506100b061034c565b6040518082815260200191505060405180910390f35b3480156100d257600080fd5b50610115600480360360208110156100e957600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610469565b005b34801561012357600080fd5b506101706004803603604081101561013a57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff1690602001909291908035906020019092919050505061078e565b005b34801561017e57600080fd5b506101876108e9565b604051808273ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200191505060405180910390f35b3480156101d557600080fd5b506101de6108ee565b005b3480156101ec57600080fd5b5061024f6004803603604081101561020357600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190803573ffffffffffffffffffffffffffffffffffffffff1690602001909291905050506109e3565b005b34801561025d57600080fd5b506102aa6004803603604081101561027457600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff16906020019092919080359060200190929190505050610d07565b005b3480156102b857600080fd5b506102fb600480360360208110156102cf57600080fd5b81019080803573ffffffffffffffffffffffffffffffffffffffff169060200190929190505050610ee7565b6040518082815260200191505060405180910390f35b34801561031d57600080fd5b5061034a6004803603602081101561033457600080fd5b8101908080359060200190929190505050611043565b005b6000600173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415151561038a57600080fd5b600073ffffffffffffffffffffffffffffffffffffffff166000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415151561042457600080fd5b600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002054905090565b600073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141515156104c757600080fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151561052357600080fd5b600073ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff161415801561058d5750600173ffffffffffffffffffffffffffffffffffffffff168173ffffffffffffffffffffffffffffffffffffffff1614155b151561059857600080fd5b600073ffffffffffffffffffffffffffffffffffffffff166000808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614151561063157600080fd5b600080600173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166000808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555080600080600173ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555050565b600173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515156107ca57600080fd5b600073ffffffffffffffffffffffffffffffffffffffff166000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415151561086457600080fd5b80600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505050565b600181565b600073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415151561094c57600080fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415156109a857600080fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16ff5b600073ffffffffffffffffffffffffffffffffffffffff16600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614151515610a4157600080fd5b600160009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff16141515610a9d57600080fd5b600073ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614158015610b075750600173ffffffffffffffffffffffffffffffffffffffff168273ffffffffffffffffffffffffffffffffffffffff1614155b1515610b1257600080fd5b8173ffffffffffffffffffffffffffffffffffffffff166000808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16141515610baa57600080fd5b6000808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff166000808373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff16021790555060008060008473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505050565b3073ffffffffffffffffffffffffffffffffffffffff1660ff7f010000000000000000000000000000000000000000000000000000000000000002600260009054906101000a900473ffffffffffffffffffffffffffffffffffffffff168473ffffffffffffffffffffffffffffffffffffffff166001028460405160200180857effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff19167effffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff191681526001018473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff166c01000000000000000000000000028152601401838152602001828152602001945050505050604051602081830303815290604052805190602001206001900473ffffffffffffffffffffffffffffffffffffffff16141515610e6057600080fd5b81600160006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055506000600260006101000a81548173ffffffffffffffffffffffffffffffffffffffff021916908373ffffffffffffffffffffffffffffffffffffffff1602179055505050565b6000600173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff1614151515610f2557600080fd5b600073ffffffffffffffffffffffffffffffffffffffff166000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff1614151515610fbf57600080fd5b600460003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060008373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020549050919050565b600173ffffffffffffffffffffffffffffffffffffffff163373ffffffffffffffffffffffffffffffffffffffff161415151561107f57600080fd5b600073ffffffffffffffffffffffffffffffffffffffff166000803373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff16815260200190815260200160002060009054906101000a900473ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff161415151561111957600080fd5b80600360003373ffffffffffffffffffffffffffffffffffffffff1673ffffffffffffffffffffffffffffffffffffffff168152602001908152602001600020819055505056fea165627a7a72305820fcc4fbded726882960a22fcbb868fbd0701133626d09eab23d55ffc330bfdda60029";
bytes32 holder_init_code_hash = 0x17bf60e63d4e2cc380fc7b8d419f6ebf015f77b0916680115f61cc123093468f;
require(holder_init_code_hash == keccak256(holder_init_code));
address payable h;
assembly{
h := create2(0, add(holder_init_code, 32), mload(holder_init_code), _owner)
}
require(h != address(0));
Holder holder = Holder(h);
holder.setOwner(_owner, holder_init_code_hash);
emit HolderCreated(holder, _owner);
return holder;
}
| 7,308,042
|
// File: github/Team3dVidyaGames/VidyaGenerator/contracts/interfaces/IVault.sol
pragma solidity ^0.8.6;
/**
* @title Vault Interface
*/
interface IVault {
/**
* @dev External function to get vidya rate.
*/
function rewardRate() external view returns (uint256);
/**
* @dev External function to get total priority.
*/
function totalPriority() external view returns (uint256);
/**
* @dev External function to get teller priority.
* @param tellerId Teller Id
*/
function tellerPriority(address tellerId) external view returns (uint256);
/**
* @dev External function to add the teller. This function can be called by only owner.
* @param teller Address of teller
* @param priority Priority of teller
*/
function addTeller(address teller, uint256 priority) external;
/**
* @dev External function to change the priority of teller. This function can be called by only owner.
* @param teller Address of teller
* @param newPriority New priority of teller
*/
function changePriority(address teller, uint256 newPriority) external;
/**
* @dev External function to pay the Vidya token to investors. This function can be called by only teller.
* @param provider Address of provider
* @param providerTimeWeight Weight time of provider
* @param totalWeight Sum of provider weight
*/
function payProvider(
address provider,
uint256 providerTimeWeight,
uint256 totalWeight
) external;
/**
* @dev External function to calculate the Vidya Rate.
*/
function calculateRateExternal() external;
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/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/token/ERC20/IERC20.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/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: github/Team3dVidyaGames/VidyaGenerator/contracts/Teller.sol
pragma solidity ^0.8.6;
/**
* @title Teller Contract
*/
contract Teller is Ownable, ReentrancyGuard {
using Address for address;
using SafeERC20 for IERC20;
/// @notice Event emitted on construction.
event TellerDeployed();
/// @notice Event emitted when teller status is toggled.
event TellerToggled(address teller, bool status);
/// @notice Event emitted when new commitment is added.
event NewCommitmentAdded(
uint256 bonus,
uint256 time,
uint256 penalty,
uint256 deciAdjustment
);
/// @notice Event emitted when commitment status is toggled.
event CommitmentToggled(uint256 index, bool status);
/// @notice Event emitted when owner sets the dev address to get the break commitment fees.
event PurposeSet(address devAddress, bool purposeStatus);
/// @notice Event emitted when a provider deposits lp tokens.
event LpDeposited(address indexed provider, uint256 indexed amount);
/// @notice Event emitted when a provider withdraws lp tokens.
event Withdrew(address indexed provider, uint256 indexed amount);
/// @notice Event emitted when a provider commits lp tokens.
event Commited(address indexed provider, uint256 indexed commitedAmount);
/// @notice Event emitted when a provider breaks the commitment.
event CommitmentBroke(address indexed provider, uint256 indexed tokenSentAmount);
/// @notice Event emitted when provider claimed rewards.
event Claimed(address indexed provider, bool indexed success);
struct Provider {
uint256 LPDepositedRatio;
uint256 userWeight;
uint256 lastClaimedTime;
uint256 commitmentIndex;
uint256 committedAmount;
uint256 commitmentEndTime;
}
struct Commitment {
uint256 bonus;
uint256 duration;
uint256 penalty;
uint256 deciAdjustment;
bool isActive;
}
IVault public Vault;
IERC20 public LpToken;
uint256 public totalLP;
uint256 public totalWeight;
uint256 public tellerClosedTime;
bool public tellerOpen;
bool public purpose;
address public devAddress;
Commitment[] public commitmentInfo;
mapping(address => Provider) public providerInfo;
modifier isTellerOpen() {
require(tellerOpen, "Teller: Teller is not open.");
_;
}
modifier isProvider() {
require(
providerInfo[msg.sender].LPDepositedRatio != 0,
"Teller: Caller is not a provider."
);
_;
}
modifier isTellerClosed() {
require(!tellerOpen, "Teller: Teller is still active.");
_;
}
/**
* @dev Constructor function
* @param _LpToken Interface of LP token
* @param _Vault Interface of Vault
*/
constructor(IERC20 _LpToken, IVault _Vault) {
LpToken = _LpToken;
Vault = _Vault;
commitmentInfo.push();
emit TellerDeployed();
}
/**
* @dev External function to toggle the teller. This function can be called only by the owner.
*/
function toggleTeller() external onlyOwner {
tellerOpen = !tellerOpen;
tellerClosedTime = block.timestamp;
emit TellerToggled(address(this), tellerOpen);
}
/**
* @dev External function to add a commitment option. This function can be called only by the owner.
* @param _bonus Amount of bonus
* @param _days Commitment duration in days
* @param _penalty The penalty
* @param _deciAdjustment Decimal percentage
*/
function addCommitment(
uint256 _bonus,
uint256 _days,
uint256 _penalty,
uint256 _deciAdjustment
) external onlyOwner {
Commitment memory holder;
holder.bonus = _bonus;
holder.duration = _days * 1 days;
holder.penalty = _penalty;
holder.deciAdjustment = _deciAdjustment;
holder.isActive = true;
commitmentInfo.push(holder);
emit NewCommitmentAdded(_bonus, _days, _penalty, _deciAdjustment);
}
/**
* @dev External function to toggle the commitment. This function can be called only by the owner.
* @param _index Commitment index
*/
function toggleCommitment(uint256 _index) external onlyOwner {
require(
0 < _index && _index < commitmentInfo.length,
"Teller: Current index is not listed in the commitment array."
);
commitmentInfo[_index].isActive = !commitmentInfo[_index].isActive;
emit CommitmentToggled(_index, commitmentInfo[_index].isActive);
}
/**
* @dev External function to set the dev address to give that address the break commitment fees. This function can be called only by the owner.
* @param _address Dev address
* @param _status If purpose is active or not
*/
function setPurpose(address _address, bool _status) external onlyOwner {
purpose = _status;
devAddress = _address;
emit PurposeSet(devAddress, purpose);
}
/**
* @dev External function for providers to deposit lp tokens. Teller must be open.
* @param _amount LP token amount
*/
function depositLP(uint256 _amount) external isTellerOpen {
uint256 contractBalance = LpToken.balanceOf(address(this));
LpToken.safeTransferFrom(msg.sender, address(this), _amount);
Provider storage user = providerInfo[msg.sender];
if (user.LPDepositedRatio != 0) {
commitmentFinished();
claim();
} else {
user.lastClaimedTime = block.timestamp;
}
if (contractBalance == totalLP || totalLP == 0) {
user.LPDepositedRatio += _amount;
totalLP += _amount;
} else {
uint256 _adjustedAmount = (_amount * totalLP) / contractBalance;
user.LPDepositedRatio += _adjustedAmount;
totalLP += _adjustedAmount;
}
user.userWeight += _amount;
totalWeight += _amount;
emit LpDeposited(msg.sender, _amount);
}
/**
* @dev External function to withdraw lp token from the teller. This function can be called only by a provider.
* @param _amount LP token amount
*/
function withdraw(uint256 _amount) external isProvider nonReentrant {
Provider storage user = providerInfo[msg.sender];
uint256 contractBalance = LpToken.balanceOf(address(this));
commitmentFinished();
uint256 userTokens = (user.LPDepositedRatio * contractBalance) /
totalLP;
require(
userTokens - user.committedAmount >= _amount,
"Teller: Provider hasn't got enough deposited LP tokens to withdraw."
);
claim();
uint256 _weightChange = (_amount * user.userWeight) / userTokens;
user.userWeight -= _weightChange;
totalWeight -= _weightChange;
uint256 ratioChange = _amount * totalLP/contractBalance;
user.LPDepositedRatio -= ratioChange;
totalLP -= ratioChange;
LpToken.safeTransfer(msg.sender, _amount);
emit Withdrew(msg.sender, _amount);
}
/**
* @dev External function to withdraw lp token when teller is closed. This function can be called only by a provider.
*/
function tellerClosedWithdraw() external isTellerClosed isProvider {
uint256 contractBalance = LpToken.balanceOf(address(this));
require(contractBalance != 0, "Teller: Contract balance is zero.");
claim();
Provider memory user = providerInfo[msg.sender];
uint256 userTokens = (user.LPDepositedRatio * contractBalance) /
totalLP;
totalLP -= user.LPDepositedRatio;
totalWeight -= user.userWeight;
providerInfo[msg.sender] = Provider(0, 0, 0, 0, 0, 0);
LpToken.safeTransfer(msg.sender, userTokens);
emit Withdrew(msg.sender, userTokens);
}
/**
* @dev External function to commit lp token to gain a minor advantage for a selected period of time. This function can be called only by a provider.
* @param _amount LP token amount
* @param _commitmentIndex Index of commitment array
*/
function commit(uint256 _amount, uint256 _commitmentIndex)
external
nonReentrant
isProvider
{
require(
commitmentInfo[_commitmentIndex].isActive,
"Teller: Current commitment is not active."
);
Provider storage user = providerInfo[msg.sender];
commitmentFinished();
uint256 contractBalance = LpToken.balanceOf(address(this));
uint256 userTokens = (user.LPDepositedRatio * contractBalance) /
totalLP;
require(
userTokens - user.committedAmount >= _amount,
"Teller: Provider hasn't got enough deposited LP tokens to commit."
);
if (user.committedAmount != 0) {
require(
_commitmentIndex == user.commitmentIndex,
"Teller: Commitment index is not the same as providers'."
);
}
uint256 newEndTime;
if (
user.commitmentEndTime >= block.timestamp &&
user.committedAmount != 0
) {
newEndTime = calculateNewEndTime(
user.committedAmount,
_amount,
user.commitmentEndTime,
_commitmentIndex
);
} else {
newEndTime =
block.timestamp +
commitmentInfo[_commitmentIndex].duration;
}
uint256 weightToGain = (_amount * user.userWeight) / userTokens;
uint256 bonusCredit = commitBonus(_commitmentIndex, weightToGain);
claim();
user.commitmentIndex = _commitmentIndex;
user.committedAmount += _amount;
user.commitmentEndTime = newEndTime;
user.userWeight += bonusCredit;
totalWeight += bonusCredit;
emit Commited(msg.sender, _amount);
}
/**
* @dev External function to break the commitment. This function can be called only by a provider.
*/
function breakCommitment() external nonReentrant isProvider {
Provider memory user = providerInfo[msg.sender];
require(
user.commitmentEndTime > block.timestamp,
"Teller: No commitment to break."
);
uint256 contractBalance = LpToken.balanceOf(address(this));
uint256 tokenToReceive = (user.LPDepositedRatio * contractBalance) /
totalLP;
Commitment memory currentCommit = commitmentInfo[user.commitmentIndex];
//fee for breaking the commitment
uint256 fee = (user.committedAmount * currentCommit.penalty) /
currentCommit.deciAdjustment;
//fee reduced from provider and left in teller
tokenToReceive -= fee;
totalLP -= user.LPDepositedRatio;
totalWeight -= user.userWeight;
providerInfo[msg.sender] = Provider(0, 0, 0, 0, 0, 0);
//if a devloper purpose is set then transfer to address
if (purpose) {
LpToken.safeTransfer(devAddress, fee / 10);
}
//Fee is not lost it is dispersed to remaining providers.
LpToken.safeTransfer(msg.sender, tokenToReceive);
emit CommitmentBroke(msg.sender, tokenToReceive);
}
/**
* @dev Internal function to claim rewards.
*/
function claim() internal {
Provider storage user = providerInfo[msg.sender];
uint256 timeGap = block.timestamp - user.lastClaimedTime;
if (!tellerOpen) {
timeGap = tellerClosedTime - user.lastClaimedTime;
}
if (timeGap > 365 * 1 days) {
timeGap = 365 * 1 days;
}
uint256 timeWeight = timeGap * user.userWeight;
user.lastClaimedTime = block.timestamp;
Vault.payProvider(msg.sender, timeWeight, totalWeight);
emit Claimed(msg.sender, true);
}
/**
* @dev Internal function to return commit bonus.
* @param _commitmentIndex Index of commitment array
* @param _amount Commitment token amount
*/
function commitBonus(uint256 _commitmentIndex, uint256 _amount)
internal
view
returns (uint256)
{
if (commitmentInfo[_commitmentIndex].isActive) {
return
(commitmentInfo[_commitmentIndex].bonus * _amount) /
commitmentInfo[_commitmentIndex].deciAdjustment;
}
return 0;
}
/**
* @dev Internal function to calculate the new ending time when the current end time is overflown.
* @param _oldAmount Commitment lp token amount which provider has
* @param _extraAmount Lp token amount which user wants to commit
* @param _oldEndTime Previous commitment ending time
* @param _commitmentIndex Index of commitment array
*/
function calculateNewEndTime(
uint256 _oldAmount,
uint256 _extraAmount,
uint256 _oldEndTime,
uint256 _commitmentIndex
) internal view returns (uint256) {
uint256 extraEndTIme = commitmentInfo[_commitmentIndex].duration +
block.timestamp;
uint256 newEndTime = ((_oldAmount * _oldEndTime) +
(_extraAmount * extraEndTIme)) / (_oldAmount + _extraAmount);
return newEndTime;
}
/**
* @dev Internal function to finish a commitment when it has ended.
*/
function commitmentFinished() internal {
Provider storage user = providerInfo[msg.sender];
if (user.commitmentEndTime <= block.timestamp) {
user.committedAmount = 0;
user.commitmentIndex = 0;
}
}
/**
* @dev External function to claim the reward token. This function can be called only by a provider and teller must be open.
*/
function claimExternal() external isTellerOpen isProvider nonReentrant {
commitmentFinished();
claim();
}
/**
* @dev External function to get User info. This function can be called from a msg.sender with active deposits.
* @return Time of rest committed time
* @return Committed amount
* @return Committed Index
* @return Amount to Claim
* @return Total LP deposited
*/
function getUserInfo(address _user)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
Provider memory user = providerInfo[_user];
if (user.LPDepositedRatio > 0) {
uint256 claimAmount = (Vault.rewardRate() *
Vault.tellerPriority(address(this)) *
(block.timestamp - user.lastClaimedTime) *
user.userWeight) / (totalWeight * Vault.totalPriority());
uint256 totalLPDeposited = (providerInfo[_user]
.LPDepositedRatio * LpToken.balanceOf(address(this))) / totalLP;
if (user.commitmentEndTime > block.timestamp) {
return (
user.commitmentEndTime - block.timestamp,
user.committedAmount,
user.commitmentIndex,
claimAmount,
totalLPDeposited
);
} else {
return (0, 0, 0, claimAmount, totalLPDeposited);
}
} else {
return (0, 0, 0, 0, 0);
}
}
}
|
Internal function to finish a commitment when it has ended./
|
function commitmentFinished() internal {
Provider storage user = providerInfo[msg.sender];
if (user.commitmentEndTime <= block.timestamp) {
user.committedAmount = 0;
user.commitmentIndex = 0;
}
}
| 618,701
|
/**
* Copyright 2017-2019, bZeroX, LLC. All Rights Reserved.
* Licensed under the Apache License, Version 2.0.
*/
pragma solidity 0.5.8;
pragma experimental ABIEncoderV2;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* See https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address _who) public view returns (uint256);
function transfer(address _to, uint256 _value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address _owner, address _spender)
public view returns (uint256);
function transferFrom(address _from, address _to, uint256 _value)
public returns (bool);
function approve(address _spender, uint256 _value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title EIP20/ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract EIP20 is ERC20 {
string public name;
uint8 public decimals;
string public symbol;
}
contract WETHInterface is EIP20 {
function deposit() external payable;
function withdraw(uint256 wad) external;
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
c = _a * _b;
assert(c / _a == _b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
// assert(_b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return _a / _b;
}
/**
* @dev Integer division of two numbers, rounding up and truncating the quotient
*/
function divCeil(uint256 _a, uint256 _b) internal pure returns (uint256) {
if (_a == 0) {
return 0;
}
return ((_a - 1) / _b) + 1;
}
/**
* @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.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Helps contracts guard against reentrancy attacks.
* @author Remco Bloemen <remco@2π.com>, Eenae <alexey@mixbytes.io>
* @dev If you mark a function `nonReentrant`, you should also
* mark it `external`.
*/
contract ReentrancyGuard {
/// @dev Constant for unlocked guard state - non-zero to prevent extra gas costs.
/// See: https://github.com/OpenZeppelin/openzeppelin-solidity/issues/1056
uint256 internal constant REENTRANCY_GUARD_FREE = 1;
/// @dev Constant for locked guard state
uint256 internal constant REENTRANCY_GUARD_LOCKED = 2;
/**
* @dev We use a single lock for the whole contract.
*/
uint256 internal reentrancyLock = REENTRANCY_GUARD_FREE;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one `nonReentrant` function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and an `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(reentrancyLock == REENTRANCY_GUARD_FREE, "nonReentrant");
reentrancyLock = REENTRANCY_GUARD_LOCKED;
_;
reentrancyLock = REENTRANCY_GUARD_FREE;
}
}
contract LoanTokenization is ReentrancyGuard, Ownable {
uint256 internal constant MAX_UINT = 2**256 - 1;
string public name;
string public symbol;
uint8 public decimals;
address public bZxContract;
address public bZxVault;
address public bZxOracle;
address public wethContract;
address public loanTokenAddress;
// price of token at last user checkpoint
mapping (address => uint256) internal checkpointPrices_;
}
contract LoanTokenStorage is LoanTokenization {
struct ListIndex {
uint256 index;
bool isSet;
}
struct LoanData {
bytes32 loanOrderHash;
uint256 leverageAmount;
uint256 initialMarginAmount;
uint256 maintenanceMarginAmount;
uint256 maxDurationUnixTimestampSec;
uint256 index;
}
struct TokenReserves {
address lender;
uint256 amount;
}
event Borrow(
address indexed borrower,
uint256 borrowAmount,
uint256 interestRate,
address collateralTokenAddress,
address tradeTokenToFillAddress,
bool withdrawOnOpen
);
event Claim(
address indexed claimant,
uint256 tokenAmount,
uint256 assetAmount,
uint256 remainingTokenAmount,
uint256 price
);
bool internal isInitialized_ = false;
address public tokenizedRegistry;
uint256 public baseRate = 1000000000000000000; // 1.0%
uint256 public rateMultiplier = 39000000000000000000; // 39%
// "fee percentage retained by the oracle" = SafeMath.sub(10**20, spreadMultiplier);
uint256 public spreadMultiplier;
mapping (uint256 => bytes32) public loanOrderHashes; // mapping of levergeAmount to loanOrderHash
mapping (bytes32 => LoanData) public loanOrderData; // mapping of loanOrderHash to LoanOrder
uint256[] public leverageList;
TokenReserves[] public burntTokenReserveList; // array of TokenReserves
mapping (address => ListIndex) public burntTokenReserveListIndex; // mapping of lender address to ListIndex objects
uint256 public burntTokenReserved; // total outstanding burnt token amount
address internal nextOwedLender_;
uint256 public totalAssetBorrow = 0; // current amount of loan token amount tied up in loans
uint256 internal checkpointSupply_;
uint256 internal lastSettleTime_;
uint256 public initialPrice;
}
contract AdvancedTokenStorage is LoanTokenStorage {
using SafeMath for uint256;
event Transfer(
address indexed from,
address indexed to,
uint256 value
);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Mint(
address indexed minter,
uint256 tokenAmount,
uint256 assetAmount,
uint256 price
);
event Burn(
address indexed burner,
uint256 tokenAmount,
uint256 assetAmount,
uint256 price
);
mapping(address => uint256) internal balances;
mapping (address => mapping (address => uint256)) internal allowed;
uint256 internal totalSupply_;
function totalSupply()
public
view
returns (uint256)
{
return totalSupply_;
}
function balanceOf(
address _owner)
public
view
returns (uint256)
{
return balances[_owner];
}
function allowance(
address _owner,
address _spender)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
}
contract AdvancedToken is AdvancedTokenStorage {
using SafeMath for uint256;
function approve(
address _spender,
uint256 _value)
public
returns (bool)
{
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function increaseApproval(
address _spender,
uint256 _addedValue)
public
returns (bool)
{
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(
address _spender,
uint256 _subtractedValue)
public
returns (bool)
{
uint256 oldValue = allowed[msg.sender][_spender];
if (_subtractedValue >= oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function _mint(
address _to,
uint256 _tokenAmount,
uint256 _assetAmount,
uint256 _price)
internal
{
require(_to != address(0), "invalid address");
totalSupply_ = totalSupply_.add(_tokenAmount);
balances[_to] = balances[_to].add(_tokenAmount);
emit Mint(_to, _tokenAmount, _assetAmount, _price);
emit Transfer(address(0), _to, _tokenAmount);
}
function _burn(
address _who,
uint256 _tokenAmount,
uint256 _assetAmount,
uint256 _price)
internal
{
require(_tokenAmount <= balances[_who], "burn value exceeds balance");
// 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(_tokenAmount);
if (balances[_who] <= 10) { // we can't leave such small balance quantities
_tokenAmount = _tokenAmount.add(balances[_who]);
balances[_who] = 0;
}
totalSupply_ = totalSupply_.sub(_tokenAmount);
emit Burn(_who, _tokenAmount, _assetAmount, _price);
emit Transfer(_who, address(0), _tokenAmount);
}
}
contract BZxObjects {
struct LoanOrder {
address loanTokenAddress;
address interestTokenAddress;
address collateralTokenAddress;
address oracleAddress;
uint256 loanTokenAmount;
uint256 interestAmount;
uint256 initialMarginAmount;
uint256 maintenanceMarginAmount;
uint256 maxDurationUnixTimestampSec;
bytes32 loanOrderHash;
}
struct LoanPosition {
address trader;
address collateralTokenAddressFilled;
address positionTokenAddressFilled;
uint256 loanTokenAmountFilled;
uint256 loanTokenAmountUsed;
uint256 collateralTokenAmountFilled;
uint256 positionTokenAmountFilled;
uint256 loanStartUnixTimestampSec;
uint256 loanEndUnixTimestampSec;
bool active;
uint256 positionId;
}
}
contract OracleNotifierInterface {
function closeLoanNotifier(
BZxObjects.LoanOrder memory loanOrder,
BZxObjects.LoanPosition memory loanPosition,
address loanCloser,
uint256 closeAmount,
bool isLiquidation)
public
returns (bool);
}
interface IBZx {
function pushLoanOrderOnChain(
address[8] calldata orderAddresses,
uint256[11] calldata orderValues,
bytes calldata oracleData,
bytes calldata signature)
external
returns (bytes32); // loanOrderHash
function setLoanOrderDesc(
bytes32 loanOrderHash,
string calldata desc)
external
returns (bool);
function updateLoanAsLender(
bytes32 loanOrderHash,
uint256 increaseAmountForLoan,
uint256 newInterestRate,
uint256 newExpirationTimestamp)
external
returns (bool);
function takeLoanOrderOnChainAsTraderByDelegate(
address trader,
bytes32 loanOrderHash,
address collateralTokenFilled,
uint256 loanTokenAmountFilled,
address tradeTokenToFillAddress,
bool withdrawOnOpen)
external
returns (uint256);
function getLenderInterestForOracle(
address lender,
address oracleAddress,
address interestTokenAddress)
external
view
returns (
uint256, // interestPaid
uint256, // interestPaidDate
uint256, // interestOwedPerDay
uint256); // interestUnPaid
function oracleAddresses(
address oracleAddress)
external
view
returns (address);
}
interface IBZxOracle {
function tradeUserAsset(
address sourceTokenAddress,
address destTokenAddress,
address receiverAddress,
address returnToSenderAddress,
uint256 sourceTokenAmount,
uint256 maxDestTokenAmount,
uint256 minConversionRate)
external
returns (uint256 destTokenAmountReceived, uint256 sourceTokenAmountUsed);
function interestFeePercent()
external
view
returns (uint256);
}
interface iTokenizedRegistry {
function getTokenAsset(
address _token,
uint256 _tokenType)
external
view
returns (address);
}
contract LoanTokenLogic is AdvancedToken, OracleNotifierInterface {
using SafeMath for uint256;
modifier onlyOracle() {
require(msg.sender == IBZx(bZxContract).oracleAddresses(bZxOracle), "unauthorized");
_;
}
function()
external
payable
{}
/* Public functions */
function mintWithEther(
address receiver)
external
payable
nonReentrant
returns (uint256 mintAmount)
{
require(loanTokenAddress == wethContract, "no ether");
return _mintToken(
receiver,
msg.value
);
}
function mint(
address receiver,
uint256 depositAmount)
external
nonReentrant
returns (uint256 mintAmount)
{
return _mintToken(
receiver,
depositAmount
);
}
function burnToEther(
address payable receiver,
uint256 burnAmount)
external
nonReentrant
returns (uint256 loanAmountPaid)
{
require(loanTokenAddress == wethContract, "no ether");
loanAmountPaid = _burnToken(
receiver,
burnAmount
);
if (loanAmountPaid > 0) {
WETHInterface(wethContract).withdraw(loanAmountPaid);
require(receiver.send(loanAmountPaid), "transfer failed");
}
}
function burn(
address receiver,
uint256 burnAmount)
external
nonReentrant
returns (uint256 loanAmountPaid)
{
loanAmountPaid = _burnToken(
receiver,
burnAmount
);
if (loanAmountPaid > 0) {
require(ERC20(loanTokenAddress).transfer(
receiver,
loanAmountPaid
), "transfer failed");
}
}
// called by a borrower to open a loan
// loan can be collateralized using any supported token (collateralTokenAddress)
// interest collected is denominated the same as loanToken
// returns borrowAmount
function borrowToken(
uint256 borrowAmount,
uint256 leverageAmount,
address collateralTokenAddress,
address tradeTokenToFillAddress,
bool withdrawOnOpen)
external
nonReentrant
returns (uint256)
{
uint256 amount = _borrowToken(
msg.sender,
borrowAmount,
leverageAmount,
collateralTokenAddress,
tradeTokenToFillAddress,
withdrawOnOpen,
false // calcBorrow
);
require(amount > 0, "can't borrow");
return amount;
}
// called by a borrower to open a loan
// escrowAmount == total collateral + interest available to back the loan
// escrowAmount is denominated the same as loanToken
// returns borrowAmount
function borrowTokenFromEscrow(
uint256 escrowAmount,
uint256 leverageAmount,
address tradeTokenToFillAddress,
bool withdrawOnOpen)
external
nonReentrant
returns (uint256)
{
uint256 amount = _borrowToken(
msg.sender,
escrowAmount,
leverageAmount,
loanTokenAddress, // collateralTokenAddress
tradeTokenToFillAddress,
withdrawOnOpen,
true // calcBorrow
);
require(amount > 0, "can't borrow");
return amount;
}
function rolloverPosition(
address borrower,
uint256 leverageAmount,
uint256 escrowAmount,
address tradeTokenToFillAddress)
external
returns (uint256)
{
require(msg.sender == address(this), "unauthorized");
return _borrowToken(
borrower,
escrowAmount,
leverageAmount,
loanTokenAddress, // collateralTokenAddress
tradeTokenToFillAddress,
false, // withdrawOnOpen
true // calcBorrow
);
}
// Claims owned loan token for the caller
// Also claims for user with the longest reserves
// returns amount claimed for the caller
function claimLoanToken()
external
nonReentrant
returns (uint256 claimedAmount)
{
claimedAmount = _claimLoanToken(msg.sender);
if (burntTokenReserveList.length > 0) {
_claimLoanToken(_getNextOwed());
if (burntTokenReserveListIndex[msg.sender].isSet && nextOwedLender_ != msg.sender) {
// ensure lender is paid next
nextOwedLender_ = msg.sender;
}
}
}
function settleInterest()
external
nonReentrant
{
_settleInterest();
}
function wrapEther()
public
{
if (address(this).balance > 0) {
WETHInterface(wethContract).deposit.value(address(this).balance)();
}
}
// Sends non-LoanToken assets to the Oracle fund
// These are assets that would otherwise be "stuck" due to a user accidently sending them to the contract
function donateAsset(
address tokenAddress)
public
returns (bool)
{
if (tokenAddress == loanTokenAddress)
return false;
uint256 balance = ERC20(tokenAddress).balanceOf(address(this));
if (balance == 0)
return false;
require(ERC20(tokenAddress).transfer(
IBZx(bZxContract).oracleAddresses(bZxOracle),
balance
), "transfer failed");
return true;
}
function transfer(
address _to,
uint256 _value)
public
returns (bool)
{
require(_value <= balances[msg.sender], "insufficient balance");
require(_to != address(0), "token burn not allowed");
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
// handle checkpoint update
uint256 currentPrice = tokenPrice();
if (burntTokenReserveListIndex[msg.sender].isSet || balances[msg.sender] > 0) {
checkpointPrices_[msg.sender] = currentPrice;
} else {
checkpointPrices_[msg.sender] = 0;
}
if (burntTokenReserveListIndex[_to].isSet || balances[_to] > 0) {
checkpointPrices_[_to] = currentPrice;
} else {
checkpointPrices_[_to] = 0;
}
emit Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(
address _from,
address _to,
uint256 _value)
public
returns (bool)
{
uint256 allowanceAmount = allowed[_from][msg.sender];
require(_value <= balances[_from], "insufficient balance");
require(_value <= allowanceAmount, "insufficient allowance");
require(_to != address(0), "token burn not allowed");
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
if (allowanceAmount < MAX_UINT) {
allowed[_from][msg.sender] = allowanceAmount.sub(_value);
}
// handle checkpoint update
uint256 currentPrice = tokenPrice();
if (burntTokenReserveListIndex[_from].isSet || balances[_from] > 0) {
checkpointPrices_[_from] = currentPrice;
} else {
checkpointPrices_[_from] = 0;
}
if (burntTokenReserveListIndex[_to].isSet || balances[_to] > 0) {
checkpointPrices_[_to] = currentPrice;
} else {
checkpointPrices_[_to] = 0;
}
emit Transfer(_from, _to, _value);
return true;
}
/* Public View functions */
function tokenPrice()
public
view
returns (uint256 price)
{
uint256 interestUnPaid = 0;
if (lastSettleTime_ != block.timestamp) {
(,,interestUnPaid) = _getAllInterest();
interestUnPaid = interestUnPaid
.mul(spreadMultiplier)
.div(10**20);
}
return _tokenPrice(_totalAssetSupply(interestUnPaid));
}
function checkpointPrice(
address _user)
public
view
returns (uint256 price)
{
return checkpointPrices_[_user];
}
function totalReservedSupply()
public
view
returns (uint256)
{
return burntTokenReserved.mul(tokenPrice()).div(10**18);
}
function marketLiquidity()
public
view
returns (uint256)
{
uint256 totalSupply = totalAssetSupply();
uint256 reservedSupply = totalReservedSupply();
if (totalSupply > reservedSupply) {
totalSupply = totalSupply.sub(reservedSupply);
} else {
return 0;
}
if (totalSupply > totalAssetBorrow) {
return totalSupply.sub(totalAssetBorrow);
} else {
return 0;
}
}
// interest that borrowers are currently paying for open loans, prior to any fees
function borrowInterestRate()
public
view
returns (uint256)
{
if (totalAssetBorrow > 0) {
return _protocolInterestRate(totalAssetSupply());
} else {
return baseRate;
}
}
// interest that lenders are currently receiving for open loans, prior to any fees
function supplyInterestRate()
public
view
returns (uint256)
{
uint256 assetSupply = totalAssetSupply();
if (totalAssetBorrow > 0) {
return _protocolInterestRate(assetSupply)
.mul(_getUtilizationRate(assetSupply))
.div(10**40);
} else {
return 0;
}
}
// the rate the next base protocol borrower will receive based on the amount being borrowed
function nextLoanInterestRate(
uint256 borrowAmount)
public
view
returns (uint256)
{
if (borrowAmount > 0) {
uint256 interestUnPaid = 0;
if (lastSettleTime_ != block.timestamp) {
(,,interestUnPaid) = _getAllInterest();
interestUnPaid = interestUnPaid
.mul(spreadMultiplier)
.div(10**20);
}
uint256 balance = ERC20(loanTokenAddress).balanceOf(address(this)).add(interestUnPaid);
if (borrowAmount > balance) {
borrowAmount = balance;
}
}
return _nextLoanInterestRate(borrowAmount);
}
// returns the total amount of interest earned for all active loans
function interestReceived()
public
view
returns (uint256 interestTotalAccrued)
{
(uint256 interestPaidSoFar,,uint256 interestUnPaid) = _getAllInterest();
return interestPaidSoFar
.add(interestUnPaid)
.mul(spreadMultiplier)
.div(10**20);
}
function totalAssetSupply()
public
view
returns (uint256)
{
uint256 interestUnPaid = 0;
if (lastSettleTime_ != block.timestamp) {
(,,interestUnPaid) = _getAllInterest();
interestUnPaid = interestUnPaid
.mul(spreadMultiplier)
.div(10**20);
}
return _totalAssetSupply(interestUnPaid);
}
function getMaxEscrowAmount(
uint256 leverageAmount)
public
view
returns (uint256)
{
LoanData memory loanData = loanOrderData[loanOrderHashes[leverageAmount]];
if (loanData.initialMarginAmount == 0)
return 0;
return marketLiquidity()
.mul(loanData.initialMarginAmount)
.div(_adjustValue(
10**20, // maximum possible interest (100%)
loanData.maxDurationUnixTimestampSec,
loanData.initialMarginAmount));
}
function getBorrowAmount(
uint256 escrowAmount,
uint256 leverageAmount,
bool withdrawOnOpen)
public
view
returns (uint256)
{
if (escrowAmount == 0)
return 0;
LoanData memory loanData = loanOrderData[loanOrderHashes[leverageAmount]];
if (loanData.initialMarginAmount == 0)
return 0;
return _getBorrowAmount(
loanData.initialMarginAmount,
escrowAmount,
nextLoanInterestRate(
escrowAmount
.mul(10**20)
.div(loanData.initialMarginAmount)
),
loanData.maxDurationUnixTimestampSec,
withdrawOnOpen
);
}
function getLoanData(
uint256 levergeAmount)
public
view
returns (LoanData memory)
{
return loanOrderData[loanOrderHashes[levergeAmount]];
}
function getLeverageList()
public
view
returns (uint256[] memory)
{
return leverageList;
}
// returns the user's balance of underlying token
function assetBalanceOf(
address _owner)
public
view
returns (uint256)
{
return balanceOf(_owner)
.mul(tokenPrice())
.div(10**18);
}
/* Internal functions */
function _mintToken(
address receiver,
uint256 depositAmount)
internal
returns (uint256 mintAmount)
{
require (depositAmount > 0, "amount == 0");
if (burntTokenReserveList.length > 0) {
_claimLoanToken(_getNextOwed());
_claimLoanToken(receiver);
if (msg.sender != receiver)
_claimLoanToken(msg.sender);
} else {
_settleInterest();
}
uint256 currentPrice = _tokenPrice(_totalAssetSupply(0));
mintAmount = depositAmount.mul(10**18).div(currentPrice);
if (msg.value == 0) {
require(ERC20(loanTokenAddress).transferFrom(
msg.sender,
address(this),
depositAmount
), "transfer failed");
} else {
WETHInterface(wethContract).deposit.value(depositAmount)();
}
_mint(receiver, mintAmount, depositAmount, currentPrice);
checkpointPrices_[receiver] = currentPrice;
}
function _burnToken(
address receiver,
uint256 burnAmount)
internal
returns (uint256 loanAmountPaid)
{
require(burnAmount > 0, "amount == 0");
if (burnAmount > balanceOf(msg.sender)) {
burnAmount = balanceOf(msg.sender);
}
if (burntTokenReserveList.length > 0) {
_claimLoanToken(_getNextOwed());
_claimLoanToken(receiver);
if (msg.sender != receiver)
_claimLoanToken(msg.sender);
} else {
_settleInterest();
}
uint256 currentPrice = _tokenPrice(_totalAssetSupply(0));
uint256 loanAmountOwed = burnAmount.mul(currentPrice).div(10**18);
uint256 loanAmountAvailableInContract = ERC20(loanTokenAddress).balanceOf(address(this));
loanAmountPaid = loanAmountOwed;
if (loanAmountPaid > loanAmountAvailableInContract) {
uint256 reserveAmount = loanAmountPaid.sub(loanAmountAvailableInContract);
uint256 reserveTokenAmount = reserveAmount.mul(10**18).div(currentPrice);
burntTokenReserved = burntTokenReserved.add(reserveTokenAmount);
if (burntTokenReserveListIndex[receiver].isSet) {
uint256 index = burntTokenReserveListIndex[receiver].index;
burntTokenReserveList[index].amount = burntTokenReserveList[index].amount.add(reserveTokenAmount);
} else {
burntTokenReserveList.push(TokenReserves({
lender: receiver,
amount: reserveTokenAmount
}));
burntTokenReserveListIndex[receiver] = ListIndex({
index: burntTokenReserveList.length-1,
isSet: true
});
}
loanAmountPaid = loanAmountAvailableInContract;
}
_burn(msg.sender, burnAmount, loanAmountPaid, currentPrice);
if (burntTokenReserveListIndex[msg.sender].isSet || balances[msg.sender] > 0) {
checkpointPrices_[msg.sender] = currentPrice;
} else {
checkpointPrices_[msg.sender] = 0;
}
}
function _settleInterest()
internal
{
if (lastSettleTime_ != block.timestamp) {
(bool success,) = bZxContract.call.gas(gasleft())(
abi.encodeWithSignature(
"payInterestForOracle(address,address)",
bZxOracle, // (leave as original value)
loanTokenAddress // same as interestTokenAddress
)
);
success;
lastSettleTime_ = block.timestamp;
}
}
function _getNextOwed()
internal
view
returns (address)
{
if (nextOwedLender_ != address(0))
return nextOwedLender_;
else if (burntTokenReserveList.length > 0)
return burntTokenReserveList[0].lender;
else
return address(0);
}
function _claimLoanToken(
address lender)
internal
returns (uint256)
{
_settleInterest();
if (!burntTokenReserveListIndex[lender].isSet)
return 0;
uint256 index = burntTokenReserveListIndex[lender].index;
uint256 currentPrice = _tokenPrice(_totalAssetSupply(0));
uint256 claimAmount = burntTokenReserveList[index].amount.mul(currentPrice).div(10**18);
if (claimAmount == 0)
return 0;
uint256 availableAmount = ERC20(loanTokenAddress).balanceOf(address(this));
if (availableAmount == 0) {
return 0;
}
uint256 claimTokenAmount;
if (claimAmount <= availableAmount) {
claimTokenAmount = burntTokenReserveList[index].amount;
_removeFromList(lender, index);
} else {
claimAmount = availableAmount;
claimTokenAmount = claimAmount.mul(10**18).div(currentPrice);
// prevents less than 10 being left in burntTokenReserveList[index].amount
if (claimTokenAmount.add(10) < burntTokenReserveList[index].amount) {
burntTokenReserveList[index].amount = burntTokenReserveList[index].amount.sub(claimTokenAmount);
} else {
_removeFromList(lender, index);
}
}
require(ERC20(loanTokenAddress).transfer(
lender,
claimAmount
), "transfer failed");
if (burntTokenReserveListIndex[lender].isSet || balances[lender] > 0) {
checkpointPrices_[lender] = currentPrice;
} else {
checkpointPrices_[lender] = 0;
}
burntTokenReserved = burntTokenReserved > claimTokenAmount ?
burntTokenReserved.sub(claimTokenAmount) :
0;
emit Claim(
lender,
claimTokenAmount,
claimAmount,
burntTokenReserveListIndex[lender].isSet ?
burntTokenReserveList[burntTokenReserveListIndex[lender].index].amount :
0,
currentPrice
);
return claimAmount;
}
function _borrowToken(
address msgsender,
uint256 borrowAmount,
uint256 leverageAmount,
address collateralTokenAddress,
address tradeTokenToFillAddress,
bool withdrawOnOpen,
bool calcBorrow)
internal
returns (uint256)
{
if (borrowAmount == 0) {
return 0;
}
bytes32 loanOrderHash = loanOrderHashes[leverageAmount];
LoanData memory loanData = loanOrderData[loanOrderHash];
require(loanData.initialMarginAmount != 0, "invalid leverage");
_settleInterest();
uint256 interestRate;
if (calcBorrow) {
interestRate = _nextLoanInterestRate(
borrowAmount // escrowAmount
.mul(10**20)
.div(loanData.initialMarginAmount)
);
borrowAmount = _getBorrowAmount(
loanData.initialMarginAmount,
borrowAmount, // escrowAmount,
interestRate,
loanData.maxDurationUnixTimestampSec,
withdrawOnOpen
);
} else {
interestRate = _nextLoanInterestRate(borrowAmount);
}
return _borrowTokenFinal(
msgsender,
loanOrderHash,
borrowAmount,
interestRate,
collateralTokenAddress,
tradeTokenToFillAddress,
withdrawOnOpen
);
}
// returns borrowAmount
function _borrowTokenFinal(
address msgsender,
bytes32 loanOrderHash,
uint256 borrowAmount,
uint256 interestRate,
address collateralTokenAddress,
address tradeTokenToFillAddress,
bool withdrawOnOpen)
internal
returns (uint256)
{
//require(ERC20(loanTokenAddress).balanceOf(address(this)) >= borrowAmount, "insufficient loan supply");
uint256 availableToBorrow = ERC20(loanTokenAddress).balanceOf(address(this));
if (availableToBorrow == 0)
return 0;
uint256 reservedSupply = totalReservedSupply();
if (availableToBorrow > reservedSupply) {
availableToBorrow = availableToBorrow.sub(reservedSupply);
} else {
return 0;
}
if (borrowAmount > availableToBorrow) {
borrowAmount = availableToBorrow;
}
// re-up the BZxVault spend approval if needed
uint256 tempAllowance = ERC20(loanTokenAddress).allowance(address(this), bZxVault);
if (tempAllowance < borrowAmount) {
if (tempAllowance > 0) {
// reset approval to 0
require(ERC20(loanTokenAddress).approve(bZxVault, 0), "approval failed");
}
require(ERC20(loanTokenAddress).approve(bZxVault, MAX_UINT), "approval failed");
}
require(IBZx(bZxContract).updateLoanAsLender(
loanOrderHash,
borrowAmount,
interestRate.div(365),
block.timestamp+1),
"updateLoan failed"
);
require (IBZx(bZxContract).takeLoanOrderOnChainAsTraderByDelegate(
msgsender,
loanOrderHash,
collateralTokenAddress,
borrowAmount,
tradeTokenToFillAddress,
withdrawOnOpen) == borrowAmount,
"takeLoan failed"
);
// update total borrowed amount outstanding in loans
totalAssetBorrow = totalAssetBorrow.add(borrowAmount);
// checkpoint supply since the base protocol borrow stats have changed
checkpointSupply_ = _totalAssetSupply(0);
if (burntTokenReserveList.length > 0) {
_claimLoanToken(_getNextOwed());
_claimLoanToken(msgsender);
}
emit Borrow(
msgsender,
borrowAmount,
interestRate,
collateralTokenAddress,
tradeTokenToFillAddress,
withdrawOnOpen
);
return borrowAmount;
}
function _removeFromList(
address lender,
uint256 index)
internal
{
// remove lender from burntToken list
if (burntTokenReserveList.length > 1) {
// replace item in list with last item in array
burntTokenReserveList[index] = burntTokenReserveList[burntTokenReserveList.length - 1];
// update the position of this replacement
burntTokenReserveListIndex[burntTokenReserveList[index].lender].index = index;
}
// trim array and clear storage
burntTokenReserveList.length--;
burntTokenReserveListIndex[lender].index = 0;
burntTokenReserveListIndex[lender].isSet = false;
if (lender == nextOwedLender_) {
nextOwedLender_ = address(0);
}
}
/* Internal View functions */
function _tokenPrice(
uint256 assetSupply)
internal
view
returns (uint256)
{
uint256 totalTokenSupply = totalSupply_.add(burntTokenReserved);
return totalTokenSupply > 0 ?
assetSupply
.mul(10**18)
.div(totalTokenSupply) : initialPrice;
}
function _protocolInterestRate(
uint256 assetSupply)
internal
view
returns (uint256)
{
uint256 interestRate;
if (totalAssetBorrow > 0) {
(,uint256 interestOwedPerDay,) = _getAllInterest();
interestRate = interestOwedPerDay
.mul(10**20)
.div(totalAssetBorrow)
.mul(365)
.mul(checkpointSupply_)
.div(assetSupply);
} else {
interestRate = baseRate;
}
return interestRate;
}
// next loan interest adjustment
function _nextLoanInterestRate(
uint256 newBorrowAmount)
internal
view
returns (uint256 nextRate)
{
uint256 assetSupply = totalAssetSupply();
uint256 utilizationRate = _getUtilizationRate(assetSupply)
.add(newBorrowAmount > 0 ?
newBorrowAmount
.mul(10**20)
.div(assetSupply) : 0);
uint256 minRate = baseRate;
uint256 maxRate = rateMultiplier.add(baseRate);
if (utilizationRate > 90 ether) {
// scale rate proportionally up to 100%
utilizationRate = utilizationRate.sub(90 ether);
if (utilizationRate > 10 ether)
utilizationRate = 10 ether;
maxRate = maxRate
.mul(90)
.div(100);
nextRate = utilizationRate
.mul(SafeMath.sub(100 ether, maxRate))
.div(10 ether)
.add(maxRate);
} else {
nextRate = utilizationRate
.mul(rateMultiplier)
.div(10**20)
.add(baseRate);
if (nextRate < minRate)
nextRate = minRate;
else if (nextRate > maxRate)
nextRate = maxRate;
}
return nextRate;
}
function _getAllInterest()
internal
view
returns (
uint256 interestPaidSoFar,
uint256 interestOwedPerDay,
uint256 interestUnPaid)
{
// these values don't account for any fees retained by the oracle, so we account for it elsewhere with spreadMultiplier
(interestPaidSoFar,,interestOwedPerDay,interestUnPaid) = IBZx(bZxContract).getLenderInterestForOracle(
address(this),
bZxOracle, // (leave as original value)
loanTokenAddress // same as interestTokenAddress
);
}
function _getBorrowAmount(
uint256 marginAmount,
uint256 escrowAmount,
uint256 interestRate,
uint256 maxDuration,
bool withdrawOnOpen)
internal
pure
returns (uint256)
{
if (withdrawOnOpen) {
// adjust for over-collateralized loan (initial margin + 100% margin)
marginAmount = marginAmount.add(10**20);
}
// assumes that loan, collateral, and interest token are the same
return escrowAmount
.mul(10**40)
.div(_adjustValue(
interestRate,
maxDuration,
marginAmount))
.div(marginAmount);
}
function _adjustValue(
uint256 interestRate,
uint256 maxDuration,
uint256 marginAmount)
internal
pure
returns (uint256)
{
return maxDuration > 0 ?
interestRate
.mul(10**20)
.div(31536000) // 86400 * 365
.mul(maxDuration)
.div(marginAmount)
.add(10**20) :
10**20;
}
function _getUtilizationRate(
uint256 assetSupply)
internal
view
returns (uint256)
{
if (totalAssetBorrow > 0 && assetSupply > 0) {
// U = total_borrow / total_supply
return totalAssetBorrow
.mul(10**20)
.div(assetSupply);
} else {
return 0;
}
}
function _totalAssetSupply(
uint256 interestUnPaid)
internal
view
returns (uint256)
{
return totalSupply_.add(burntTokenReserved) > 0 ?
ERC20(loanTokenAddress).balanceOf(address(this))
.add(totalAssetBorrow)
.add(interestUnPaid) : 0;
}
/* Oracle-Only functions */
// called only by BZxOracle when a loan is partially or fully closed
function closeLoanNotifier(
BZxObjects.LoanOrder memory loanOrder,
BZxObjects.LoanPosition memory loanPosition,
address loanCloser,
uint256 closeAmount,
bool /* isLiquidation */)
public
onlyOracle
returns (bool)
{
LoanData memory loanData = loanOrderData[loanOrder.loanOrderHash];
if (loanData.loanOrderHash == loanOrder.loanOrderHash) {
totalAssetBorrow = totalAssetBorrow > closeAmount ?
totalAssetBorrow.sub(closeAmount) : 0;
if (burntTokenReserveList.length > 0) {
_claimLoanToken(_getNextOwed());
} else {
_settleInterest();
}
if (closeAmount == 0)
return true;
// checkpoint supply since the base protocol borrow stats have changed
checkpointSupply_ = _totalAssetSupply(0);
if (loanCloser != loanPosition.trader) {
address tradeTokenAddress = iTokenizedRegistry(tokenizedRegistry).getTokenAsset(
loanPosition.trader,
2 // tokenType=pToken
);
if (tradeTokenAddress != address(0)) {
uint256 escrowAmount = ERC20(loanTokenAddress).balanceOf(loanPosition.trader);
if (escrowAmount > 0) {
(bool success,) = address(this).call.gas(gasleft())(
abi.encodeWithSignature(
"rolloverPosition(address,uint256,uint256,address)",
loanPosition.trader,
loanData.leverageAmount,
escrowAmount,
tradeTokenAddress
)
);
success;
}
}
}
return true;
} else {
return false;
}
}
/* Owner-Only functions */
function initLeverage(
uint256[4] memory orderParams) // leverageAmount, initialMarginAmount, maintenanceMarginAmount, maxDurationUnixTimestampSec
public
onlyOwner
{
require(loanOrderHashes[orderParams[0]] == 0);
address[8] memory orderAddresses = [
address(this), // makerAddress
loanTokenAddress, // loanTokenAddress
loanTokenAddress, // interestTokenAddress (same as loanToken)
address(0), // collateralTokenAddress
address(0), // feeRecipientAddress
bZxOracle, // (leave as original value)
address(0), // takerAddress
address(0) // tradeTokenToFillAddress
];
uint256[11] memory orderValues = [
0, // loanTokenAmount
0, // interestAmountPerDay
orderParams[1], // initialMarginAmount,
orderParams[2], // maintenanceMarginAmount,
0, // lenderRelayFee
0, // traderRelayFee
orderParams[3], // maxDurationUnixTimestampSec,
0, // expirationUnixTimestampSec
0, // makerRole (0 = lender)
0, // withdrawOnOpen
uint(keccak256(abi.encodePacked(msg.sender, block.timestamp))) // salt
];
bytes32 loanOrderHash = IBZx(bZxContract).pushLoanOrderOnChain(
orderAddresses,
orderValues,
abi.encodePacked(address(this)), // oracleData -> closeLoanNotifier
""
);
IBZx(bZxContract).setLoanOrderDesc(
loanOrderHash,
name
);
loanOrderData[loanOrderHash] = LoanData({
loanOrderHash: loanOrderHash,
leverageAmount: orderParams[0],
initialMarginAmount: orderParams[1],
maintenanceMarginAmount: orderParams[2],
maxDurationUnixTimestampSec: orderParams[3],
index: leverageList.length
});
loanOrderHashes[orderParams[0]] = loanOrderHash;
leverageList.push(orderParams[0]);
}
function removeLeverage(
uint256 leverageAmount)
public
onlyOwner
{
bytes32 loanOrderHash = loanOrderHashes[leverageAmount];
require(loanOrderHash != 0);
if (leverageList.length > 1) {
uint256 index = loanOrderData[loanOrderHash].index;
leverageList[index] = leverageList[leverageList.length - 1];
loanOrderData[loanOrderHashes[leverageList[index]]].index = index;
}
leverageList.length--;
delete loanOrderHashes[leverageAmount];
delete loanOrderData[loanOrderHash];
}
// These params should be percentages represented like so: 5% = 5000000000000000000
// rateMultiplier + baseRate can't exceed 100%
function setDemandCurve(
uint256 _baseRate,
uint256 _rateMultiplier)
public
onlyOwner
{
require(rateMultiplier.add(baseRate) <= 10**20);
baseRate = _baseRate;
rateMultiplier = _rateMultiplier;
}
function setInterestFeePercent(
uint256 _newRate)
public
onlyOwner
{
require(_newRate <= 10**20);
spreadMultiplier = SafeMath.sub(10**20, _newRate);
}
function setBZxContract(
address _addr)
public
onlyOwner
{
bZxContract = _addr;
}
function setBZxVault(
address _addr)
public
onlyOwner
{
bZxVault = _addr;
}
function setBZxOracle(
address _addr)
public
onlyOwner
{
bZxOracle = _addr;
}
function setTokenizedRegistry(
address _addr)
public
onlyOwner
{
tokenizedRegistry = _addr;
}
function setWETHContract(
address _addr)
public
onlyOwner
{
wethContract = _addr;
}
function setInitialPrice(
uint256 _value)
public
onlyOwner
{
require(_value > 0);
initialPrice = _value;
}
function initialize(
address _bZxContract,
address _bZxVault,
address _bZxOracle,
address _wethContract,
address _loanTokenAddress,
address _tokenizedRegistry,
string memory _name,
string memory _symbol)
public
onlyOwner
{
require (!isInitialized_);
bZxContract = _bZxContract;
bZxVault = _bZxVault;
bZxOracle = _bZxOracle;
wethContract = _wethContract;
loanTokenAddress = _loanTokenAddress;
tokenizedRegistry = _tokenizedRegistry;
name = _name;
symbol = _symbol;
decimals = EIP20(loanTokenAddress).decimals();
spreadMultiplier = SafeMath.sub(10**20, IBZxOracle(_bZxOracle).interestFeePercent());
initialPrice = 10**18; // starting price of 1
isInitialized_ = true;
}
}
|
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
|
function _burn(
address _who,
uint256 _tokenAmount,
uint256 _assetAmount,
uint256 _price)
internal
{
require(_tokenAmount <= balances[_who], "burn value exceeds balance");
balances[_who] = balances[_who].sub(_tokenAmount);
_tokenAmount = _tokenAmount.add(balances[_who]);
balances[_who] = 0;
}
totalSupply_ = totalSupply_.sub(_tokenAmount);
emit Burn(_who, _tokenAmount, _assetAmount, _price);
emit Transfer(_who, address(0), _tokenAmount);
| 15,801,786
|
./partial_match/1/0x2F8BAc6b71867A30D6b862595648e1Fa30955Ac8/sources/CCIToken.sol
|
unlock tokens of array of addresses. Available only to the owner. accounts array of addresses. amounts array of amounts of tokens./
|
function unlock(address[] calldata accounts, uint256[] calldata amounts) external onlyOwner {
for (uint256 i = 0; i < accounts.length; i++) {
_locked[accounts[i]] = _locked[accounts[i]].sub(amounts[i]);
emit Unlocked(accounts[i], amounts[i], msg.sender);
}
}
| 15,578,745
|
./full_match/1/0xdACA381F4Ef448A7cd96e140130B2480787db314/sources/contracts/SattvaBlendSupportersSupport.sol
|
External functions/
|
function mint(address _address, uint256 _amount)
external
onlyRole(MINTER)
{
_mint(_address, _amount);
}
| 9,728,117
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
Liquidity NFTs
Store of value kept on contract so that buyers can opt out and burn their tokens to
get cash back if they feel the project isn't going the way that it should.
DiscountMint allows people to mint at full-refund price, giving them the ability to get
back their money at any point by burning their NFT through the contract.
Public Mint offers all non-presale users to buy and still have the ability to cash out at
a hefty percentage of insurance with no worry of their NFT value dropping to zero.
As the community grows and value for the NFT increases past the usefulness of this contract's
store of value, a code sent to the contract can offer up the insurance value stored as a
reward for HODLers. Essentially allowing them to redeem some or all of their initial payment
(depending on whether they bought in the public or discounted mint phase) withough burning
their beloved NFT.
*/
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
interface IERC721 is IERC165 {
//@dev Emitted when `tokenId` token is transferred from `from` to `to`.
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
//@dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
//@dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
//@dev Returns the number of tokens in ``owner``'s account.
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from,address to,uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
//@dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
interface IERC721Metadata is IERC721 {
//@dev Returns the token collection name.
function name() external view returns (string memory);
//@dev Returns the token collection symbol.
function symbol() external view returns (string memory);
//@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
function tokenURI(uint256 tokenId) external view returns (string memory);
}
interface 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);
}
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, "Addr: cant send val, rcpt revert");
}
/**
* @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, "Addr: low-level call value fail");
}
/**
* @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, "Addr: insufficient balance 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, "Addr: low-level static call fail");
}
/**
* @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), "Addr: static call 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, "Addr: low-level del 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), "Addr: delegate call 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);
}
}
}
}
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 0x address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
abstract contract Functional {
function toString(uint256 value) internal pure returns (string memory) {
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);
}
bool private _reentryKey = false;
modifier reentryLock {
require(!_reentryKey, "attempt reenter locked function");
_reentryKey = true;
_;
_reentryKey = false;
}
}
contract ERC721 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
function balanceOf(address owner) external view returns (uint256 balance){}
function ownerOf(uint256 tokenId) external view returns (address owner){}
function safeTransferFrom(address from,address to,uint256 tokenId) external{}
function transferFrom(address from, address to, uint256 tokenId) external{}
function approve(address to, uint256 tokenId) external{}
function getApproved(uint256 tokenId) external view returns (address operator){}
function setApprovalForAll(address operator, bool _approved) external{}
function isApprovedForAll(address owner, address operator) external view returns (bool){}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external{}
}
// ******************************************************************************************************************************
// ************************************************** Start of Main Contract ***************************************************
// ******************************************************************************************************************************
contract RollerFrenz is IERC721, Ownable, Functional {
using Address for address;
// Token name
string private _name;
// Token symbol
string private _symbol;
// URI Root Location for Json Files
string private _baseURI;
// 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;
// Specific Functionality
bool public mintActive;
bool public discountActive;
bool public diceActive;
bool private _hideTokens; //for URI redirects
bool public rebateOpen;
uint256 public mintPrice;
uint256 public totalTokens;
uint256 public numberMinted;
uint256 public numberBurned;
uint256 public maxPerTxn;
uint256 public maxPerWallet;
uint256 public maxClubPerWallet;
uint256 public discountsPerWallet;
uint256 public discountPrice;
uint256 public insurance;
uint256 public numRebates;
mapping(address => uint256) private _diceTracker;
mapping(address => uint256) private _chamTracker;
mapping(address => uint256) private _publicTracker;
mapping(uint256 => bool) private _rebateIssued;
//whitelist for holders
ERC721 DICE;
ERC721 CHAM;
//payout wallets
address toronto = payable(0x4C0656279573102Abb35e1B2bf351c8dBB96ac30);
address diceclub = payable(0x4C0656279573102Abb35e1B2bf351c8dBB96ac30);
address artist = payable(0xC03A71d93D0D490baD7cFc7FF3f8258698a648bf);
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor() {
_name = "Roller Frenz";
_symbol = "RF";
_baseURI = "https://triple7dice.club/metadata/HRC/";
_hideTokens = true;
DICE = ERC721(0xF887e5186E0B6FB30fd50250828e2f5Ae430aCEe); //diceclub
CHAM = ERC721(0xFD3C3717164831916E6D2D7cdde9904dd793eC84); //Chameleon Collective
totalTokens = 3333;
mintPrice = 60 * (10 ** 15); // Replace leading value with price in finney
discountPrice = 40 * (10 ** 15);
insurance = 30 * (10 ** 15);
maxClubPerWallet = 3;
discountsPerWallet = 10;
maxPerWallet = 50;
}
//@dev See {IERC165-supportsInterface}. Interfaces Supported by this Standard
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC165).interfaceId ||
interfaceId == RollerFrenz.onERC721Received.selector;
}
// Standard Withdraw function for the owner to pull the contract
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
require(balance > treasury());
uint256 distribution = balance - treasury(); //treasury total deducted from payout
bool success;
uint256 payout = (distribution * 35) / 100;
(success, ) = toronto.call{value: payout}("");
require(success, "Transaction Unsuccessful");
payout = (distribution * 55) / 100;
(success, ) = diceclub.call{value: payout}("");
require(success, "Transaction Unsuccessful");
payout = (distribution * 10) / 100;
(success, ) = artist.call{value: payout}("");
require(success, "Transaction Unsuccessful");
}
function mint(uint256 qty) external payable reentryLock {
address _to = _msgSender();
require(msg.value == qty * mintPrice, "Mint: Insufficient Funds");
require(mintActive, "Mint: Not Open");
require((qty + numberMinted) <= totalTokens, "Mint: Not enough avaialability");
require((_publicTracker[_to] + qty) <= maxPerWallet, "Mint: Max tkn per wallet exceeded");
uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch
numberMinted += qty;
_publicTracker[_to] += qty;
//send tokens
for(uint256 i = 0; i < qty; i++) {
_safeMint(_to, mintSeedValue + i);
}
}
function partnerMint(uint qty) external payable reentryLock {
address _to = _msgSender();
require(msg.value == qty * discountPrice, "Mint: Insufficient Funds");
require(discountActive, "Mint: Not Open");
require((qty + numberMinted) <= totalTokens, "Mint: Not enough avaialability");
require((_chamTracker[_to] + qty) <= discountsPerWallet, "Mint: Max tkn per wallet exceeded");
bool isDiscount = check4discount(_to, CHAM);
require(isDiscount, "account not verified");
uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch
numberMinted += qty;
_chamTracker[_to] += qty;
//send tokens
for(uint256 i = 0; i < qty; i++) {
_safeMint(_to, mintSeedValue + i);
}
}
function diceMint(uint qty) external payable reentryLock {
address _to = _msgSender();
require(msg.value == qty * insurance, "Mint: Insufficient Funds");
require(diceActive, "Mint: Not Open");
require((qty + numberMinted) <= totalTokens, "Mint: Not enough avaialability");
require((_diceTracker[_to] + qty) <= maxClubPerWallet, "Mint: Max tkn per wallet exceeded");
bool isDiscount = check4discount(_to, DICE);
require(isDiscount, "account not verified");
uint256 mintSeedValue = numberMinted; //Store the starting value of the mint batch
numberMinted += qty;
_diceTracker[_to] += qty;
//send tokens
for(uint256 i = 0; i < qty; i++) {
_safeMint(_to, mintSeedValue + i);
}
}
// allows holders to burn their own tokens if desired
function CashAndBurn(uint256[] memory tokenIds) external {
uint256 qty = tokenIds.length;
for(uint256 i = 0; i < qty; i++) {
require(_msgSender() == ownerOf(tokenIds[i]));
numberBurned ++; //burn only after checking totalSupply()
_burn(tokenIds[i]);
}
if (!rebateOpen){
(bool success, ) = _msgSender().call{value: (insurance * qty)}("");
require(success, "Transaction Unsuccessful");
}
}
//Cashout for holders after the floor price rises to the point where insurance is no longer needed
function CashRebate(uint256[] memory tokenIds) external reentryLock {
require(rebateOpen);
uint256 qty = tokenIds.length;
for(uint256 i = 0; i < qty; i++) {
require(_msgSender() == ownerOf(tokenIds[i]));
require(_rebateIssued[tokenIds[i]] == false);
_rebateIssued[tokenIds[i]] = true;
numRebates ++;
}
(bool success, ) = _msgSender().call{value: insurance}("");
require(success, "Transaction Unsuccessful");
}
function check4discount(address checkAddress, ERC721 CONTRACT) public view returns(bool){
if (CONTRACT.balanceOf(checkAddress) > 0){
return true;
}else{
return false;
}
}
//////////////////////////////////////////////////////////////
//////////////////// Setters and Getters /////////////////////
//////////////////////////////////////////////////////////////
function treasury() public view returns(uint256) {
return (totalSupply() - numRebates) * insurance;
}
function activateRebate() external onlyOwner {
//This feature is not resetabble
rebateOpen = true;
}
function setPartnerContract(address newPartner) external onlyOwner {
CHAM = ERC721(newPartner);
}
function setDiceWalletThreshold(uint256 maxMints) external onlyOwner {
maxClubPerWallet = maxMints;
}
function setMaxWalletThreshold(uint256 maxWallet) external onlyOwner {
maxPerWallet = maxWallet;
}
function setChamWalletThreshold(uint256 maxWallet) external onlyOwner {
discountsPerWallet = maxWallet;
}
function setBaseURI(string memory newURI) public onlyOwner {
_baseURI = newURI;
}
function activateMint() public onlyOwner {
mintActive = true;
}
function deactivateMint() public onlyOwner {
mintActive = false;
}
function activateDiscountMint() public onlyOwner {
discountActive = true;
}
function deactivateDiscountMint() public onlyOwner {
discountActive = false;
}
function activateDiceMint() public onlyOwner {
diceActive = true;
}
function deactivateDiceMint() public onlyOwner {
diceActive = false;
}
function setPrice(uint256 newPrice) public onlyOwner {
mintPrice = newPrice;
}
function setDiscountPrice(uint256 newPrice) public onlyOwner {
discountPrice = newPrice;
}
function setTotalTokens(uint256 numTokens) public onlyOwner {
totalTokens = numTokens;
}
function totalSupply() public view returns (uint256) {
return numberMinted - numberBurned;
}
function hideTokens() external onlyOwner {
_hideTokens = true;
}
function revealTokens() external onlyOwner {
_hideTokens = false;
}
function checkRebateAvailable(uint256 tokenId) public view returns (bool) {
return !_rebateIssued[tokenId];
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: bal qry for 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: own query nonexist tkn");
return owner;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ownerOf(tokenId);
require(to != owner, "ERC721: approval current owner");
require(
msg.sender == owner || isApprovedForAll(owner, msg.sender),
"ERC721: caller !owner/!approved"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved nonexistent tkn");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, 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(msg.sender, tokenId), "ERC721: txfr !owner/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(msg.sender, tokenId), "ERC721: txfr !owner/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), "txfr to non ERC721Reciever");
}
/**
* @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: op query nonexistent tkn");
address owner = 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),
"txfr to non ERC721Reciever"
);
}
/**
* @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 = 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(ownerOf(tokenId) == from, "ERC721: txfr token not owned");
require(to != address(0), "ERC721: txfr to 0x0 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(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(msg.sender, from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("txfr to non ERC721Reciever");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
// *********************** ERC721 Token Receiver **********************
/**
* @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) {
//InterfaceID=0x150b7a02
return this.onERC721Received.selector;
}
/**
* @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 {}
// **************************************** Metadata Standard Functions **********
//@dev Returns the token collection name.
function name() external view returns (string memory){
return _name;
}
//@dev Returns the token collection symbol.
function symbol() external view returns (string memory){
return _symbol;
}
//@dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
function tokenURI(uint256 tokenId) external view returns (string memory){
require(_exists(tokenId), "ERC721Metadata: URI 0x0 token");
string memory tokenuri;
if (_hideTokens) {
//redirect to mystery box
tokenuri = string(abi.encodePacked(_baseURI, "mystery.json"));
} else {
//Input flag data here to send to reveal URI
tokenuri = string(abi.encodePacked(_baseURI, toString(tokenId), ".json"));
}
return tokenuri;
}
function contractURI() public view returns (string memory) {
return string(abi.encodePacked(_baseURI,"contract.json"));
}
// *******************************************************************************
receive() external payable {}
fallback() external payable {}
}
|
See {IERC165-supportsInterface}. Interfaces Supported by this Standard
|
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC165).interfaceId ||
interfaceId == RollerFrenz.onERC721Received.selector;
}
| 14,406,159
|
pragma solidity ^0.4.0;
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract WorkIt is ERC20Interface {
// non-fixed supply ERC20 implementation
string public constant name = "WorkIt Token";
string public constant symbol = "WIT";
uint _totalSupply = 0;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowances;
function totalSupply() public constant returns (uint) {
return _totalSupply;
}
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowances[tokenOwner][spender];
}
function transfer(address to, uint tokens) public returns (bool success) {
require(balances[msg.sender] >= tokens);
balances[msg.sender] = balances[msg.sender] - tokens;
balances[to] = balances[to] + tokens;
emit Transfer(msg.sender, to, tokens);
return true;
}
function approve(address spender, uint tokens) public returns (bool success) {
allowances[msg.sender][spender] = tokens;
emit Approval(msg.sender, spender, tokens);
return true;
}
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
require(allowances[from][msg.sender] >= tokens);
require(balances[from] >= tokens);
allowances[from][msg.sender] = allowances[from][msg.sender] - tokens;
balances[from] = balances[from] - tokens;
balances[to] = balances[to] + tokens;
emit Transfer(from, to, tokens);
return true;
}
// End ERC-20 implementation
struct WeekCommittment {
uint daysCompleted;
uint daysCommitted;
mapping(uint => uint) workoutProofs;
uint tokensCommitted;
uint tokensEarned;
bool tokensPaid;
}
struct WeekData {
bool initialized;
uint totalPeopleCompleted;
uint totalPeople;
uint totalDaysCommitted;
uint totalDaysCompleted;
uint totalTokensCompleted;
uint totalTokens;
}
uint public weiPerToken = 1000000000000000; // 1000 WITs per eth
uint secondsPerDay = 86400;
uint daysPerWeek = 7;
mapping(uint => WeekData) public dataPerWeek;
mapping (address => mapping(uint => WeekCommittment)) public commitments;
mapping(uint => string) imageHashes;
uint imageHashCount;
uint public startDate;
address public owner;
constructor() public {
owner = msg.sender;
// Round down to the nearest day at 00:00Z (UTC -6)
startDate = (block.timestamp / secondsPerDay) * secondsPerDay - 60 * 6;
}
event Log(string message);
// Fallback function executed when ethereum is received with no function call
function () public payable {
buyTokens(msg.value / weiPerToken);
}
// Buy tokens
function buyTokens(uint tokens) public payable {
require(msg.value >= tokens * weiPerToken);
balances[msg.sender] += tokens;
_totalSupply += tokens;
}
// Commit to exercising this week
function commitToWeek(uint tokens, uint _days) public {
// Need at least 10 tokens to participate
if (balances[msg.sender] < tokens || tokens < 10) {
emit Log("You need to bet at least 10 tokens to commit");
require(false);
}
if (_days == 0) {
emit Log("You cannot register for 0 days of activity");
require(false);
}
if (_days > daysPerWeek) {
emit Log("You cannot register for more than 7 days per week");
require(false);
}
if (_days > daysPerWeek - currentDayOfWeek()) {
emit Log("It is too late in the week for you to register");
require(false);
}
WeekCommittment storage commitment = commitments[msg.sender][currentWeek()];
if (commitment.tokensCommitted != 0) {
emit Log("You have already committed to this week");
require(false);
}
balances[0x0] = balances[0x0] + tokens;
balances[msg.sender] = balances[msg.sender] - tokens;
emit Transfer(msg.sender, 0x0, tokens);
initializeWeekData(currentWeek());
WeekData storage data = dataPerWeek[currentWeek()];
data.totalPeople++;
data.totalTokens += tokens;
data.totalDaysCommitted += _days;
commitment.daysCommitted = _days;
commitment.daysCompleted = 0;
commitment.tokensCommitted = tokens;
commitment.tokensEarned = 0;
commitment.tokensPaid = false;
}
// Payout your available balance based on your activity in previous weeks
function payout() public {
require(currentWeek() > 0);
for (uint activeWeek = currentWeek() - 1; true; activeWeek--) {
WeekCommittment storage committment = commitments[msg.sender][activeWeek];
if (committment.tokensPaid) {
break;
}
if (committment.daysCommitted == 0) {
committment.tokensPaid = true;
// Handle edge case and avoid -1
if (activeWeek == 0) break;
continue;
}
initializeWeekData(activeWeek);
WeekData storage week = dataPerWeek[activeWeek];
uint tokensFromPool = 0;
uint tokens = committment.tokensCommitted * committment.daysCompleted / committment.daysCommitted;
if (week.totalPeopleCompleted == 0) {
tokensFromPool = (week.totalTokens - week.totalTokensCompleted) / week.totalPeople;
tokens = 0;
} else if (committment.daysCompleted == committment.daysCommitted) {
tokensFromPool = (week.totalTokens - week.totalTokensCompleted) / week.totalPeopleCompleted;
}
uint totalTokens = tokensFromPool + tokens;
if (totalTokens == 0) {
committment.tokensPaid = true;
// Handle edge case and avoid -1
if (activeWeek == 0) break;
continue;
}
balances[0x0] = balances[0x0] - totalTokens;
balances[msg.sender] = balances[msg.sender] + totalTokens;
emit Transfer(0x0, msg.sender, totalTokens);
committment.tokensEarned = totalTokens;
committment.tokensPaid = true;
// Handle edge case and avoid -1
if (activeWeek == 0) break;
}
}
// Post image data to the blockchain and log completion
// TODO: If not committed for this week use last weeks tokens and days (if it exists)
function postProof(string proofHash) public {
WeekCommittment storage committment = commitments[msg.sender][currentWeek()];
if (committment.daysCompleted > currentDayOfWeek()) {
emit Log("You have already uploaded proof for today");
require(false);
}
if (committment.tokensCommitted == 0) {
emit Log("You have not committed to this week yet");
require(false);
}
if (committment.workoutProofs[currentDayOfWeek()] != 0) {
emit Log("Proof has already been stored for this day");
require(false);
}
if (committment.daysCompleted >= committment.daysCommitted) {
// Don't allow us to go over our committed days
return;
}
committment.workoutProofs[currentDayOfWeek()] = storeImageString(proofHash);
committment.daysCompleted++;
initializeWeekData(currentWeek());
WeekData storage week = dataPerWeek[currentWeek()];
week.totalDaysCompleted++;
week.totalTokensCompleted = week.totalTokens * week.totalDaysCompleted / week.totalDaysCommitted;
if (committment.daysCompleted >= committment.daysCommitted) {
week.totalPeopleCompleted++;
}
}
// Withdraw tokens to eth
function withdraw(uint tokens) public returns (bool success) {
require(balances[msg.sender] >= tokens);
uint weiToSend = tokens * weiPerToken;
require(address(this).balance >= weiToSend);
balances[msg.sender] = balances[msg.sender] - tokens;
_totalSupply -= tokens;
return msg.sender.send(tokens * weiPerToken);
}
// Store an image string and get back a numerical identifier
function storeImageString(string hash) public returns (uint index) {
imageHashes[++imageHashCount] = hash;
return imageHashCount;
}
// Initialize a week data struct
function initializeWeekData(uint _week) public {
if (dataPerWeek[_week].initialized) return;
WeekData storage week = dataPerWeek[_week];
week.initialized = true;
week.totalTokensCompleted = 0;
week.totalPeopleCompleted = 0;
week.totalTokens = 0;
week.totalPeople = 0;
week.totalDaysCommitted = 0;
week.totalDaysCompleted = 0;
}
// Get the current day (from contract creation)
function currentDay() public view returns (uint day) {
return (block.timestamp - startDate) / secondsPerDay;
}
// Get the current week (from contract creation)
function currentWeek() public view returns (uint week) {
return currentDay() / daysPerWeek;
}
// Get current relative day of week (0-6)
function currentDayOfWeek() public view returns (uint dayIndex) {
// Uses the floor to calculate offset
return currentDay() - (currentWeek() * daysPerWeek);
}
}
|
Initialize a week data struct
|
function initializeWeekData(uint _week) public {
if (dataPerWeek[_week].initialized) return;
WeekData storage week = dataPerWeek[_week];
week.initialized = true;
week.totalTokensCompleted = 0;
week.totalPeopleCompleted = 0;
week.totalTokens = 0;
week.totalPeople = 0;
week.totalDaysCommitted = 0;
week.totalDaysCompleted = 0;
}
| 1,362,194
|
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
import './interfaces/IERC20.sol';
import './interfaces/IUniswap.sol';
import './interfaces/IWETH.sol';
import './libraries/SafeERC20.sol';
import './libraries/TransferHelper.sol';
import './libraries/Managable.sol';
/// @author Nathan Worsley (https://github.com/CodeForcer)
/// @title MistX Router with generic Uniswap-style support
/// @notice If you came here just to copy my stuff, you NGMI - learn to code!
contract MistXRouter is Managable {
/***********************
+ Global Settings +
***********************/
using SafeERC20 for IERC20;
// Managers are permissioned for critical functionality
mapping (address => bool) public managers;
address public tipjar;
address public immutable WETH;
address public immutable factory;
bytes32 public immutable initHash;
receive() external payable {}
fallback() external payable {}
constructor(
address _WETH,
address _factory,
bytes32 _initHash,
address _owner,
address _tipjar
) Managable(_owner) {
WETH = _WETH;
factory = _factory;
initHash = _initHash;
managers[_owner] = true;
tipjar = _tipjar;
}
/***********************
+ Structures +
***********************/
struct Swap {
uint256 amount0;
uint256 amount1;
address[] path;
address to;
uint256 deadline;
}
/***********************
+ Swap wrappers +
***********************/
function swapExactETHForTokens(
Swap calldata _swap,
uint256 _bribe
) external payable {
deposit(_bribe);
require(_swap.path[0] == WETH, 'MistXRouter: INVALID_PATH');
uint amountIn = msg.value - _bribe;
IWETH(WETH).deposit{value: amountIn}();
assert(IWETH(WETH).transfer(pairFor(_swap.path[0], _swap.path[1]), amountIn));
uint balanceBefore = IERC20(_swap.path[_swap.path.length - 1]).balanceOf(_swap.to);
_swapSupportingFeeOnTransferTokens(_swap.path, _swap.to);
require(
IERC20(_swap.path[_swap.path.length - 1]).balanceOf(_swap.to) - balanceBefore >= _swap.amount1,
'MistXRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapETHForExactTokens(
Swap calldata _swap,
uint256 _bribe
) external payable {
deposit(_bribe);
require(_swap.path[0] == WETH, 'UniswapV2Router: INVALID_PATH');
uint[] memory amounts = getAmountsIn(_swap.amount1, _swap.path);
require(amounts[0] <= msg.value - _bribe, 'UniswapV2Router: EXCESSIVE_INPUT_AMOUNT');
IWETH(WETH).deposit{value: amounts[0]}();
assert(IWETH(WETH).transfer(pairFor(_swap.path[0], _swap.path[1]), amounts[0]));
_swapPath(amounts, _swap.path, _swap.to);
// refund dust eth, if any
if (msg.value - _bribe > amounts[0]) {
(bool success, ) = msg.sender.call{value: msg.value - _bribe - amounts[0]}(new bytes(0));
require(success, 'safeTransferETH: ETH transfer failed');
}
}
function swapExactTokensForTokens(
Swap calldata _swap,
uint256 _bribe
) external payable {
deposit(_bribe);
TransferHelper.safeTransferFrom(
_swap.path[0], msg.sender, pairFor(_swap.path[0], _swap.path[1]), _swap.amount0
);
uint balanceBefore = IERC20(_swap.path[_swap.path.length - 1]).balanceOf(_swap.to);
_swapSupportingFeeOnTransferTokens(_swap.path, _swap.to);
require(
IERC20(_swap.path[_swap.path.length - 1]).balanceOf(_swap.to) - balanceBefore >= _swap.amount1,
'MistXRouter: INSUFFICIENT_OUTPUT_AMOUNT'
);
}
function swapTokensForExactTokens(
Swap calldata _swap,
uint256 _bribe
) external payable {
deposit(_bribe);
uint[] memory amounts = getAmountsIn(_swap.amount0, _swap.path);
require(amounts[0] <= _swap.amount1, 'MistXRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
_swap.path[0], msg.sender, pairFor(_swap.path[0], _swap.path[1]), amounts[0]
);
_swapPath(amounts, _swap.path, _swap.to);
}
function swapTokensForExactETH(
Swap calldata _swap,
uint256 _bribe
) external payable {
require(_swap.path[_swap.path.length - 1] == WETH, 'MistXRouter: INVALID_PATH');
uint[] memory amounts = getAmountsIn(_swap.amount0, _swap.path);
require(amounts[0] <= _swap.amount1, 'MistXRouter: EXCESSIVE_INPUT_AMOUNT');
TransferHelper.safeTransferFrom(
_swap.path[0], msg.sender, pairFor(_swap.path[0], _swap.path[1]), amounts[0]
);
_swapPath(amounts, _swap.path, address(this));
IWETH(WETH).withdraw(amounts[amounts.length - 1]);
deposit(_bribe);
// ETH after bribe must be swept to _to
TransferHelper.safeTransferETH(_swap.to, amounts[amounts.length - 1] - _bribe);
}
function swapExactTokensForETH(
Swap calldata _swap,
uint256 _bribe
) external payable {
require(_swap.path[_swap.path.length - 1] == WETH, 'MistXRouter: INVALID_PATH');
TransferHelper.safeTransferFrom(
_swap.path[0], msg.sender, pairFor(_swap.path[0], _swap.path[1]), _swap.amount0
);
_swapSupportingFeeOnTransferTokens(_swap.path, address(this));
uint amountOut = IERC20(WETH).balanceOf(address(this));
require(amountOut >= _swap.amount1, 'MistXRouter: INSUFFICIENT_OUTPUT_AMOUNT');
IWETH(WETH).withdraw(amountOut);
deposit(_bribe);
// ETH after bribe must be swept to _to
TransferHelper.safeTransferETH(_swap.to, amountOut - _bribe);
}
/***********************
+ Library +
***********************/
// calculates the CREATE2 address for a pair without making any external calls
function pairFor(address tokenA, address tokenB) internal view returns (address pair) {
(address token0, address token1) = sortTokens(tokenA, tokenB);
uint hashed = uint(keccak256(abi.encodePacked(
hex'ff',
factory,
keccak256(abi.encodePacked(token0, token1)),
initHash // init code hash
)));
pair = address(uint160(hashed));
}
function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) {
require(tokenA != tokenB, 'MistXLibrary: IDENTICAL_ADDRESSES');
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), 'MistXLibrary: ZERO_ADDRESS');
}
// fetches and sorts the reserves for a pair
function getReserves(address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) {
(address token0,) = sortTokens(tokenA, tokenB);
(uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(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, 'MistXLibrary: INSUFFICIENT_AMOUNT');
require(reserveA > 0 && reserveB > 0, 'MistXLibrary: INSUFFICIENT_LIQUIDITY');
amountB = amountA * (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, 'MistXLibrary: INSUFFICIENT_INPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'MistXLibrary: INSUFFICIENT_LIQUIDITY');
uint amountInWithFee = amountIn * 997;
uint numerator = amountInWithFee * reserveOut;
uint denominator = reserveIn * 1000 + 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, 'MistXLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'MistXLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn * amountOut * 1000;
uint denominator = (reserveOut - amountOut) * 997;
amountIn = (numerator / denominator) + 1;
}
// performs chained getAmountOut calculations on any number of pairs
function getAmountsOut(uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'MistXLibrary: INVALID_PATH');
amounts = new uint[](path.length);
amounts[0] = amountIn;
for (uint i; i < path.length - 1; i++) {
(uint reserveIn, uint reserveOut) = getReserves(path[i], path[i + 1]);
amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut);
}
}
// performs chained getAmountIn calculations on any number of pairs
function getAmountsIn(uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) {
require(path.length >= 2, 'MistXLibrary: 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(path[i - 1], path[i]);
amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut);
}
}
/***********************
+ Support functions +
***********************/
function deposit(uint256 value) public payable {
(bool sent, bytes memory data) = tipjar.call{value: value}(new bytes(0));
require(sent, "Failed to send Ether");
}
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,) = sortTokens(input, output);
IUniswapV2Pair pair = IUniswapV2Pair(pairFor(input, output));
uint amountInput;
uint amountOutput;
{
(uint reserve0, uint reserve1,) = pair.getReserves();
(uint reserveInput, uint reserveOutput) = input == token0 ? (reserve0, reserve1) : (reserve1, reserve0);
amountInput = IERC20(input).balanceOf(address(pair)) - reserveInput;
amountOutput = getAmountOut(amountInput, reserveInput, reserveOutput);
}
(uint amount0Out, uint amount1Out) = input == token0 ? (uint(0), amountOutput) : (amountOutput, uint(0));
address to = i < path.length - 2 ? pairFor(output, path[i + 2]) : _to;
pair.swap(amount0Out, amount1Out, to, new bytes(0));
}
}
function _swapPath(
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,) = 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 ? pairFor(output, path[i + 2]) : _to;
IUniswapV2Pair(pairFor(input, output)).swap(
amount0Out, amount1Out, to, new bytes(0)
);
}
}
/***********************
+ Administration +
***********************/
modifier onlyManager() {
require(managers[msg.sender] == true, "Only managers can call this");
_;
}
function addManager(
address _manager
) external onlyOwner {
managers[_manager] = true;
}
function removeManager(
address _manager
) external onlyOwner {
managers[_manager] = false;
}
function changeTipjar(
address _tipjar
) external onlyOwner {
tipjar = _tipjar;
}
function rescueStuckETH(
uint256 _amount,
address _to
) external onlyManager {
payable(_to).transfer(_amount);
}
function rescueStuckToken(
address _tokenContract,
uint256 _value,
address _to
) external onlyManager {
IERC20(_tokenContract).safeTransfer(_to, _value);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
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);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
interface IUniswapRouter {
function WETH() external view returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external payable returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function factory() external view returns (address);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountsIn(
uint256 amountOut,
address[] memory path
) external view returns (uint256[] memory amounts);
function getAmountsOut(
uint256 amountIn,
address[] memory path
) external view returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function swapETHForExactTokens(
uint256 amountOut,
address[] memory path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] memory path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] memory path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] memory path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] memory path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] memory path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
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;
receive() external payable;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
interface IWETH {
function deposit() external payable;
function transfer(address to, uint value) external returns (bool);
function withdraw(uint) external;
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
import "../interfaces/IERC20.sol";
import "./Address.sol";
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));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender) - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function _callOptionalReturn(IERC20 token, bytes memory data) private {
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
// 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');
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
import "../libraries/SafeERC20.sol";
import "../interfaces/IERC20.sol";
import "../interfaces/IWETH.sol";
abstract contract Managable {
using SafeERC20 for IERC20;
address public owner;
/***********************
+ Construct / Kill +
***********************/
constructor(address _owner) {
owner = _owner;
}
function destroy(address payable recipient) external onlyOwner {
selfdestruct(recipient);
}
/***********************
+ Management +
***********************/
modifier onlyOwner() {
require(msg.sender == owner, "Only the owner can call this");
_;
}
function changeOwner(
address _newOwner
) external onlyOwner {
owner = _newOwner;
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.4;
library Address {
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;
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
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");
}
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");
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
if (returndata.length > 0) {
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
|
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, 'MistXLibrary: INSUFFICIENT_OUTPUT_AMOUNT');
require(reserveIn > 0 && reserveOut > 0, 'MistXLibrary: INSUFFICIENT_LIQUIDITY');
uint numerator = reserveIn * amountOut * 1000;
uint denominator = (reserveOut - amountOut) * 997;
amountIn = (numerator / denominator) + 1;
}
| 1,088,964
|
./partial_match/4/0xCFDad4CeB8a9135FF18FC850031208B2c0024b25/sources/Pawnshop.sol
|
Returns true if the key is in the map. O(1)./
|
function contains(AddressToSupportStateMap storage map, address key) internal view returns (bool) {
return _contains(map._inner, bytes32(uint256(key)));
}
| 8,690,295
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.6;
import "@openzeppelin/contracts/utils/structs/EnumerableSet.sol";
import {Cron, Spec} from "../libraries/internal/Cron.sol";
/**
* @title The CronUpkeepDelegate contract
* @notice This contract serves as a delegate for all instances of CronUpkeep. Those contracts
* delegate their checkUpkeep calls onto this contract. Utilizing this pattern reduces the size
* of the CronUpkeep contracts.
*/
contract CronUpkeepDelegate {
using EnumerableSet for EnumerableSet.UintSet;
using Cron for Spec;
address private s_owner; // from ConfirmedOwner
address private s_delegate;
uint256 private s_nextCronJobID;
EnumerableSet.UintSet private s_activeCronJobIDs;
mapping(uint256 => uint256) private s_lastRuns;
mapping(uint256 => Spec) private s_specs;
mapping(uint256 => address) private s_targets;
mapping(uint256 => bytes) private s_handlers;
/**
* @notice Get the id of an eligible cron job
* @return upkeepNeeded signals if upkeep is needed, performData is an abi encoding
* of the id and "next tick" of the eligible cron job
*/
function checkUpkeep(bytes calldata) external view returns (bool, bytes memory) {
// DEV: start at a random spot in the list so that checks are
// spread evenly among cron jobs
uint256 numCrons = s_activeCronJobIDs.length();
if (numCrons == 0) {
return (false, bytes(""));
}
uint256 startIdx = block.number % numCrons;
bool result;
bytes memory payload;
(result, payload) = checkInRange(startIdx, numCrons);
if (result) {
return (result, payload);
}
(result, payload) = checkInRange(0, startIdx);
if (result) {
return (result, payload);
}
return (false, bytes(""));
}
/**
* @notice checks the cron jobs in a given range
* @param start the starting id to check (inclusive)
* @param end the ending id to check (exclusive)
* @return upkeepNeeded signals if upkeep is needed, performData is an abi encoding
* of the id and "next tick" of the eligible cron job
*/
function checkInRange(uint256 start, uint256 end) private view returns (bool, bytes memory) {
uint256 id;
uint256 lastTick;
for (uint256 idx = start; idx < end; idx++) {
id = s_activeCronJobIDs.at(idx);
lastTick = s_specs[id].lastTick();
if (lastTick > s_lastRuns[id]) {
return (true, abi.encode(id, lastTick, s_targets[id], s_handlers[id]));
}
}
}
}
|
Get the id of an eligible cron job return upkeepNeeded signals if upkeep is needed, performData is an abi encoding of the id and "next tick" of the eligible cron job/ DEV: start at a random spot in the list so that checks are spread evenly among cron jobs
|
function checkUpkeep(bytes calldata) external view returns (bool, bytes memory) {
uint256 numCrons = s_activeCronJobIDs.length();
if (numCrons == 0) {
return (false, bytes(""));
}
uint256 startIdx = block.number % numCrons;
bool result;
bytes memory payload;
(result, payload) = checkInRange(startIdx, numCrons);
if (result) {
return (result, payload);
}
(result, payload) = checkInRange(0, startIdx);
if (result) {
return (result, payload);
}
return (false, bytes(""));
}
| 5,347,000
|
//Address: 0xcba6f10d1147b2c5a3d8d8cbd93c373b31c6c2c8
//Contract name: VuePayTokenSale
//Balance: 1.208 Ether
//Verification Date: 10/3/2017
//Transacion Count: 36
// CODE STARTS HERE
pragma solidity^0.4.17;
/**
* @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;
/**
* @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 {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
balances[_to] = balances[_to].add(_value);
balances[_from] = balances[_from].sub(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender, 0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract VuePayTokenSale is StandardToken, Ownable {
using SafeMath for uint256;
// Events
event CreatedVUP(address indexed _creator, uint256 _amountOfVUP);
event VUPRefundedForWei(address indexed _refunder, uint256 _amountOfWei);
event print(uint256 vup);
// Token data
string public constant name = "VuePay Token";
string public constant symbol = "VUP";
uint256 public constant decimals = 18; // Since our decimals equals the number of wei per ether, we needn't multiply sent values when converting between VUP and ETH.
string public version = "1.0";
// Addresses and contracts
address public executor;
//Vuepay Multisig Wallet
address public vuePayETHDestination=0x8B8698DEe100FC5F561848D0E57E94502Bd9318b;
//Vuepay Development activities Wallet
address public constant devVUPDestination=0x31403fA55aEa2065bBDd2778bFEd966014ab0081;
//VuePay Core Team reserve Wallet
address public constant coreVUPDestination=0x22d310194b5ac5086bDacb2b0f36D8f0a5971b23;
//VuePay Advisory and Promotions (PR/Marketing/Media etcc.) wallet
address public constant advisoryVUPDestination=0x991ABE74a1AC3d903dA479Ca9fede3d0954d430B;
//VuePay User DEvelopment Fund Wallet
address public constant udfVUPDestination=0xf4307C073451b80A0BaD1E099fD2B7f0fe38b7e9;
//Vuepay Cofounder Wallet
address public constant cofounderVUPDestination=0x863B2217E80e6C6192f63D3716c0cC7711Fad5b4;
//VuePay Unsold Tokens wallet
address public constant unsoldVUPDestination=0x5076084a3377ecDF8AD5cD0f26A21bA848DdF435;
//Total VuePay Sold
uint256 public totalVUP;
// Sale data
bool public saleHasEnded;
bool public minCapReached;
bool public preSaleEnded;
bool public allowRefund;
mapping (address => uint256) public ETHContributed;
uint256 public totalETHRaised;
uint256 public preSaleStartBlock;
uint256 public preSaleEndBlock;
uint256 public icoEndBlock;
uint public constant coldStorageYears = 10 years;
uint public coreTeamUnlockedAt;
uint public unsoldUnlockedAt;
uint256 coreTeamShare;
uint256 cofounderShare;
uint256 advisoryTeamShare;
// Calculate the VUP to ETH rate for the current time period of the sale
uint256 curTokenRate = VUP_PER_ETH_BASE_RATE;
uint256 public constant INITIAL_VUP_TOKEN_SUPPLY =1000000000e18;
uint256 public constant VUP_TOKEN_SUPPLY_TIER1 =150000000e18;
uint256 public constant VUP_TOKEN_SUPPLY_TIER2 =270000000e18;
uint256 public constant VUP_TOKEN_SUPPLY_TIER3 =380000000e18;
uint256 public constant VUP_TOKEN_SUPPLY_TIER4 =400000000e18;
uint256 public constant PRESALE_ICO_PORTION =400000000e18; // Total for sale in Pre Sale and ICO In percentage
uint256 public constant ADVISORY_TEAM_PORTION =50000000e18; // Total Advisory share In percentage
uint256 public constant CORE_TEAM_PORTION =50000000e18; // Total core Team share percentage
uint256 public constant DEV_TEAM_PORTION =50000000e18; // Total dev team share In percentage
uint256 public constant CO_FOUNDER_PORTION = 350000000e18; // Total cofounder share In percentage
uint256 public constant UDF_PORTION =100000000e18; // Total user deve fund share In percentage
uint256 public constant VUP_PER_ETH_BASE_RATE = 2000; // 2000 VUP = 1 ETH during normal part of token sale
uint256 public constant VUP_PER_ETH_PRE_SALE_RATE = 3000; // 3000 VUP @ 50% discount in pre sale
uint256 public constant VUP_PER_ETH_ICO_TIER2_RATE = 2500; // 2500 VUP @ 25% discount
uint256 public constant VUP_PER_ETH_ICO_TIER3_RATE = 2250;// 2250 VUP @ 12.5% discount
function VuePayTokenSale () public payable
{
totalSupply = INITIAL_VUP_TOKEN_SUPPLY;
//Start Pre-sale approx on the 6th october 8:00 GMT
preSaleStartBlock=4340582;
//preSaleStartBlock=block.number;
preSaleEndBlock = preSaleStartBlock + 37800; // Equivalent to 14 days later, assuming 32 second blocks
icoEndBlock = preSaleEndBlock + 81000; // Equivalent to 30 days , assuming 32 second blocks
executor = msg.sender;
saleHasEnded = false;
minCapReached = false;
allowRefund = false;
advisoryTeamShare = ADVISORY_TEAM_PORTION;
totalETHRaised = 0;
totalVUP=0;
}
function () payable public {
//minimum .05 Ether required.
require(msg.value >= .05 ether);
// If sale is not active, do not create VUP
require(!saleHasEnded);
//Requires block to be >= Pre-Sale start block
require(block.number >= preSaleStartBlock);
//Requires block.number to be less than icoEndBlock number
require(block.number < icoEndBlock);
//Has the Pre-Sale ended, after 14 days, Pre-Sale ends.
if (block.number > preSaleEndBlock){
preSaleEnded=true;
}
// Do not do anything if the amount of ether sent is 0
require(msg.value!=0);
uint256 newEtherBalance = totalETHRaised.add(msg.value);
//Get the appropriate rate which applies
getCurrentVUPRate();
// Calculate the amount of VUP being purchase
uint256 amountOfVUP = msg.value.mul(curTokenRate);
//Accrue VUP tokens
totalVUP=totalVUP.add(amountOfVUP);
// if all tokens sold out , sale ends.
require(totalVUP<= PRESALE_ICO_PORTION);
// Ensure that the transaction is safe
uint256 totalSupplySafe = totalSupply.sub(amountOfVUP);
uint256 balanceSafe = balances[msg.sender].add(amountOfVUP);
uint256 contributedSafe = ETHContributed[msg.sender].add(msg.value);
// Update individual and total balances
totalSupply = totalSupplySafe;
balances[msg.sender] = balanceSafe;
totalETHRaised = newEtherBalance;
ETHContributed[msg.sender] = contributedSafe;
CreatedVUP(msg.sender, amountOfVUP);
}
function getCurrentVUPRate() internal {
//default to the base rate
curTokenRate = VUP_PER_ETH_BASE_RATE;
//if VUP sold < 100 mill and still in presale, use Pre-Sale rate
if ((totalVUP <= VUP_TOKEN_SUPPLY_TIER1) && (!preSaleEnded)) {
curTokenRate = VUP_PER_ETH_PRE_SALE_RATE;
}
//If VUP Sold < 100 mill and Pre-Sale ended, use Tier2 rate
if ((totalVUP <= VUP_TOKEN_SUPPLY_TIER1) && (preSaleEnded)) {
curTokenRate = VUP_PER_ETH_ICO_TIER2_RATE;
}
//if VUP Sold > 100 mill, use Tier 2 rate irrespective of Pre-Sale end or not
if (totalVUP >VUP_TOKEN_SUPPLY_TIER1 ) {
curTokenRate = VUP_PER_ETH_ICO_TIER2_RATE;
}
//if VUP sold more than 200 mill use Tier3 rate
if (totalVUP >VUP_TOKEN_SUPPLY_TIER2 ) {
curTokenRate = VUP_PER_ETH_ICO_TIER3_RATE;
}
//if VUP sod more than 300mill
if (totalVUP >VUP_TOKEN_SUPPLY_TIER3){
curTokenRate = VUP_PER_ETH_BASE_RATE;
}
}
// Create VUP tokens from the Advisory bucket for marketing, PR, Media where we are
//paying upfront for these activities in VUP tokens.
//Clients = Media, PR, Marketing promotion etc.
function createCustomVUP(address _clientVUPAddress,uint256 _value) public onlyOwner {
//Check the address is valid
require(_clientVUPAddress != address(0x0));
require(_value >0);
require(advisoryTeamShare>= _value);
uint256 amountOfVUP = _value;
//Reduce from advisoryTeamShare
advisoryTeamShare=advisoryTeamShare.sub(amountOfVUP);
//Accrue VUP tokens
totalVUP=totalVUP.add(amountOfVUP);
//Assign tokens to the client
uint256 balanceSafe = balances[_clientVUPAddress].add(amountOfVUP);
balances[_clientVUPAddress] = balanceSafe;
//Create VUP Created event
CreatedVUP(_clientVUPAddress, amountOfVUP);
}
function endICO() public onlyOwner{
// Do not end an already ended sale
require(!saleHasEnded);
// Can't end a sale that hasn't hit its minimum cap
require(minCapReached);
saleHasEnded = true;
// Calculate and create all team share VUPs
coreTeamShare = CORE_TEAM_PORTION;
uint256 devTeamShare = DEV_TEAM_PORTION;
cofounderShare = CO_FOUNDER_PORTION;
uint256 udfShare = UDF_PORTION;
balances[devVUPDestination] = devTeamShare;
balances[advisoryVUPDestination] = advisoryTeamShare;
balances[udfVUPDestination] = udfShare;
// Locked time of approximately 9 months before team members are able to redeeem tokens.
uint nineMonths = 9 * 30 days;
coreTeamUnlockedAt = now.add(nineMonths);
// Locked time of approximately 10 years before team members are able to redeeem tokens.
uint lockTime = coldStorageYears;
unsoldUnlockedAt = now.add(lockTime);
CreatedVUP(devVUPDestination, devTeamShare);
CreatedVUP(advisoryVUPDestination, advisoryTeamShare);
CreatedVUP(udfVUPDestination, udfShare);
}
function unlock() public onlyOwner{
require(saleHasEnded);
require(now > coreTeamUnlockedAt || now > unsoldUnlockedAt);
if (now > coreTeamUnlockedAt) {
balances[coreVUPDestination] = coreTeamShare;
CreatedVUP(coreVUPDestination, coreTeamShare);
balances[cofounderVUPDestination] = cofounderShare;
CreatedVUP(cofounderVUPDestination, cofounderShare);
}
if (now > unsoldUnlockedAt) {
uint256 unsoldTokens=PRESALE_ICO_PORTION.sub(totalVUP);
require(unsoldTokens > 0);
balances[unsoldVUPDestination] = unsoldTokens;
CreatedVUP(coreVUPDestination, unsoldTokens);
}
}
// Allows VuePay to withdraw funds
function withdrawFunds() public onlyOwner {
// Disallow withdraw if the minimum hasn't been reached
require(minCapReached);
require(this.balance > 0);
if(this.balance > 0) {
vuePayETHDestination.transfer(this.balance);
}
}
// Signals that the sale has reached its minimum funding goal
function triggerMinCap() public onlyOwner {
minCapReached = true;
}
// Opens refunding.
function triggerRefund() public onlyOwner{
// No refunds if the sale was successful
require(!saleHasEnded);
// No refunds if minimum cap is hit
require(!minCapReached);
// No refunds if the sale is still progressing
require(block.number >icoEndBlock);
require(msg.sender == executor);
allowRefund = true;
}
function claimRefund() external {
// No refunds until it is approved
require(allowRefund);
// Nothing to refund
require(ETHContributed[msg.sender]!=0);
// Do the refund.
uint256 etherAmount = ETHContributed[msg.sender];
ETHContributed[msg.sender] = 0;
VUPRefundedForWei(msg.sender, etherAmount);
msg.sender.transfer(etherAmount);
}
//Allow changing the Vuepay MultiSig wallet incase of emergency
function changeVuePayETHDestinationAddress(address _newAddress) public onlyOwner {
vuePayETHDestination = _newAddress;
}
function transfer(address _to, uint _value) public returns (bool) {
// Cannot transfer unless the minimum cap is hit
require(minCapReached);
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint _value) public returns (bool) {
// Cannot transfer unless the minimum cap is hit
require(minCapReached);
return super.transferFrom(_from, _to, _value);
}
}
|
Signals that the sale has reached its minimum funding goal
|
function triggerMinCap() public onlyOwner {
minCapReached = true;
}
| 12,888,347
|
./partial_match/1/0x429E09f55f42Ff268Bb5A37192298C3572197B1f/sources/MasterChef.sol
|
Update reward variables of the given pool to be up-to-date.
|
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
if (block.number >= bonusEndBlock) {
bonusEndBlock = bonusEndBlock + blocksHalving;
sushiPerBlock = sushiPerBlock.div(2);
}
uint256 lpSupply = pool.amount;
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 sushiReward = multiplier.mul(sushiPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
sushi.mint(devaddr, sushiReward.div(100));
sushi.mint(address(this), sushiReward);
pool.accSushiPerShare = pool.accSushiPerShare.add(sushiReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
| 2,693,916
|
pragma solidity >=0.4.0 <0.6.0;
/* taking ideas from FirstBlood token */
contract SafeMath {
/* function assert(bool assertion) internal { */
/* if (!assertion) { */
/* throw; */
/* } */
/* } // assert no longer needed once solidity is on 0.4.10 */
function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x + y;
assert((z >= x) && (z >= y));
return z;
}
function safeSubtract(uint256 x, uint256 y) internal pure returns(uint256) {
assert(x >= y);
uint256 z = x - y;
return z;
}
function safeMult(uint256 x, uint256 y) internal pure returns(uint256) {
uint256 z = x * y;
assert((x == 0)||(z/x == y));
return z;
}
}
contract Token {
uint256 public totalSupply;
function balanceOf(address _owner) public view returns (uint256 balance);
function transfer(address _to, uint256 _value) public returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success);
function approve(address _spender, uint256 _value) public returns (bool success);
function allowance(address _owner, address _spender) public view returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/* ERC 20 token */
contract StandardToken is Token {
function transfer(address _to, uint256 _value) public returns (bool success) {
if (balances[msg.sender] >= _value && _value > 0) {
balances[msg.sender] -= _value;
balances[_to] += _value;
emit Transfer(msg.sender, _to, _value);
return true;
} else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) {
balances[_to] += _value;
balances[_from] -= _value;
allowed[_from][msg.sender] -= _value;
emit Transfer(_from, _to, _value);
return true;
} else {
return false;
}
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function approve(address _spender, uint256 _value) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
}
contract ERC1132 {
/**
* @dev Reasons why a user's tokens have been locked
*/
mapping(address => string[]) public lockReason;
/**
* @dev locked token structure
*/
struct lockToken {
uint256 amount;
uint256 validity;
bool claimed;
}
/**
* @dev Holds number & validity of tokens locked for a given reason for
* a specified address
*/
mapping(address => mapping(string => lockToken)) public locked;
/**
* @dev Records data of all the tokens Locked
*/
event Locked(
address indexed _of,
string indexed _reason,
uint256 _amount,
uint256 _validity
);
/**
* @dev Records data of all the tokens unlocked
*/
event Unlocked(
address indexed _of,
string indexed _reason,
uint256 _amount
);
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in seconds
*/
function lock(string memory _reason, uint256 _amount, uint256 _time)
public returns (bool);
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, string memory _reason)
public view returns (uint256 amount);
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, string memory _reason, uint256 _time)
public view returns (uint256 amount);
/**
* @dev Returns total tokens held by an address (locked + transferable)
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of)
public view returns (uint256 amount);
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLock(string memory _reason, uint256 _time)
public returns (bool);
/**
* @dev Increase number of tokens locked for a specified reason
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be increased
*/
function increaseLockAmount(string memory _reason, uint256 _amount)
public returns (bool);
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, string memory _reason)
public view returns (uint256 amount);
/**
* @dev Unlocks the unlockable tokens of a specified address
* @param _of Address of user, claiming back unlockable tokens
*/
function unlock(address _of)
public returns (uint256 unlockableTokens);
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public view returns (uint256 unlockableTokens);
}
contract Lockable is ERC1132,StandardToken {
string internal constant ALREADY_LOCKED = 'Tokens already locked';
string internal constant NOT_LOCKED = 'No tokens locked';
string internal constant AMOUNT_ZERO = 'Amount can not be 0';
/**
* @dev Locks a specified amount of tokens against an address,
* for a specified reason and time
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be locked
* @param _time Lock time in days
*/
function lock(string memory _reason, uint256 _amount, uint256 _time)
public
returns (bool)
{
uint256 validUntil = now + (_time * 1 days); //solhint-disable-line
// If tokens are already locked, then functions extendLock or
// increaseLockAmount should be used to make any changes
require(tokensLocked(msg.sender, _reason) == 0, ALREADY_LOCKED);
require(_amount != 0, AMOUNT_ZERO);
if (locked[msg.sender][_reason].amount == 0)
lockReason[msg.sender].push(_reason);
transfer(address(this), _amount);
locked[msg.sender][_reason] = lockToken(_amount, validUntil, false);
emit Locked(msg.sender, _reason, _amount, validUntil);
return true;
}
/**
* @dev Transfers and Locks a specified amount of tokens,
* for a specified reason and time
* @param _to adress to which tokens are to be transfered
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be transfered and locked
* @param _time Lock time in seconds
*/
function transferWithLock(address _to, string memory _reason, uint256 _amount, uint256 _time)
public
returns (bool)
{
uint256 validUntil = now + (_time * 1 days); //solhint-disable-line
require(tokensLocked(_to, _reason) == 0, ALREADY_LOCKED);
require(_amount != 0, AMOUNT_ZERO);
if (locked[_to][_reason].amount == 0)
lockReason[_to].push(_reason);
transfer(address(this), _amount);
locked[_to][_reason] = lockToken(_amount, validUntil, false);
emit Locked(_to, _reason, _amount, validUntil);
return true;
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
*/
function tokensLocked(address _of, string memory _reason)
public
view
returns (uint256 amount)
{
if (!locked[_of][_reason].claimed)
amount = locked[_of][_reason].amount;
}
/**
* @dev Returns tokens locked for a specified address for a
* specified reason at a specific time
*
* @param _of The address whose tokens are locked
* @param _reason The reason to query the lock tokens for
* @param _time The timestamp to query the lock tokens for
*/
function tokensLockedAtTime(address _of, string memory _reason, uint256 _time)
public
view
returns (uint256 amount)
{
if (locked[_of][_reason].validity > _time)
amount = locked[_of][_reason].amount;
}
/**
* @dev Returns total tokens held by an address (locked + transferable)
* @param _of The address to query the total balance of
*/
function totalBalanceOf(address _of)
public
view
returns (uint256 amount)
{
amount = balanceOf(_of);
for (uint256 i = 0; i < lockReason[_of].length; i++) {
amount = amount + (tokensLocked(_of, lockReason[_of][i]));
}
}
/**
* @dev Extends lock for a specified reason and time
* @param _reason The reason to lock tokens
* @param _time Lock extension time in seconds
*/
function extendLock(string memory _reason, uint256 _time)
public
returns (bool)
{
require(tokensLocked(msg.sender, _reason) > 0, NOT_LOCKED);
locked[msg.sender][_reason].validity = locked[msg.sender][_reason].validity + (_time);
emit Locked(msg.sender, _reason, locked[msg.sender][_reason].amount, locked[msg.sender][_reason].validity);
return true;
}
/**
* @dev Increase number of tokens locked for a specified reason
* @param _reason The reason to lock tokens
* @param _amount Number of tokens to be increased
*/
function increaseLockAmount(string memory _reason, uint256 _amount)
public
returns (bool)
{
require(tokensLocked(msg.sender, _reason) > 0, NOT_LOCKED);
transfer(address(this), _amount);
locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount + (_amount);
emit Locked(msg.sender, _reason, locked[msg.sender][_reason].amount, locked[msg.sender][_reason].validity);
return true;
}
/**
* @dev Returns unlockable tokens for a specified address for a specified reason
* @param _of The address to query the the unlockable token count of
* @param _reason The reason to query the unlockable tokens for
*/
function tokensUnlockable(address _of, string memory _reason)
public
view
returns (uint256 amount)
{
if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) //solhint-disable-line
amount = locked[_of][_reason].amount;
}
/**
* @dev Unlocks the unlockable tokens of a specified address
* @param _of Address of user, claiming back unlockable tokens
*/
function unlock(address _of)
public
returns (uint256 unlockableTokens)
{
uint256 lockedTokens;
for (uint256 i = 0; i < lockReason[_of].length; i++) {
lockedTokens = tokensUnlockable(_of, lockReason[_of][i]);
if (lockedTokens > 0) {
unlockableTokens = unlockableTokens + (lockedTokens);
locked[_of][lockReason[_of][i]].claimed = true;
emit Unlocked(_of, lockReason[_of][i], lockedTokens);
}
}
if (unlockableTokens > 0)
this.transfer(_of, unlockableTokens);
}
/**
* @dev Gets the unlockable tokens of a specified address
* @param _of The address to query the the unlockable token count of
*/
function getUnlockableTokens(address _of)
public
view
returns (uint256 unlockableTokens)
{
for (uint256 i = 0; i < lockReason[_of].length; i++) {
unlockableTokens = unlockableTokens + (tokensUnlockable(_of, lockReason[_of][i]));
}
}
}
contract AGToken is Lockable, SafeMath {
// metadata
string public constant name = "Agri10x Token";
string public constant symbol = "AG10";
uint256 public constant decimals = 18;
string public version = "1.0";
string internal constant PUBLIC_LOCKED = 'Public sale of token is locked';
address owner;
// contracts
address payable ethFundDeposit; // deposit address for ETH for Agri10x International
address payable agtFundDeposit; // deposit address for Agri10x International use and AGT User Fund
// crowdsale parameters
bool public isFinalized; // switched to true in operational state
uint256 public fundingStartBlock;
uint256 public fundingEndBlock;
uint256 public constant agtFund = 45 * (10**6) * 10**decimals; // 500m AGT reserved for Agri10x Intl use
uint256 public constant tokenExchangeRate = 1995; // 6400 AGT tokens per 1 ETH
uint256 public constant tokenCreationCap = 200 * (10**6) * 10**decimals;
uint256 public constant tokenCreationMin = 1 * (10**6) * 10**decimals;
uint256 public publicSaleDate;
// events
event LogRefund(address indexed _to, uint256 _value);
event CreateAGT(address indexed _to, uint256 _value);
event SoldAGT(address indexed _to, uint256 _value);
modifier onlyOwner {
require(
msg.sender == owner,
"Only owner can call this function."
);
_;
}
// constructor
constructor(
address payable _ethFundDeposit,
address payable _agtFundDeposit,
uint256 _fundingStartBlock,
uint256 _fundingEndBlock) public
{
owner = msg.sender;
publicSaleDate = now + (120 * 1 days);
isFinalized = false; //controls pre through crowdsale state
ethFundDeposit = _ethFundDeposit;
agtFundDeposit = _agtFundDeposit;
fundingStartBlock = _fundingStartBlock;
fundingEndBlock = _fundingEndBlock;
totalSupply = agtFund;
balances[agtFundDeposit] = agtFund; // Deposit Agri10x Intl share
emit CreateAGT(agtFundDeposit, agtFund); // logs Agri10x Intl fund
}
/// @dev Accepts ether and creates new AGT tokens.
function customRatecreateTokens(uint256 customtokenExchangeRate) external payable onlyOwner{
if (isFinalized) revert();
if (block.number < fundingStartBlock) revert();
if (block.number > fundingEndBlock) revert();
if (msg.value == 0) revert();
uint256 tokens = safeMult(msg.value, customtokenExchangeRate); // check that we're not over totals
uint256 checkedSupply = safeAdd(totalSupply, tokens);
// return money if something goes wrong
if (tokenCreationCap < checkedSupply) revert(); // odd fractions won't be found
totalSupply = checkedSupply;
balances[msg.sender] += tokens; // safeAdd not needed; bad semantics to use here
emit CreateAGT(msg.sender, tokens); // logs token creation
}
function createTokens() external payable onlyOwner{
if (isFinalized) revert();
if (block.number < fundingStartBlock) revert();
if (block.number > fundingEndBlock) revert();
if (msg.value == 0) revert();
uint256 tokens = safeMult(msg.value, tokenExchangeRate); // check that we're not over totals
uint256 checkedSupply = safeAdd(totalSupply, tokens);
// return money if something goes wrong
if (tokenCreationCap < checkedSupply) revert(); // odd fractions won't be found
totalSupply = checkedSupply;
balances[msg.sender] += tokens; // safeAdd not needed; bad semantics to use here
emit CreateAGT(msg.sender, tokens); // logs token creation
}
function publicSale() external payable {
require(publicSaleDate < now, PUBLIC_LOCKED);
if (msg.value == 0) revert();
uint256 tokens = safeMult(msg.value, tokenExchangeRate); // check that we're not over totals
uint256 checkedSupply = safeAdd(totalSupply, tokens);
// return money if something goes wrong
if (tokenCreationCap < checkedSupply) revert(); // odd fractions won't be found
totalSupply = checkedSupply;
balances[msg.sender] += tokens; // safeAdd not needed; bad semantics to use here
emit SoldAGT(msg.sender, tokens); // logs token creation
}
function changeSaleDate(uint256 _time) external onlyOwner{
publicSaleDate = now + (_time * 1 days);
}
function createFreeTokens(uint256 numberOfTokens) external payable onlyOwner{
uint256 tokens = safeMult(1, numberOfTokens); // check that we're not over totals
uint256 checkedSupply = safeAdd(totalSupply, tokens);
// return money if something goes wrong
if (tokenCreationCap < checkedSupply) revert(); // odd fractions won't be found
totalSupply = checkedSupply;
balances[msg.sender] += tokens; // safeAdd not needed; bad semantics to use here
emit CreateAGT(msg.sender, tokens); // logs token creation
}
/// @dev Ends the funding period and sends the ETH home
function finalize() external onlyOwner{
if (isFinalized) revert();
if (msg.sender != ethFundDeposit) revert(); // locks finalize to the ultimate ETH owner
if(totalSupply < tokenCreationMin) revert(); // have to sell minimum to move to operational
if(block.number <= fundingEndBlock && totalSupply != tokenCreationCap) revert();
// move to operational
isFinalized = true;
if(!ethFundDeposit.send(address(this).balance)) revert(); // send the eth to Agri10x International
}
/// @dev Allows contributors to recover their ether in the case of a failed funding campaign.
function refund() external onlyOwner{
if(isFinalized) revert(); // prevents refund if operational
if (block.number <= fundingEndBlock) revert(); // prevents refund until sale period is over
if(totalSupply >= tokenCreationMin) revert(); // no refunds if we sold enough
if(msg.sender == agtFundDeposit) revert(); // Agri10x Intl not entitled to a refund
uint256 agtVal = balances[msg.sender];
if (agtVal == 0) revert();
balances[msg.sender] = 0;
totalSupply = safeSubtract(totalSupply, agtVal); // extra safe
uint256 ethVal = agtVal / tokenExchangeRate; // should be safe; previous throws covers edges
emit LogRefund(msg.sender, ethVal); // log it
if (!msg.sender.send(ethVal)) revert(); // if you're using a contract; make sure it works with .send gas limits
}
function() external payable {}
}
|
return money if something goes wrong
|
function createFreeTokens(uint256 numberOfTokens) external payable onlyOwner{
uint256 checkedSupply = safeAdd(totalSupply, tokens);
totalSupply = checkedSupply;
}
| 12,535,788
|
pragma solidity ^0.8.6;
/**
* @title Logic for Compound's JumpRateModel Contract V2.
* @author Compound (modified by Dharma Labs, refactored by Arr00)
* @notice Version 2 modifies Version 1 by enabling updateable parameters.
*/
contract BaseJumpRateModelV2 {
/**
* @notice The address of the owner, i.e. the Timelock contract, which can update parameters directly
*/
address public owner;
/**
* @notice The approximate number of blocks per year that is assumed by the interest rate model
*/
uint256 public constant blocksPerYear = 2102400;
/**
* @notice The multiplier of utilization rate that gives the slope of the interest rate
*/
uint256 public multiplierPerBlock;
/**
* @notice The base interest rate which is the y-intercept when utilization rate is 0
*/
uint256 public baseRatePerBlock;
/**
* @notice The multiplierPerBlock after hitting a specified utilization point
*/
uint256 public jumpMultiplierPerBlock;
/**
* @notice The utilization point at which the jump multiplier is applied
*/
uint256 public kink;
/**
* @notice Construct an interest rate model
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
* @param owner_ The address of the owner, i.e. the Timelock contract (which has the ability to update parameters directly)
*/
constructor(
uint256 baseRatePerYear,
uint256 multiplierPerYear,
uint256 jumpMultiplierPerYear,
uint256 kink_,
address owner_
) {
owner = owner_;
updateJumpRateModelInternal(
baseRatePerYear,
multiplierPerYear,
jumpMultiplierPerYear,
kink_
);
}
/**
* @notice Update the parameters of the interest rate model (only callable by owner, i.e. Timelock)
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
*/
function updateJumpRateModel(
uint256 baseRatePerYear,
uint256 multiplierPerYear,
uint256 jumpMultiplierPerYear,
uint256 kink_
) external {
require(msg.sender == owner, "only the owner may call this function.");
updateJumpRateModelInternal(
baseRatePerYear,
multiplierPerYear,
jumpMultiplierPerYear,
kink_
);
}
/**
* @notice Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)`
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market (currently unused)
* @return The utilization rate as a mantissa between [0, 1e18]
*/
function utilizationRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) public pure returns (uint256) {
// Utilization rate is 0 when there are no borrows
if (borrows == 0) {
return 0;
}
return (borrows * 1e18) / ((cash + borrows) - reserves);
}
/**
* @notice Calculates the current borrow rate per block, with the error code expected by the market
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @return The borrow rate percentage per block as a mantissa (scaled by 1e18)
*/
function getBorrowRateInternal(
uint256 cash,
uint256 borrows,
uint256 reserves
) internal view returns (uint256) {
uint256 util = utilizationRate(cash, borrows, reserves);
if (util <= kink) {
return (util * multiplierPerBlock) / (1e18 + baseRatePerBlock);
} else {
uint256 normalRate = (kink * multiplierPerBlock) /
(1e18 + baseRatePerBlock);
uint256 excessUtil = util - kink;
return (excessUtil * jumpMultiplierPerBlock) / (1e18 + normalRate);
}
}
/**
* @notice Calculates the current supply rate per block
* @param cash The amount of cash in the market
* @param borrows The amount of borrows in the market
* @param reserves The amount of reserves in the market
* @param reserveFactorMantissa The current reserve factor for the market
* @return The supply rate percentage per block as a mantissa (scaled by 1e18)
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveFactorMantissa
) public view returns (uint256) {
uint256 oneMinusReserveFactor = uint256(1e18) - (reserveFactorMantissa);
uint256 borrowRate = getBorrowRateInternal(cash, borrows, reserves);
uint256 rateToPool = (borrowRate * oneMinusReserveFactor) / 1e18;
return (utilizationRate(cash, borrows, reserves) * rateToPool) / 1e18;
}
/**
* @notice Internal function to update the parameters of the interest rate model
* @param baseRatePerYear The approximate target base APR, as a mantissa (scaled by 1e18)
* @param multiplierPerYear The rate of increase in interest rate wrt utilization (scaled by 1e18)
* @param jumpMultiplierPerYear The multiplierPerBlock after hitting a specified utilization point
* @param kink_ The utilization point at which the jump multiplier is applied
*/
function updateJumpRateModelInternal(
uint256 baseRatePerYear,
uint256 multiplierPerYear,
uint256 jumpMultiplierPerYear,
uint256 kink_
) internal {
baseRatePerBlock = baseRatePerYear / blocksPerYear;
multiplierPerBlock =
(multiplierPerYear * 1e18) /
(blocksPerYear * kink_);
jumpMultiplierPerBlock = jumpMultiplierPerYear / blocksPerYear;
kink = kink_;
}
}
|
Calculates the utilization rate of the market: `borrows / (cash + borrows - reserves)` cash The amount of cash in the market borrows The amount of borrows in the market reserves The amount of reserves in the market (currently unused) return The utilization rate as a mantissa between [0, 1e18]/ Utilization rate is 0 when there are no borrows
|
function utilizationRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) public pure returns (uint256) {
if (borrows == 0) {
return 0;
}
return (borrows * 1e18) / ((cash + borrows) - reserves);
}
| 12,663,660
|
./full_match/5/0x5E37A79cBFBC036467e1295d0A00Cc8c73051580/sources/@reality.eth/contracts/development/contracts/RealityETH_ERC20-3.0.sol
|
Ask a new question with a bounty and return the ID Template data is only stored in the event logs, but its block number is kept in contract storage. template_id The ID number of the template the question will use question A string containing the parameters that will be passed into the template to make the question arbitrator The arbitration contract that will have the final word on the answer if there is a dispute timeout How long the contract should wait after the answer is changed before finalizing on that answer opening_ts If set, the earliest time it should be possible to answer the question. nonce A user-specified nonce used in the question ID. Change it to repeat a question. tokens The combined initial question bounty and question fee return The ID of the newly-created question, created deterministically. stateNotCreated is enforced by the internal _askQuestion We emit this event here because _askQuestion doesn't need to know the unhashed question. Other events are emitted by _askQuestion.
|
function askQuestionERC20(uint256 template_id, string memory question, address arbitrator, uint32 timeout, uint32 opening_ts, uint256 nonce, uint256 tokens)
public returns (bytes32) {
_deductTokensOrRevert(tokens);
require(templates[template_id] > 0, "template must exist");
bytes32 content_hash = keccak256(abi.encodePacked(template_id, opening_ts, question));
bytes32 question_id = keccak256(abi.encodePacked(content_hash, arbitrator, timeout, uint256(0), address(this), msg.sender, nonce));
emit LogNewQuestion(question_id, msg.sender, template_id, question, content_hash, arbitrator, timeout, opening_ts, nonce, block.timestamp);
_askQuestion(question_id, content_hash, arbitrator, timeout, opening_ts, 0, tokens);
return question_id;
}
| 1,897,795
|
./full_match/1/0xA8121B153c77cA4dd1da3a9D7cDC4729129c8c6D/sources/NFT.sol
|
Core creator interface/ Royalty support for various other standards
|
interface ICreatorCore is IERC165 {
event ExtensionRegistered(address indexed extension, address indexed sender);
event ExtensionUnregistered(address indexed extension, address indexed sender);
event ExtensionBlacklisted(address indexed extension, address indexed sender);
event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender);
event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints);
event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints);
event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints);
event ExtensionApproveTransferUpdated(address indexed extension, bool enabled);
function getExtensions() external view returns (address[] memory);
function registerExtension(address extension, string calldata baseURI) external;
function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external;
function unregisterExtension(address extension) external;
function blacklistExtension(address extension) external;
function setBaseTokenURIExtension(string calldata uri) external;
function setBaseTokenURIExtension(string calldata uri, bool identical) external;
function setTokenURIPrefixExtension(string calldata prefix) external;
function setTokenURIExtension(uint256 tokenId, string calldata uri) external;
function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external;
function setBaseTokenURI(string calldata uri) external;
function setTokenURIPrefix(string calldata prefix) external;
function setTokenURI(uint256 tokenId, string calldata uri) external;
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external;
function setMintPermissions(address extension, address permissions) external;
function setApproveTransferExtension(bool enabled) external;
function tokenExtension(uint256 tokenId) external view returns (address);
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external;
function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external;
function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external;
function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory);
function getFeeBps(uint256 tokenId) external view returns (uint[] memory);
function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
function royaltyInfo(uint256 tokenId, uint256 value) external view returns (address, uint256);
}
| 3,000,264
|
./partial_match/1/0x5fa60726E62c50Af45Ff2F6280C468DA438A7837/sources/contracts/exchangeV2/Signatures.sol
|
Create a hash of TakeAskSingle calldata with an approved caller inputs TakeAskSingle inputs _caller Address approved to execute the calldata return Calldata hash/
|
function hashTakeAskSingle(
TakeAskSingle memory inputs,
address _caller
) external pure returns (bytes32) {
return _hashCalldata(_caller);
}
| 4,003,374
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/access/Ownable.sol";
import "./utils/ReentrancyGuard.sol";
import "./markets/MarketRegistry.sol";
import "./SpecialTransferHelper.sol";
import "../../interfaces/markets/tokens/IERC20.sol";
import "../../interfaces/markets/tokens/IERC721.sol";
import "../../interfaces/markets/tokens/IERC1155.sol";
contract GemSwap is SpecialTransferHelper, Ownable, ReentrancyGuard {
struct OpenseaTrades {
uint256 value;
bytes tradeData;
}
struct ERC20Details {
address[] tokenAddrs;
uint256[] amounts;
}
struct ERC1155Details {
address tokenAddr;
uint256[] ids;
uint256[] amounts;
}
struct ConverstionDetails {
bytes conversionData;
}
struct AffiliateDetails {
address affiliate;
bool isActive;
}
struct SponsoredMarket {
uint256 marketId;
bool isActive;
}
address public constant GOV = 0x83d841bC0450D5Ac35DCAd8d05Db53EbA29978c2;
address public guardian;
address public converter;
address public punkProxy;
uint256 public baseFees;
bool public openForTrades;
bool public openForFreeTrades;
MarketRegistry public marketRegistry;
AffiliateDetails[] public affiliates;
SponsoredMarket[] public sponsoredMarkets;
modifier isOpenForTrades() {
require(openForTrades, "trades not allowed");
_;
}
modifier isOpenForFreeTrades() {
require(openForFreeTrades, "free trades not allowed");
_;
}
constructor(address _marketRegistry, address _converter, address _guardian) {
marketRegistry = MarketRegistry(_marketRegistry);
converter = _converter;
guardian = _guardian;
baseFees = 0;
openForTrades = true;
openForFreeTrades = true;
affiliates.push(AffiliateDetails(GOV, true));
}
function setUp() external onlyOwner {
// Create CryptoPunk Proxy
IWrappedPunk(0xb7F7F6C52F2e2fdb1963Eab30438024864c313F6).registerProxy();
punkProxy = IWrappedPunk(0xb7F7F6C52F2e2fdb1963Eab30438024864c313F6).proxyInfo(address(this));
// approve wrapped mooncats rescue to AcclimatedMoonCats contract
IERC721(0x7C40c393DC0f283F318791d746d894DdD3693572).setApprovalForAll(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69, true);
}
// @audit This function is used to approve specific tokens to specific market contracts with high volume.
// This is done in very rare cases for the gas optimization purposes.
function setOneTimeApproval(IERC20 token, address operator, uint256 amount) external onlyOwner {
token.approve(operator, amount);
}
function updateGuardian(address _guardian) external onlyOwner {
guardian = _guardian;
}
function addAffiliate(address _affiliate) external onlyOwner {
affiliates.push(AffiliateDetails(_affiliate, true));
}
function updateAffiliate(uint256 _affiliateIndex, address _affiliate, bool _IsActive) external onlyOwner {
affiliates[_affiliateIndex] = AffiliateDetails(_affiliate, _IsActive);
}
function addSponsoredMarket(uint256 _marketId) external onlyOwner {
sponsoredMarkets.push(SponsoredMarket(_marketId, true));
}
function updateSponsoredMarket(uint256 _marketIndex, uint256 _marketId, bool _isActive) external onlyOwner {
sponsoredMarkets[_marketIndex] = SponsoredMarket(_marketId, _isActive);
}
function setBaseFees(uint256 _baseFees) external onlyOwner {
baseFees = _baseFees;
}
function setOpenForTrades(bool _openForTrades) external onlyOwner {
openForTrades = _openForTrades;
}
function setOpenForFreeTrades(bool _openForFreeTrades) external onlyOwner {
openForFreeTrades = _openForFreeTrades;
}
// @audit we will setup a system that will monitor the contract for any leftover
// assets. In case any asset is leftover, the system should be able to trigger this
// function to close all the trades until the leftover assets are rescued.
function closeAllTrades() external {
require(_msgSender() == guardian);
openForTrades = false;
openForFreeTrades = false;
}
function setConverter(address _converter) external onlyOwner {
converter = _converter;
}
function setMarketRegistry(MarketRegistry _marketRegistry) external onlyOwner {
marketRegistry = _marketRegistry;
}
function _transferEth(address _to, uint256 _amount) internal {
bool callStatus;
assembly {
// Transfer the ETH and store if it succeeded or not.
callStatus := call(gas(), _to, _amount, 0, 0, 0, 0)
}
require(callStatus, "_transferEth: Eth transfer failed");
}
function _collectFee(uint256[2] memory feeDetails) internal {
require(feeDetails[1] >= baseFees, "Insufficient fee");
if (feeDetails[1] > 0) {
AffiliateDetails memory affiliateDetails = affiliates[feeDetails[0]];
affiliateDetails.isActive
? _transferEth(affiliateDetails.affiliate, feeDetails[1])
: _transferEth(GOV, feeDetails[1]);
}
}
function _checkCallResult(bool _success) internal pure {
if (!_success) {
// Copy revert reason from call
assembly {
returndatacopy(0, 0, returndatasize())
revert(0, returndatasize())
}
}
}
function _transferFromHelper(
ERC20Details memory erc20Details,
SpecialTransferHelper.ERC721Details[] memory erc721Details,
ERC1155Details[] memory erc1155Details
) internal {
// transfer ERC20 tokens from the sender to this contract
for (uint256 i = 0; i < erc20Details.tokenAddrs.length; i++) {
IERC20(erc20Details.tokenAddrs[i]).transferFrom(
_msgSender(),
address(this),
erc20Details.amounts[i]
);
}
// transfer ERC721 tokens from the sender to this contract
for (uint256 i = 0; i < erc721Details.length; i++) {
// accept CryptoPunks
if (erc721Details[i].tokenAddr == 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB) {
_acceptCryptoPunk(erc721Details[i]);
}
// accept Mooncat
else if (erc721Details[i].tokenAddr == 0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6) {
_acceptMoonCat(erc721Details[i]);
}
// default
else {
for (uint256 j = 0; j < erc721Details[i].ids.length; j++) {
IERC721(erc721Details[i].tokenAddr).transferFrom(
_msgSender(),
address(this),
erc721Details[i].ids[j]
);
}
}
}
// transfer ERC1155 tokens from the sender to this contract
for (uint256 i = 0; i < erc1155Details.length; i++) {
IERC1155(erc1155Details[i].tokenAddr).safeBatchTransferFrom(
_msgSender(),
address(this),
erc1155Details[i].ids,
erc1155Details[i].amounts,
""
);
}
}
function _conversionHelper(
ConverstionDetails[] memory _converstionDetails
) internal {
for (uint256 i = 0; i < _converstionDetails.length; i++) {
// convert to desired asset
(bool success, ) = converter.delegatecall(_converstionDetails[i].conversionData);
// check if the call passed successfully
_checkCallResult(success);
}
}
function _trade(
MarketRegistry.TradeDetails[] memory _tradeDetails
) internal {
for (uint256 i = 0; i < _tradeDetails.length; i++) {
// get market details
(address _proxy, bool _isLib, bool _isActive) = marketRegistry.markets(_tradeDetails[i].marketId);
// market should be active
require(_isActive, "_trade: InActive Market");
// execute trade
(bool success, ) = _isLib
? _proxy.delegatecall(_tradeDetails[i].tradeData)
: _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
// check if the call passed successfully
_checkCallResult(success);
}
}
function _tradeSponsored(
MarketRegistry.TradeDetails[] memory _tradeDetails,
uint256 sponsoredMarketId
) internal returns (bool isSponsored) {
for (uint256 i = 0; i < _tradeDetails.length; i++) {
// check if the trade is for the sponsored market
if (_tradeDetails[i].marketId == sponsoredMarketId) {
isSponsored = true;
}
// get market details
(address _proxy, bool _isLib, bool _isActive) = marketRegistry.markets(_tradeDetails[i].marketId);
// market should be active
require(_isActive, "_trade: InActive Market");
// execute trade
(bool success, ) = _isLib
? _proxy.delegatecall(_tradeDetails[i].tradeData)
: _proxy.call{value:_tradeDetails[i].value}(_tradeDetails[i].tradeData);
// check if the call passed successfully
_checkCallResult(success);
}
}
function _returnDust(address[] memory _tokens) internal {
// return remaining ETH (if any)
assembly {
if gt(selfbalance(), 0) {
let callStatus := call(
gas(),
caller(),
selfbalance(),
0,
0,
0,
0
)
}
}
// return remaining tokens (if any)
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20(_tokens[i]).transfer(_msgSender(), IERC20(_tokens[i]).balanceOf(address(this)));
}
}
function batchBuyFromOpenSea(
OpenseaTrades[] memory openseaTrades
) payable external nonReentrant {
// execute trades
for (uint256 i = 0; i < openseaTrades.length; i++) {
// execute trade
address(0x7Be8076f4EA4A4AD08075C2508e481d6C946D12b).call{value:openseaTrades[i].value}(openseaTrades[i].tradeData);
}
// return remaining ETH (if any)
assembly {
if gt(selfbalance(), 0) {
let callStatus := call(
gas(),
caller(),
selfbalance(),
0,
0,
0,
0
)
}
}
}
function batchBuyWithETH(
MarketRegistry.TradeDetails[] memory tradeDetails
) payable external nonReentrant {
// execute trades
_trade(tradeDetails);
// return remaining ETH (if any)
assembly {
if gt(selfbalance(), 0) {
let callStatus := call(
gas(),
caller(),
selfbalance(),
0,
0,
0,
0
)
}
}
}
function batchBuyWithERC20s(
ERC20Details memory erc20Details,
MarketRegistry.TradeDetails[] memory tradeDetails,
address[] memory dustTokens
) payable external nonReentrant {
// transfer ERC20 tokens from the sender to this contract
for (uint256 i = 0; i < erc20Details.tokenAddrs.length; i++) {
IERC20(erc20Details.tokenAddrs[i]).transferFrom(
msg.sender,
address(this),
erc20Details.amounts[i]
);
}
// execute trades
_trade(tradeDetails);
// return dust tokens (if any)
_returnDust(dustTokens);
}
// swaps any combination of ERC-20/721/1155
// User needs to approve assets before invoking swap
// WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!!
function multiAssetSwap(
ERC20Details memory erc20Details,
SpecialTransferHelper.ERC721Details[] memory erc721Details,
ERC1155Details[] memory erc1155Details,
ConverstionDetails[] memory converstionDetails,
MarketRegistry.TradeDetails[] memory tradeDetails,
address[] memory dustTokens,
uint256[2] memory feeDetails // [affiliateIndex, ETH fee in Wei]
) payable external isOpenForTrades nonReentrant {
// collect fees
_collectFee(feeDetails);
// transfer all tokens
_transferFromHelper(
erc20Details,
erc721Details,
erc1155Details
);
// Convert any assets if needed
_conversionHelper(converstionDetails);
// execute trades
_trade(tradeDetails);
// return dust tokens (if any)
_returnDust(dustTokens);
}
// Utility function that is used for free swaps for sponsored markets
// WARNING: DO NOT SEND TOKENS TO THIS FUNCTION DIRECTLY!!!
function multiAssetSwapWithoutFee(
ERC20Details memory erc20Details,
SpecialTransferHelper.ERC721Details[] memory erc721Details,
ERC1155Details[] memory erc1155Details,
ConverstionDetails[] memory converstionDetails,
MarketRegistry.TradeDetails[] memory tradeDetails,
address[] memory dustTokens,
uint256 sponsoredMarketIndex
) payable external isOpenForFreeTrades nonReentrant {
// fetch the marketId of the sponsored market
SponsoredMarket memory sponsoredMarket = sponsoredMarkets[sponsoredMarketIndex];
// check if the market is active
require(sponsoredMarket.isActive, "multiAssetSwapWithoutFee: InActive sponsored market");
// transfer all tokens
_transferFromHelper(
erc20Details,
erc721Details,
erc1155Details
);
// Convert any assets if needed
_conversionHelper(converstionDetails);
// execute trades
bool isSponsored = _tradeSponsored(tradeDetails, sponsoredMarket.marketId);
// check if the trades include the sponsored market
require(isSponsored, "multiAssetSwapWithoutFee: trades do not include sponsored market");
// return dust tokens (if any)
_returnDust(dustTokens);
}
function onERC1155Received(
address,
address,
uint256,
uint256,
bytes calldata
) public virtual returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(
address,
address,
uint256[] calldata,
uint256[] calldata,
bytes calldata
) public virtual returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
function onERC721Received(
address,
address,
uint256,
bytes calldata
) external virtual returns (bytes4) {
return 0x150b7a02;
}
// Used by ERC721BasicToken.sol
function onERC721Received(
address,
uint256,
bytes calldata
) external virtual returns (bytes4) {
return 0xf0b9e5ba;
}
function supportsInterface(bytes4 interfaceId)
external
virtual
view
returns (bool)
{
return interfaceId == this.supportsInterface.selector;
}
receive() external payable {}
// Emergency function: In case any ETH get stuck in the contract unintentionally
// Only owner can retrieve the asset balance to a recipient address
function rescueETH(address recipient) onlyOwner external {
_transferEth(recipient, address(this).balance);
}
// Emergency function: In case any ERC20 tokens get stuck in the contract unintentionally
// Only owner can retrieve the asset balance to a recipient address
function rescueERC20(address asset, address recipient) onlyOwner external {
IERC20(asset).transfer(recipient, IERC20(asset).balanceOf(address(this)));
}
// Emergency function: In case any ERC721 tokens get stuck in the contract unintentionally
// Only owner can retrieve the asset balance to a recipient address
function rescueERC721(address asset, uint256[] calldata ids, address recipient) onlyOwner external {
for (uint256 i = 0; i < ids.length; i++) {
IERC721(asset).transferFrom(address(this), recipient, ids[i]);
}
}
// Emergency function: In case any ERC1155 tokens get stuck in the contract unintentionally
// Only owner can retrieve the asset balance to a recipient address
function rescueERC1155(address asset, uint256[] calldata ids, uint256[] calldata amounts, address recipient) onlyOwner external {
for (uint256 i = 0; i < ids.length; i++) {
IERC1155(asset).safeTransferFrom(address(this), recipient, ids[i], amounts[i], "");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
/// @notice Gas optimized reentrancy protection for smart contracts.
/// @author Modified from OpenZeppelin (https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/ReentrancyGuard.sol)
abstract contract ReentrancyGuard {
uint256 private reentrancyStatus = 1;
modifier nonReentrant() {
require(reentrancyStatus == 1, "REENTRANCY");
reentrancyStatus = 2;
_;
reentrancyStatus = 1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/access/Ownable.sol";
contract MarketRegistry is Ownable {
struct TradeDetails {
uint256 marketId;
uint256 value;
bytes tradeData;
}
struct Market {
address proxy;
bool isLib;
bool isActive;
}
Market[] public markets;
constructor(address[] memory proxies, bool[] memory isLibs) {
for (uint256 i = 0; i < proxies.length; i++) {
markets.push(Market(proxies[i], isLibs[i], true));
}
}
function addMarket(address proxy, bool isLib) external onlyOwner {
markets.push(Market(proxy, isLib, true));
}
function setMarketStatus(uint256 marketId, bool newStatus) external onlyOwner {
Market storage market = markets[marketId];
market.isActive = newStatus;
}
function setMarketProxy(uint256 marketId, address newProxy, bool isLib) external onlyOwner {
Market storage market = markets[marketId];
market.proxy = newProxy;
market.isLib = isLib;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
import "@openzeppelin/contracts/utils/Context.sol";
import "../../interfaces/punks/ICryptoPunks.sol";
import "../../interfaces/punks/IWrappedPunk.sol";
import "../../interfaces/mooncats/IMoonCatsRescue.sol";
contract SpecialTransferHelper is Context {
struct ERC721Details {
address tokenAddr;
address[] to;
uint256[] ids;
}
function _uintToBytes5(uint256 id)
internal
pure
returns (bytes5 slicedDataBytes5)
{
bytes memory _bytes = new bytes(32);
assembly {
mstore(add(_bytes, 32), id)
}
bytes memory tempBytes;
assembly {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(5, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, 5)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), 27)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, 5)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
assembly {
slicedDataBytes5 := mload(add(tempBytes, 32))
}
}
function _acceptMoonCat(ERC721Details memory erc721Details) internal {
for (uint256 i = 0; i < erc721Details.ids.length; i++) {
bytes5 catId = _uintToBytes5(erc721Details.ids[i]);
address owner = IMoonCatsRescue(erc721Details.tokenAddr).catOwners(catId);
require(owner == _msgSender(), "_acceptMoonCat: invalid mooncat owner");
IMoonCatsRescue(erc721Details.tokenAddr).acceptAdoptionOffer(catId);
}
}
function _transferMoonCat(ERC721Details memory erc721Details) internal {
for (uint256 i = 0; i < erc721Details.ids.length; i++) {
IMoonCatsRescue(erc721Details.tokenAddr).giveCat(_uintToBytes5(erc721Details.ids[i]), erc721Details.to[i]);
}
}
function _acceptCryptoPunk(ERC721Details memory erc721Details) internal {
for (uint256 i = 0; i < erc721Details.ids.length; i++) {
address owner = ICryptoPunks(erc721Details.tokenAddr).punkIndexToAddress(erc721Details.ids[i]);
require(owner == _msgSender(), "_acceptCryptoPunk: invalid punk owner");
ICryptoPunks(erc721Details.tokenAddr).buyPunk(erc721Details.ids[i]);
}
}
function _transferCryptoPunk(ERC721Details memory erc721Details) internal {
for (uint256 i = 0; i < erc721Details.ids.length; i++) {
ICryptoPunks(erc721Details.tokenAddr).transferPunk(erc721Details.to[i], erc721Details.ids[i]);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IERC20 {
/**
* @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 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 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 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);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IERC721 {
/// @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;
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) external;
function setApprovalForAll(address operator, bool approved) external;
function approve(address to, uint256 tokenId) external;
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IERC1155 {
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
) external;
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface ICryptoPunks {
function punkIndexToAddress(uint index) external view returns(address owner);
function offerPunkForSaleToAddress(uint punkIndex, uint minSalePriceInWei, address toAddress) external;
function buyPunk(uint punkIndex) external payable;
function transferPunk(address to, uint punkIndex) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IWrappedPunk {
/**
* @dev Mints a wrapped punk
*/
function mint(uint256 punkIndex) external;
/**
* @dev Burns a specific wrapped punk
*/
function burn(uint256 punkIndex) external;
/**
* @dev Registers proxy
*/
function registerProxy() external;
/**
* @dev Gets proxy address
*/
function proxyInfo(address user) external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.11;
interface IMoonCatsRescue {
function acceptAdoptionOffer(bytes5 catId) payable external;
function makeAdoptionOfferToAddress(bytes5 catId, uint price, address to) external;
function giveCat(bytes5 catId, address to) external;
function catOwners(bytes5 catId) external view returns(address);
function rescueOrder(uint256 rescueIndex) external view returns(bytes5 catId);
}
|
return remaining ETH (if any) return remaining tokens (if any)
|
function _returnDust(address[] memory _tokens) internal {
assembly {
if gt(selfbalance(), 0) {
let callStatus := call(
gas(),
caller(),
selfbalance(),
0,
0,
0,
0
)
}
}
for (uint256 i = 0; i < _tokens.length; i++) {
IERC20(_tokens[i]).transfer(_msgSender(), IERC20(_tokens[i]).balanceOf(address(this)));
}
}
| 1,346,559
|
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol";
import "./interfaces/IValidatorShare.sol";
import "./interfaces/INodeOperatorRegistry.sol";
import "./interfaces/IStakeManager.sol";
import "./interfaces/IPoLidoNFT.sol";
import "./interfaces/IFxStateRootTunnel.sol";
import "./interfaces/IStMATIC.sol";
contract StMATIC is
IStMATIC,
ERC20Upgradeable,
AccessControlUpgradeable,
PausableUpgradeable
{
event SubmitEvent(address indexed _from, uint256 indexed _amount);
event RequestWithdrawEvent(address indexed _from, uint256 indexed _amount);
event DistributeRewardsEvent(uint256 indexed _amount);
event WithdrawTotalDelegatedEvent(
address indexed _from,
uint256 indexed _amount
);
event DelegateEvent(
uint256 indexed _amountDelegated,
uint256 indexed _remainder
);
event ClaimTokensEvent(
address indexed _from,
uint256 indexed _id,
uint256 indexed _amountClaimed,
uint256 _amountBurned
);
using SafeERC20Upgradeable for IERC20Upgradeable;
INodeOperatorRegistry public override nodeOperatorRegistry;
FeeDistribution public override entityFees;
IStakeManager public override stakeManager;
IPoLidoNFT public override poLidoNFT;
IFxStateRootTunnel public override fxStateRootTunnel;
string public override version;
address public override dao;
address public override insurance;
address public override token;
uint256 public override lastWithdrawnValidatorId;
uint256 public override totalBuffered;
uint256 public override delegationLowerBound;
uint256 public override rewardDistributionLowerBound;
uint256 public override reservedFunds;
uint256 public override submitThreshold;
bool public override submitHandler;
mapping(uint256 => RequestWithdraw) public override token2WithdrawRequest;
bytes32 public constant override DAO = keccak256("DAO");
/**
* @param _nodeOperatorRegistry - Address of the node operator registry
* @param _token - Address of MATIC token on Ethereum Mainnet
* @param _dao - Address of the DAO
* @param _insurance - Address of the insurance
* @param _stakeManager - Address of the stake manager
* @param _poLidoNFT - Address of the stMATIC NFT
* @param _fxStateRootTunnel - Address of the FxStateRootTunnel
*/
function initialize(
address _nodeOperatorRegistry,
address _token,
address _dao,
address _insurance,
address _stakeManager,
address _poLidoNFT,
address _fxStateRootTunnel,
uint256 _submitThreshold
) external override initializer {
__AccessControl_init();
__Pausable_init();
__ERC20_init("Staked MATIC", "stMATIC");
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
_setupRole(DAO, _dao);
nodeOperatorRegistry = INodeOperatorRegistry(_nodeOperatorRegistry);
stakeManager = IStakeManager(_stakeManager);
poLidoNFT = IPoLidoNFT(_poLidoNFT);
fxStateRootTunnel = IFxStateRootTunnel(_fxStateRootTunnel);
dao = _dao;
token = _token;
insurance = _insurance;
entityFees = FeeDistribution(25, 50, 25);
submitThreshold = _submitThreshold;
submitHandler = true;
}
/**
* @dev Send funds to StMATIC contract and mints StMATIC to msg.sender
* @notice Requires that msg.sender has approved _amount of MATIC to this contract
* @param _amount - Amount of MATIC sent from msg.sender to this contract
* @return Amount of StMATIC shares generated
*/
function submit(uint256 _amount)
external
override
whenNotPaused
returns (uint256)
{
require(_amount > 0, "Invalid amount");
if (submitHandler) {
require(
_amount + getTotalPooledMatic() <= submitThreshold,
"Submit threshold reached"
);
}
IERC20Upgradeable(token).safeTransferFrom(
msg.sender,
address(this),
_amount
);
(
uint256 amountToMint,
uint256 totalShares,
uint256 totalPooledMatic
) = convertMaticToStMatic(_amount);
_mint(msg.sender, amountToMint);
totalBuffered += _amount;
fxStateRootTunnel.sendMessageToChild(
abi.encode(totalShares + amountToMint, totalPooledMatic + _amount)
);
emit SubmitEvent(msg.sender, _amount);
return amountToMint;
}
/**
* @dev Stores users request to withdraw into a RequestWithdraw struct
* @param _amount - Amount of StMATIC that is requested to withdraw
*/
function requestWithdraw(uint256 _amount) external override whenNotPaused {
require(_amount > 0, "Invalid amount");
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(false, true);
uint256 operatorInfosLength = operatorInfos.length;
uint256 tokenId;
(
uint256 totalAmount2WithdrawInMatic,
uint256 totalShares,
uint256 totalPooledMATIC
) = convertStMaticToMatic(_amount);
uint256 currentAmount2WithdrawInMatic = totalAmount2WithdrawInMatic;
uint256 totalDelegated = getTotalStakeAcrossAllValidators();
uint256 minValidatorBalance = _getMinValidatorBalance(operatorInfos);
uint256 allowedAmount2RequestFromValidators = 0;
if (totalDelegated != 0) {
require(
(totalDelegated + totalBuffered) >=
currentAmount2WithdrawInMatic +
minValidatorBalance *
operatorInfosLength,
"Too much to withdraw"
);
allowedAmount2RequestFromValidators =
totalDelegated -
minValidatorBalance *
operatorInfosLength;
} else {
require(
totalBuffered >= currentAmount2WithdrawInMatic,
"Too much to withdraw"
);
}
while (currentAmount2WithdrawInMatic != 0) {
tokenId = poLidoNFT.mint(msg.sender);
if (allowedAmount2RequestFromValidators != 0) {
if (lastWithdrawnValidatorId > operatorInfosLength - 1) {
lastWithdrawnValidatorId = 0;
}
address validatorShare = operatorInfos[lastWithdrawnValidatorId]
.validatorShare;
(uint256 validatorBalance, ) = IValidatorShare(validatorShare)
.getTotalStake(address(this));
if (validatorBalance <= minValidatorBalance) {
lastWithdrawnValidatorId++;
continue;
}
uint256 allowedAmount2Withdraw = validatorBalance -
minValidatorBalance;
uint256 amount2WithdrawFromValidator = (allowedAmount2Withdraw <=
currentAmount2WithdrawInMatic)
? allowedAmount2Withdraw
: currentAmount2WithdrawInMatic;
sellVoucher_new(
validatorShare,
amount2WithdrawFromValidator,
type(uint256).max
);
token2WithdrawRequest[tokenId] = RequestWithdraw(
0,
IValidatorShare(validatorShare).unbondNonces(address(this)),
stakeManager.epoch() + stakeManager.withdrawalDelay(),
validatorShare
);
allowedAmount2RequestFromValidators -= amount2WithdrawFromValidator;
currentAmount2WithdrawInMatic -= amount2WithdrawFromValidator;
lastWithdrawnValidatorId++;
} else {
token2WithdrawRequest[tokenId] = RequestWithdraw(
currentAmount2WithdrawInMatic,
0,
stakeManager.epoch() + stakeManager.withdrawalDelay(),
address(0)
);
reservedFunds += currentAmount2WithdrawInMatic;
currentAmount2WithdrawInMatic = 0;
}
}
_burn(msg.sender, _amount);
fxStateRootTunnel.sendMessageToChild(
abi.encode(
totalShares - _amount,
totalPooledMATIC - totalAmount2WithdrawInMatic
)
);
emit RequestWithdrawEvent(msg.sender, _amount);
}
/**
* @notice This will be included in the cron job
* @dev Delegates tokens to validator share contract
*/
function delegate() external override whenNotPaused {
require(
totalBuffered > delegationLowerBound + reservedFunds,
"Amount to delegate lower than minimum"
);
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(true, false);
uint256 operatorInfosLength = operatorInfos.length;
require(operatorInfosLength > 0, "No operator shares, cannot delegate");
uint256 availableAmountToDelegate = totalBuffered - reservedFunds;
uint256 maxDelegateLimitsSum;
uint256 remainder;
for (uint256 i = 0; i < operatorInfosLength; i++) {
maxDelegateLimitsSum += operatorInfos[i].maxDelegateLimit;
}
require(maxDelegateLimitsSum > 0, "maxDelegateLimitsSum=0");
uint256 totalToDelegatedAmount = maxDelegateLimitsSum <=
availableAmountToDelegate
? maxDelegateLimitsSum
: availableAmountToDelegate;
IERC20Upgradeable(token).safeApprove(address(stakeManager), 0);
IERC20Upgradeable(token).safeApprove(
address(stakeManager),
totalToDelegatedAmount
);
uint256 amountDelegated;
for (uint256 i = 0; i < operatorInfosLength; i++) {
uint256 amountToDelegatePerOperator = (operatorInfos[i]
.maxDelegateLimit * totalToDelegatedAmount) /
maxDelegateLimitsSum;
buyVoucher(
operatorInfos[i].validatorShare,
amountToDelegatePerOperator,
0
);
amountDelegated += amountToDelegatePerOperator;
}
remainder = availableAmountToDelegate - amountDelegated;
totalBuffered = remainder + reservedFunds;
emit DelegateEvent(amountDelegated, remainder);
}
/**
* @dev Claims tokens from validator share and sends them to the
* user if his request is in the userToWithdrawRequest
* @param _tokenId - Id of the token that wants to be claimed
*/
function claimTokens(uint256 _tokenId) external override whenNotPaused {
require(poLidoNFT.isApprovedOrOwner(msg.sender, _tokenId), "Not owner");
RequestWithdraw storage usersRequest = token2WithdrawRequest[_tokenId];
require(
stakeManager.epoch() >= usersRequest.requestEpoch,
"Not able to claim yet"
);
poLidoNFT.burn(_tokenId);
uint256 amountToClaim;
if (usersRequest.validatorAddress != address(0)) {
uint256 balanceBeforeClaim = IERC20Upgradeable(token).balanceOf(
address(this)
);
unstakeClaimTokens_new(
usersRequest.validatorAddress,
usersRequest.validatorNonce
);
amountToClaim =
IERC20Upgradeable(token).balanceOf(address(this)) -
balanceBeforeClaim;
} else {
amountToClaim = usersRequest.amount2WithdrawFromStMATIC;
reservedFunds -= amountToClaim;
totalBuffered -= amountToClaim;
}
IERC20Upgradeable(token).safeTransfer(msg.sender, amountToClaim);
emit ClaimTokensEvent(msg.sender, _tokenId, amountToClaim, 0);
}
/**
* @dev Distributes rewards claimed from validator shares based on fees defined in entityFee
*/
function distributeRewards() external override whenNotPaused {
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(true, false);
uint256 operatorInfosLength = operatorInfos.length;
for (uint256 i = 0; i < operatorInfosLength; i++) {
IValidatorShare validatorShare = IValidatorShare(
operatorInfos[i].validatorShare
);
uint256 stMaticReward = validatorShare.getLiquidRewards(
address(this)
);
uint256 rewardThreshold = validatorShare.minAmount();
if (stMaticReward >= rewardThreshold) {
validatorShare.withdrawRewards();
}
}
uint256 totalRewards = (
(IERC20Upgradeable(token).balanceOf(address(this)) - totalBuffered)
) / 10;
require(
totalRewards > rewardDistributionLowerBound,
"Amount to distribute lower than minimum"
);
uint256 balanceBeforeDistribution = IERC20Upgradeable(token).balanceOf(
address(this)
);
uint256 daoRewards = (totalRewards * entityFees.dao) / 100;
uint256 insuranceRewards = (totalRewards * entityFees.insurance) / 100;
uint256 operatorsRewards = (totalRewards * entityFees.operators) / 100;
uint256 operatorReward = operatorsRewards / operatorInfosLength;
IERC20Upgradeable(token).safeTransfer(dao, daoRewards);
IERC20Upgradeable(token).safeTransfer(insurance, insuranceRewards);
for (uint256 i = 0; i < operatorInfosLength; i++) {
IERC20Upgradeable(token).safeTransfer(
operatorInfos[i].rewardAddress,
operatorReward
);
}
uint256 currentBalance = IERC20Upgradeable(token).balanceOf(
address(this)
);
uint256 totalDistributed = balanceBeforeDistribution - currentBalance;
// Add the remainder to totalBuffered
totalBuffered = currentBalance;
emit DistributeRewardsEvent(totalDistributed);
}
/**
* @notice Only NodeOperatorRegistry can call this function
* @dev Withdraws funds from unstaked validator
* @param _validatorShare - Address of the validator share that will be withdrawn
*/
function withdrawTotalDelegated(address _validatorShare) external override {
require(
msg.sender == address(nodeOperatorRegistry),
"Not a node operator"
);
(uint256 stakedAmount, ) = getTotalStake(
IValidatorShare(_validatorShare)
);
if (stakedAmount == 0) {
return;
}
uint256 tokenId = poLidoNFT.mint(address(this));
sellVoucher_new(_validatorShare, stakedAmount, type(uint256).max);
token2WithdrawRequest[tokenId] = RequestWithdraw(
uint256(0),
IValidatorShare(_validatorShare).unbondNonces(address(this)),
stakeManager.epoch() + stakeManager.withdrawalDelay(),
_validatorShare
);
fxStateRootTunnel.sendMessageToChild(
abi.encode(totalSupply(), getTotalPooledMatic())
);
emit WithdrawTotalDelegatedEvent(_validatorShare, stakedAmount);
}
/**
* @dev Claims tokens from validator share and sends them to the
* StMATIC contract
* @param _tokenId - Id of the token that is supposed to be claimed
*/
function claimTokens2StMatic(uint256 _tokenId)
external
override
whenNotPaused
{
RequestWithdraw storage lidoRequests = token2WithdrawRequest[_tokenId];
require(
poLidoNFT.ownerOf(_tokenId) == address(this),
"Not owner of the NFT"
);
poLidoNFT.burn(_tokenId);
require(
stakeManager.epoch() >= lidoRequests.requestEpoch,
"Not able to claim yet"
);
uint256 balanceBeforeClaim = IERC20Upgradeable(token).balanceOf(
address(this)
);
unstakeClaimTokens_new(
lidoRequests.validatorAddress,
lidoRequests.validatorNonce
);
uint256 claimedAmount = IERC20Upgradeable(token).balanceOf(
address(this)
) - balanceBeforeClaim;
totalBuffered += claimedAmount;
fxStateRootTunnel.sendMessageToChild(
abi.encode(totalSupply(), getTotalPooledMatic())
);
emit ClaimTokensEvent(address(this), _tokenId, claimedAmount, 0);
}
/**
* @dev Flips the pause state
*/
function togglePause() external override onlyRole(DEFAULT_ADMIN_ROLE) {
paused() ? _unpause() : _pause();
}
////////////////////////////////////////////////////////////
///// ///
///// ***ValidatorShare API*** ///
///// ///
////////////////////////////////////////////////////////////
/**
* @dev API for delegated buying vouchers from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @param _amount - Amount of MATIC to use for buying vouchers
* @param _minSharesToMint - Minimum of shares that is bought with _amount of MATIC
* @return Actual amount of MATIC used to buy voucher, might differ from _amount because of _minSharesToMint
*/
function buyVoucher(
address _validatorShare,
uint256 _amount,
uint256 _minSharesToMint
) private returns (uint256) {
uint256 amountSpent = IValidatorShare(_validatorShare).buyVoucher(
_amount,
_minSharesToMint
);
return amountSpent;
}
/**
* @dev API for delegated restaking rewards to validatorShare
* @param _validatorShare - Address of validatorShare contract
*/
function restake(address _validatorShare) private {
IValidatorShare(_validatorShare).restake();
}
/**
* @dev API for delegated unstaking and claiming tokens from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @param _unbondNonce - Unbond nonce
*/
function unstakeClaimTokens_new(
address _validatorShare,
uint256 _unbondNonce
) private {
IValidatorShare(_validatorShare).unstakeClaimTokens_new(_unbondNonce);
}
/**
* @dev API for delegated selling vouchers from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @param _claimAmount - Amount of MATIC to claim
* @param _maximumSharesToBurn - Maximum amount of shares to burn
*/
function sellVoucher_new(
address _validatorShare,
uint256 _claimAmount,
uint256 _maximumSharesToBurn
) private {
IValidatorShare(_validatorShare).sellVoucher_new(
_claimAmount,
_maximumSharesToBurn
);
}
/**
* @dev API for getting total stake of this contract from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @return Total stake of this contract and MATIC -> share exchange rate
*/
function getTotalStake(IValidatorShare _validatorShare)
public
view
override
returns (uint256, uint256)
{
return _validatorShare.getTotalStake(address(this));
}
/**
* @dev API for liquid rewards of this contract from validatorShare
* @param _validatorShare - Address of validatorShare contract
* @return Liquid rewards of this contract
*/
function getLiquidRewards(IValidatorShare _validatorShare)
external
view
override
returns (uint256)
{
return _validatorShare.getLiquidRewards(address(this));
}
////////////////////////////////////////////////////////////
///// ///
///// ***Helpers & Utilities*** ///
///// ///
////////////////////////////////////////////////////////////
/**
* @dev Helper function for that returns total pooled MATIC
* @return Total pooled MATIC
*/
function getTotalStakeAcrossAllValidators()
public
view
override
returns (uint256)
{
uint256 totalStake;
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(false, true);
uint256 operatorInfosLength = operatorInfos.length;
for (uint256 i = 0; i < operatorInfosLength; i++) {
(uint256 currValidatorShare, ) = getTotalStake(
IValidatorShare(operatorInfos[i].validatorShare)
);
totalStake += currValidatorShare;
}
return totalStake;
}
/**
* @dev Function that calculates total pooled Matic
* @return Total pooled Matic
*/
function getTotalPooledMatic() public view override returns (uint256) {
uint256 totalStaked = getTotalStakeAcrossAllValidators();
return totalStaked + totalBuffered - reservedFunds;
}
/**
* @dev Function that converts arbitrary stMATIC to Matic
* @param _balance - Balance in stMATIC
* @return Balance in Matic, totalShares and totalPooledMATIC
*/
function convertStMaticToMatic(uint256 _balance)
public
view
override
returns (
uint256,
uint256,
uint256
)
{
uint256 totalShares = totalSupply();
totalShares = totalShares == 0 ? 1 : totalShares;
uint256 totalPooledMATIC = getTotalPooledMatic();
totalPooledMATIC = totalPooledMATIC == 0 ? 1 : totalPooledMATIC;
uint256 balanceInMATIC = (_balance * totalPooledMATIC) / totalShares;
return (balanceInMATIC, totalShares, totalPooledMATIC);
}
/**
* @dev Function that converts arbitrary Matic to stMATIC
* @param _balance - Balance in Matic
* @return Balance in stMATIC, totalShares and totalPooledMATIC
*/
function convertMaticToStMatic(uint256 _balance)
public
view
override
returns (
uint256,
uint256,
uint256
)
{
uint256 totalShares = totalSupply();
totalShares = totalShares == 0 ? 1 : totalShares;
uint256 totalPooledMatic = getTotalPooledMatic();
totalPooledMatic = totalPooledMatic == 0 ? 1 : totalPooledMatic;
uint256 balanceInStMatic = (_balance * totalShares) / totalPooledMatic;
return (balanceInStMatic, totalShares, totalPooledMatic);
}
/**
* @dev Function that calculates minimal allowed validator balance (lower bound)
* @return Minimal validator balance in MATIC
*/
function getMinValidatorBalance() external view override returns (uint256) {
Operator.OperatorInfo[] memory operatorInfos = nodeOperatorRegistry
.getOperatorInfos(false, true);
return _getMinValidatorBalance(operatorInfos);
}
function _getMinValidatorBalance(Operator.OperatorInfo[] memory operatorInfos) private view returns (uint256) {
uint256 operatorInfosLength = operatorInfos.length;
uint256 minValidatorBalance = type(uint256).max;
for (uint256 i = 0; i < operatorInfosLength; i++) {
(uint256 validatorShare, ) = getTotalStake(
IValidatorShare(operatorInfos[i].validatorShare)
);
// 10% of current validatorShare
uint256 minValidatorBalanceCurrent = validatorShare / 10;
if (
minValidatorBalanceCurrent != 0 &&
minValidatorBalanceCurrent < minValidatorBalance
) {
minValidatorBalance = minValidatorBalanceCurrent;
}
}
return minValidatorBalance;
}
////////////////////////////////////////////////////////////
///// ///
///// ***Setters*** ///
///// ///
////////////////////////////////////////////////////////////
/**
* @dev Function that sets entity fees
* @notice Callable only by dao
* @param _daoFee - DAO fee in %
* @param _operatorsFee - Operator fees in %
* @param _insuranceFee - Insurance fee in %
*/
function setFees(
uint8 _daoFee,
uint8 _operatorsFee,
uint8 _insuranceFee
) external override onlyRole(DAO) {
require(
_daoFee + _operatorsFee + _insuranceFee == 100,
"sum(fee)!=100"
);
entityFees.dao = _daoFee;
entityFees.operators = _operatorsFee;
entityFees.insurance = _insuranceFee;
}
/**
* @dev Function that sets new dao address
* @notice Callable only by dao
* @param _address - New dao address
*/
function setDaoAddress(address _address) external override onlyRole(DAO) {
revokeRole(DAO, dao);
dao = _address;
_setupRole(DAO, dao);
}
/**
* @dev Function that sets new insurance address
* @notice Callable only by dao
* @param _address - New insurance address
*/
function setInsuranceAddress(address _address)
external
override
onlyRole(DAO)
{
insurance = _address;
}
/**
* @dev Function that sets new node operator address
* @notice Only callable by dao
* @param _address - New node operator address
*/
function setNodeOperatorRegistryAddress(address _address)
external
override
onlyRole(DAO)
{
nodeOperatorRegistry = INodeOperatorRegistry(_address);
}
/**
* @dev Function that sets new lower bound for delegation
* @notice Only callable by dao
* @param _delegationLowerBound - New lower bound for delegation
*/
function setDelegationLowerBound(uint256 _delegationLowerBound)
external
override
onlyRole(DAO)
{
delegationLowerBound = _delegationLowerBound;
}
/**
* @dev Function that sets new lower bound for rewards distribution
* @notice Only callable by dao
* @param _rewardDistributionLowerBound - New lower bound for rewards distribution
*/
function setRewardDistributionLowerBound(
uint256 _rewardDistributionLowerBound
) external override onlyRole(DAO) {
rewardDistributionLowerBound = _rewardDistributionLowerBound;
}
/**
* @dev Function that sets the poLidoNFT address
* @param _poLidoNFT new poLidoNFT address
*/
function setPoLidoNFT(address _poLidoNFT) external override onlyRole(DAO) {
poLidoNFT = IPoLidoNFT(_poLidoNFT);
}
/**
* @dev Function that sets the fxStateRootTunnel address
* @param _fxStateRootTunnel address of fxStateRootTunnel
*/
function setFxStateRootTunnel(address _fxStateRootTunnel)
external
override
onlyRole(DAO)
{
fxStateRootTunnel = IFxStateRootTunnel(_fxStateRootTunnel);
}
/**
* @dev Function that sets the submitThreshold
* @param _submitThreshold new value for submit threshold
*/
function setSubmitThreshold(uint256 _submitThreshold)
external
override
onlyRole(DAO)
{
submitThreshold = _submitThreshold;
}
/**
* @dev Function that sets the submitHandler value to its NOT value
*/
function flipSubmitHandler() external override onlyRole(DAO) {
submitHandler = !submitHandler;
}
/**
* @dev Function that sets the new version
* @param _version - New version that will be set
*/
function setVersion(string calldata _version)
external
override
onlyRole(DEFAULT_ADMIN_ROLE)
{
version = _version;
}
/**
* @dev Function that retrieves the amount of matic that will be claimed from the NFT token
* @param _tokenId - Id of the PolidoNFT
*/
function getMaticFromTokenId(uint256 _tokenId)
external
view
override
returns (uint256)
{
RequestWithdraw memory requestData = token2WithdrawRequest[_tokenId];
IValidatorShare validatorShare = IValidatorShare(
requestData.validatorAddress
);
uint256 validatorId = validatorShare.validatorId();
uint256 exchangeRatePrecision = validatorId < 8 ? 100 : 10**29;
uint256 withdrawExchangeRate = validatorShare.withdrawExchangeRate();
IValidatorShare.DelegatorUnbond memory unbond = validatorShare
.unbonds_new(address(this), requestData.validatorNonce);
return (withdrawExchangeRate * unbond.shares) / exchangeRatePrecision;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
import "./IERC20Upgradeable.sol";
import "./extensions/IERC20MetadataUpgradeable.sol";
import "../../utils/ContextUpgradeable.sol";
import "../../proxy/utils/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 Contracts guidelines: functions revert
* instead 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, IERC20MetadataUpgradeable {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal onlyInitializing {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
unchecked {
_approve(sender, _msgSender(), currentAllowance - amount);
}
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[sender] = senderBalance - amount;
}
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
_afterTokenTransfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
uint256[45] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControlUpgradeable.sol";
import "../utils/ContextUpgradeable.sol";
import "../utils/StringsUpgradeable.sol";
import "../utils/introspection/ERC165Upgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable {
function __AccessControl_init() internal onlyInitializing {
__Context_init_unchained();
__ERC165_init_unchained();
__AccessControl_init_unchained();
}
function __AccessControl_init_unchained() internal onlyInitializing {
}
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
StringsUpgradeable.toHexString(uint160(account), 20),
" is missing role ",
StringsUpgradeable.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface 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
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
import "../../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using AddressUpgradeable for address;
function safeTransfer(
IERC20Upgradeable token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20Upgradeable token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20Upgradeable token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/Pausable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal onlyInitializing {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal onlyInitializing {
_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-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
interface IValidatorShare {
struct DelegatorUnbond {
uint256 shares;
uint256 withdrawEpoch;
}
function unbondNonces(address _address) external view returns (uint256);
function activeAmount() external view returns (uint256);
function validatorId() external view returns (uint256);
function withdrawExchangeRate() external view returns (uint256);
function withdrawRewards() external;
function unstakeClaimTokens() external;
function minAmount() external view returns (uint256);
function getLiquidRewards(address user) external view returns (uint256);
function delegation() external view returns (bool);
function updateDelegation(bool _delegation) external;
function buyVoucher(uint256 _amount, uint256 _minSharesToMint)
external
returns (uint256);
function sellVoucher_new(uint256 claimAmount, uint256 maximumSharesToBurn)
external;
function unstakeClaimTokens_new(uint256 unbondNonce) external;
function unbonds_new(address _address, uint256 _unbondNonce)
external
view
returns (DelegatorUnbond memory);
function getTotalStake(address user)
external
view
returns (uint256, uint256);
function owner() external view returns (address);
function restake() external returns (uint256, uint256);
function unlock() external;
function lock() external;
function drain(
address token,
address payable destination,
uint256 amount
) external;
function slash(uint256 _amount) external;
function migrateOut(address user, uint256 amount) external;
function migrateIn(address user, uint256 amount) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "../lib/Operator.sol";
/// @title INodeOperatorRegistry
/// @author 2021 ShardLabs
/// @notice Node operator registry interface
interface INodeOperatorRegistry {
/// @notice Allows to add a new node operator to the system.
/// @param _name the node operator name.
/// @param _rewardAddress public address used for ACL and receive rewards.
/// @param _signerPubkey public key used on heimdall len 64 bytes.
function addOperator(
string memory _name,
address _rewardAddress,
bytes memory _signerPubkey
) external;
/// @notice Allows to stop a node operator.
/// @param _operatorId node operator id.
function stopOperator(uint256 _operatorId) external;
/// @notice Allows to remove a node operator from the system.
/// @param _operatorId node operator id.
function removeOperator(uint256 _operatorId) external;
/// @notice Allows a staked validator to join the system.
function joinOperator() external;
/// @notice Allows to stake an operator on the Polygon stakeManager.
/// This function calls Polygon transferFrom so the totalAmount(_amount + _heimdallFee)
/// has to be approved first.
/// @param _amount amount to stake.
/// @param _heimdallFee heimdallFee to stake.
function stake(uint256 _amount, uint256 _heimdallFee) external;
/// @notice Restake Matics for a validator on polygon stake manager.
/// @param _amount amount to stake.
/// @param _restakeRewards restake rewards.
function restake(uint256 _amount, bool _restakeRewards) external;
/// @notice Allows the operator's owner to migrate the NFT. This can be done only
/// if the DAO stopped the operator.
function migrate() external;
/// @notice Allows to unstake an operator from the stakeManager. After the withdraw_delay
/// the operator owner can call claimStake func to withdraw the staked tokens.
function unstake() external;
/// @notice Allows to topup heimdall fees on polygon stakeManager.
/// @param _heimdallFee amount to topup.
function topUpForFee(uint256 _heimdallFee) external;
/// @notice Allows to claim staked tokens on the stake Manager after the end of the
/// withdraw delay
function unstakeClaim() external;
/// @notice Allows an owner to withdraw rewards from the stakeManager.
function withdrawRewards() external;
/// @notice Allows to update the signer pubkey
/// @param _signerPubkey update signer public key
function updateSigner(bytes memory _signerPubkey) external;
/// @notice Allows to claim the heimdall fees staked by the owner of the operator
/// @param _accumFeeAmount accumulated fees amount
/// @param _index index
/// @param _proof proof
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof
) external;
/// @notice Allows to unjail a validator and switch from UNSTAKE status to STAKED
function unjail() external;
/// @notice Allows an operator's owner to set the operator name.
function setOperatorName(string memory _name) external;
/// @notice Allows an operator's owner to set the operator rewardAddress.
function setOperatorRewardAddress(address _rewardAddress) external;
/// @notice Allows the DAO to set _defaultMaxDelegateLimit.
function setDefaultMaxDelegateLimit(uint256 _defaultMaxDelegateLimit)
external;
/// @notice Allows the DAO to set _maxDelegateLimit for an operator.
function setMaxDelegateLimit(uint256 _operatorId, uint256 _maxDelegateLimit)
external;
/// @notice Allows the DAO to set _commissionRate.
function setCommissionRate(uint256 _commissionRate) external;
/// @notice Allows the DAO to set _commissionRate for an operator.
/// @param _operatorId id of the operator
/// @param _newCommissionRate new commission rate
function updateOperatorCommissionRate(
uint256 _operatorId,
uint256 _newCommissionRate
) external;
/// @notice Allows the DAO to set _minAmountStake and _minHeimdallFees.
function setStakeAmountAndFees(
uint256 _minAmountStake,
uint256 _minHeimdallFees
) external;
/// @notice Allows to pause/unpause the node operator contract.
function togglePause() external;
/// @notice Allows the DAO to enable/disable restake.
function setRestake(bool _restake) external;
/// @notice Allows the DAO to set stMATIC contract.
function setStMATIC(address _stMATIC) external;
/// @notice Allows the DAO to set validator factory contract.
function setValidatorFactory(address _validatorFactory) external;
/// @notice Allows the DAO to set stake manager contract.
function setStakeManager(address _stakeManager) external;
/// @notice Allows to set contract version.
function setVersion(string memory _version) external;
/// @notice Get the stMATIC contract addresses
function getContracts()
external
view
returns (
address _validatorFactory,
address _stakeManager,
address _polygonERC20,
address _stMATIC
);
/// @notice Allows to get stats.
function getState()
external
view
returns (
uint256 _totalNodeOperator,
uint256 _totalInactiveNodeOperator,
uint256 _totalActiveNodeOperator,
uint256 _totalStoppedNodeOperator,
uint256 _totalUnstakedNodeOperator,
uint256 _totalClaimedNodeOperator,
uint256 _totalExitNodeOperator,
uint256 _totalSlashedNodeOperator,
uint256 _totalEjectedNodeOperator
);
/// @notice Allows to get a list of operatorInfo.
function getOperatorInfos(bool _delegation, bool _allActive)
external
view
returns (Operator.OperatorInfo[] memory);
/// @notice Allows to get all the operator ids.
function getOperatorIds() external view returns (uint256[] memory);
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
/// @title polygon stake manager interface.
/// @author 2021 ShardLabs
/// @notice User to interact with the polygon stake manager.
interface IStakeManager {
/// @notice Stake a validator on polygon stake manager.
/// @param user user that own the validator in our case the validator contract.
/// @param amount amount to stake.
/// @param heimdallFee heimdall fees.
/// @param acceptDelegation accept delegation.
/// @param signerPubkey signer publickey used in heimdall node.
function stakeFor(
address user,
uint256 amount,
uint256 heimdallFee,
bool acceptDelegation,
bytes memory signerPubkey
) external;
/// @notice Restake Matics for a validator on polygon stake manager.
/// @param validatorId validator id.
/// @param amount amount to stake.
/// @param stakeRewards restake rewards.
function restake(
uint256 validatorId,
uint256 amount,
bool stakeRewards
) external;
/// @notice Request unstake a validator.
/// @param validatorId validator id.
function unstake(uint256 validatorId) external;
/// @notice Increase the heimdall fees.
/// @param user user that own the validator in our case the validator contract.
/// @param heimdallFee heimdall fees.
function topUpForFee(address user, uint256 heimdallFee) external;
/// @notice Get the validator id using the user address.
/// @param user user that own the validator in our case the validator contract.
/// @return return the validator id
function getValidatorId(address user) external view returns (uint256);
/// @notice get the validator contract used for delegation.
/// @param validatorId validator id.
/// @return return the address of the validator contract.
function getValidatorContract(uint256 validatorId)
external
view
returns (address);
/// @notice Withdraw accumulated rewards
/// @param validatorId validator id.
function withdrawRewards(uint256 validatorId) external;
/// @notice Get validator total staked.
/// @param validatorId validator id.
function validatorStake(uint256 validatorId)
external
view
returns (uint256);
/// @notice Allows to unstake the staked tokens on the stakeManager.
/// @param validatorId validator id.
function unstakeClaim(uint256 validatorId) external;
/// @notice Allows to update the signer pubkey
/// @param _validatorId validator id
/// @param _signerPubkey update signer public key
function updateSigner(uint256 _validatorId, bytes memory _signerPubkey)
external;
/// @notice Allows to claim the heimdall fees.
/// @param _accumFeeAmount accumulated fees amount
/// @param _index index
/// @param _proof proof
function claimFee(
uint256 _accumFeeAmount,
uint256 _index,
bytes memory _proof
) external;
/// @notice Allows to update the commision rate of a validator
/// @param _validatorId operator id
/// @param _newCommissionRate commission rate
function updateCommissionRate(
uint256 _validatorId,
uint256 _newCommissionRate
) external;
/// @notice Allows to unjail a validator.
/// @param _validatorId id of the validator that is to be unjailed
function unjail(uint256 _validatorId) external;
/// @notice Returns a withdrawal delay.
function withdrawalDelay() external view returns (uint256);
/// @notice Transfers amount from delegator
function delegationDeposit(
uint256 validatorId,
uint256 amount,
address delegator
) external returns (bool);
function epoch() external view returns (uint256);
enum Status {
Inactive,
Active,
Locked,
Unstaked
}
struct Validator {
uint256 amount;
uint256 reward;
uint256 activationEpoch;
uint256 deactivationEpoch;
uint256 jailTime;
address signer;
address contractAddress;
Status status;
uint256 commissionRate;
uint256 lastCommissionUpdate;
uint256 delegatorsReward;
uint256 delegatedAmount;
uint256 initialRewardPerStake;
}
function validators(uint256 _index)
external
view
returns (Validator memory);
/// @notice Returns the address of the nft contract
function NFTContract() external view returns (address);
/// @notice Returns the validator accumulated rewards on stake manager.
function validatorReward(uint256 validatorId)
external
view
returns (uint256);
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
/// @title PoLidoNFT interface.
/// @author 2021 ShardLabs
interface IPoLidoNFT is IERC721Upgradeable {
function mint(address _to) external returns (uint256);
function burn(uint256 _tokenId) external;
function isApprovedOrOwner(address _spender, uint256 _tokenId)
external
view
returns (bool);
function setStMATIC(address _stMATIC) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
interface IFxStateRootTunnel {
function latestData() external view returns (bytes memory);
function setFxChildTunnel(address _fxChildTunnel) external;
function sendMessageToChild(bytes memory message) external;
function setStMATIC(address _stMATIC) external;
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./IValidatorShare.sol";
import "./INodeOperatorRegistry.sol";
import "./INodeOperatorRegistry.sol";
import "./IStakeManager.sol";
import "./IPoLidoNFT.sol";
import "./IFxStateRootTunnel.sol";
/// @title StMATIC interface.
/// @author 2021 ShardLabs
interface IStMATIC is IERC20Upgradeable {
struct RequestWithdraw {
uint256 amount2WithdrawFromStMATIC;
uint256 validatorNonce;
uint256 requestEpoch;
address validatorAddress;
}
struct FeeDistribution {
uint8 dao;
uint8 operators;
uint8 insurance;
}
function withdrawTotalDelegated(address _validatorShare) external;
function nodeOperatorRegistry() external returns (INodeOperatorRegistry);
function entityFees()
external
returns (
uint8,
uint8,
uint8
);
function getMaticFromTokenId(uint256 _tokenId)
external
view
returns (uint256);
function stakeManager() external view returns (IStakeManager);
function poLidoNFT() external view returns (IPoLidoNFT);
function fxStateRootTunnel() external view returns (IFxStateRootTunnel);
function version() external view returns (string memory);
function dao() external view returns (address);
function insurance() external view returns (address);
function token() external view returns (address);
function lastWithdrawnValidatorId() external view returns (uint256);
function totalBuffered() external view returns (uint256);
function delegationLowerBound() external view returns (uint256);
function rewardDistributionLowerBound() external view returns (uint256);
function reservedFunds() external view returns (uint256);
function submitThreshold() external view returns (uint256);
function submitHandler() external view returns (bool);
function getMinValidatorBalance() external view returns (uint256);
function token2WithdrawRequest(uint256 _requestId)
external
view
returns (
uint256,
uint256,
uint256,
address
);
function DAO() external view returns (bytes32);
function initialize(
address _nodeOperatorRegistry,
address _token,
address _dao,
address _insurance,
address _stakeManager,
address _poLidoNFT,
address _fxStateRootTunnel,
uint256 _submitThreshold
) external;
function submit(uint256 _amount) external returns (uint256);
function requestWithdraw(uint256 _amount) external;
function delegate() external;
function claimTokens(uint256 _tokenId) external;
function distributeRewards() external;
function claimTokens2StMatic(uint256 _tokenId) external;
function togglePause() external;
function getTotalStake(IValidatorShare _validatorShare)
external
view
returns (uint256, uint256);
function getLiquidRewards(IValidatorShare _validatorShare)
external
view
returns (uint256);
function getTotalStakeAcrossAllValidators() external view returns (uint256);
function getTotalPooledMatic() external view returns (uint256);
function convertStMaticToMatic(uint256 _balance)
external
view
returns (
uint256,
uint256,
uint256
);
function convertMaticToStMatic(uint256 _balance)
external
view
returns (
uint256,
uint256,
uint256
);
function setFees(
uint8 _daoFee,
uint8 _operatorsFee,
uint8 _insuranceFee
) external;
function setDaoAddress(address _address) external;
function setInsuranceAddress(address _address) external;
function setNodeOperatorRegistryAddress(address _address) external;
function setDelegationLowerBound(uint256 _delegationLowerBound) external;
function setRewardDistributionLowerBound(
uint256 _rewardDistributionLowerBound
) external;
function setPoLidoNFT(address _poLidoNFT) external;
function setFxStateRootTunnel(address _fxStateRootTunnel) external;
function setSubmitThreshold(uint256 _submitThreshold) external;
function flipSubmitHandler() external;
function setVersion(string calldata _version) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC20Upgradeable.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20MetadataUpgradeable is IERC20Upgradeable {
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
__Context_init_unchained();
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/utils/Initializable.sol)
pragma solidity ^0.8.0;
import "../../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the
* initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() initializer {}
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, because in other contexts the
// contract may have been reentered.
require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} modifier, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControlUpgradeable {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-FileCopyrightText: 2021 ShardLabs
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.7;
library Operator {
struct OperatorInfo {
uint256 operatorId;
address validatorShare;
uint256 maxDelegateLimit;
address rewardAddress;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
|
Only NodeOperatorRegistry can call this function Withdraws funds from unstaked validator _validatorShare - Address of the validator share that will be withdrawn/
|
function withdrawTotalDelegated(address _validatorShare) external override {
require(
msg.sender == address(nodeOperatorRegistry),
"Not a node operator"
);
(uint256 stakedAmount, ) = getTotalStake(
IValidatorShare(_validatorShare)
);
if (stakedAmount == 0) {
return;
}
uint256 tokenId = poLidoNFT.mint(address(this));
sellVoucher_new(_validatorShare, stakedAmount, type(uint256).max);
token2WithdrawRequest[tokenId] = RequestWithdraw(
uint256(0),
IValidatorShare(_validatorShare).unbondNonces(address(this)),
stakeManager.epoch() + stakeManager.withdrawalDelay(),
_validatorShare
);
fxStateRootTunnel.sendMessageToChild(
abi.encode(totalSupply(), getTotalPooledMatic())
);
emit WithdrawTotalDelegatedEvent(_validatorShare, stakedAmount);
}
| 5,895,454
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./interfaces/Constants.sol";
import { PoolParams } from "./interfaces/Types.sol";
import "./interfaces/IVestingPools.sol";
import "./utils/Claimable.sol";
import "./utils/DefaultOwnable.sol";
import { DefaultOwnerAddress, TokenAddress, VestingPoolsAddress } from "./utils/Linking.sol";
import "./utils/ProxyFactory.sol";
import "./utils/SafeUints.sol";
/**
* @title PoolStakes
* @notice The contract claims (ERC-20) token from the "VestingPools" contract
* and then let "stakeholders" withdraw token amounts prorate to their stakes.
* @dev A few copy of this contract (i.e. proxies created via the {createProxy}
* method) are supposed to run. Every proxy distributes its own "vesting pool",
* so it (the proxy) must be registered with the "VestingPools" contract as the
* "wallet" for that "vesting pool".
*/
contract PoolStakes is
Claimable,
SafeUints,
ProxyFactory,
DefaultOwnable,
Constants
{
// @dev "Stake" of a "stakeholder" in the "vesting pool"
struct Stake {
// token amount allocated for the stakeholder
uint96 allocated;
// token amount released to the stakeholder so far
uint96 released;
}
/// @notice ID of the vesting pool this contract is the "wallet" for
uint16 public poolId;
/// @notice Token amount the vesting pool is set to vest
uint96 public allocation;
/// @notice Token amount allocated from {allocation} to stakeholders so far
/// @dev It is the total amount of all {stakes[..].allocated}
uint96 public allocated;
/// @notice Token amount released to stakeholders so far
/// @dev It is the total amount of all {stakes[..].released}
uint96 public released;
/// @notice Share of vested amount attributable to 1 unit of {allocation}
/// @dev Stakeholder "h" may withdraw from the contract this token amount:
/// factor/SCALE * stakes[h].allocated - stakes[h].released
uint160 public factor;
// mapping from stakeholder address to stake
mapping(address => Stake) public stakes;
event VestingClaimed(uint256 amount);
event Released(address indexed holder, uint256 amount);
event StakeAdded(address indexed holder, uint256 allocated);
event StakeSplit(
address indexed holder,
uint256 allocated,
uint256 released
);
/// @notice Returns address of the token being vested
function token() external view returns (address) {
return address(_getToken());
}
/// @notice Returns address of the {VestingPool} smart contract
function vestingPools() external view returns (address) {
return address(_getVestingPools());
}
/// @notice Returns token amount the specified stakeholder may withdraw now
function releasableAmount(address holder) external view returns (uint256) {
Stake memory stake = _getStake(holder);
return _releasableAmount(stake, uint256(factor));
}
/// @notice Returns token amount the specified stakeholder may withdraw now
/// on top of the {releasableAmount} should {claimVesting} be called
function unclaimedShare(address holder) external view returns (uint256) {
Stake memory stake = _getStake(holder);
uint256 unclaimed = _getVestingPools().releasableAmount(poolId);
return (unclaimed * uint256(stake.allocated)) / allocation;
}
/// @notice Claims vesting to this contract from the vesting pool
function claimVesting() external {
_claimVesting();
}
/////////////////////
//// StakeHolder ////
/////////////////////
/// @notice Sends the releasable amount to the message sender
/// @dev Stakeholder only may call
function withdraw() external {
_withdraw(msg.sender); // throws if msg.sender is not a stakeholder
}
/// @notice Calls {claimVesting} and sends the releasable amount to the message sender
/// @dev Stakeholder only may call
function claimAndWithdraw() external {
_claimVesting();
_withdraw(msg.sender); // throws if msg.sender is not a stakeholder
}
/// @notice Allots a new stake out of the stake of the message sender
/// @dev Stakeholder only may call
function splitStake(address newHolder, uint256 newAmount) external {
address holder = msg.sender;
require(newHolder != holder, "PStakes: duplicated address");
Stake memory stake = _getStake(holder);
require(newAmount <= stake.allocated, "PStakes: too large allocated");
uint256 updAmount = uint256(stake.allocated) - newAmount;
uint256 updReleased = (uint256(stake.released) * updAmount) /
uint256(stake.allocated);
stakes[holder] = Stake(_safe96(updAmount), _safe96(updReleased));
emit StakeSplit(holder, updAmount, updReleased);
uint256 newVested = uint256(stake.released) - updReleased;
stakes[newHolder] = Stake(_safe96(newAmount), _safe96(newVested));
emit StakeSplit(newHolder, newAmount, newVested);
}
//////////////////
//// Owner ////
//////////////////
/// @notice Inits the contract and adds stakes
/// @dev Owner only may call on a proxy (but not on the implementation)
function addStakes(
uint256 _poolId,
address[] calldata holders,
uint256[] calldata allocations,
uint256 unallocated
) external onlyOwner {
if (allocation == 0) {
_init(_poolId);
} else {
require(_poolId == poolId, "PStakes: pool mismatch");
}
uint256 nEntries = holders.length;
require(nEntries == allocations.length, "PStakes: length mismatch");
uint256 updAllocated = uint256(allocated);
for (uint256 i = 0; i < nEntries; i++) {
_throwZeroHolderAddress(holders[i]);
require(
stakes[holders[i]].allocated == 0,
"PStakes: holder exists"
);
require(allocations[i] > 0, "PStakes: zero allocation");
updAllocated += allocations[i];
stakes[holders[i]] = Stake(_safe96(allocations[i]), 0);
emit StakeAdded(holders[i], allocations[i]);
}
require(
updAllocated + unallocated == allocation,
"PStakes: invalid allocation"
);
allocated = _safe96(updAllocated);
}
/// @notice Calls {claimVesting} and sends releasable tokens to specified stakeholders
/// @dev Owner may call only
function massWithdraw(address[] calldata holders) external onlyOwner {
_claimVesting();
for (uint256 i = 0; i < holders.length; i++) {
_withdraw(holders[i]);
}
}
/// @notice Withdraws accidentally sent token from this contract
/// @dev Owner may call only
function claimErc20(
address claimedToken,
address to,
uint256 amount
) external onlyOwner nonReentrant {
IERC20 vestedToken = IERC20(address(_getToken()));
if (claimedToken == address(vestedToken)) {
uint256 balance = vestedToken.balanceOf(address(this));
require(
balance - amount >= allocation - released,
"PStakes: too big amount"
);
}
_claimErc20(claimedToken, to, amount);
}
/// @notice Removes the contract from blockchain when tokens are released
/// @dev Owner only may call on a proxy (but not on the implementation)
function removeContract() external onlyOwner {
// avoid accidental removing of the implementation
_throwImplementation();
require(allocation == released, "PStakes: unpaid stakes");
IERC20 vestedToken = IERC20(address(_getToken()));
uint256 balance = vestedToken.balanceOf(address(this));
require(balance == 0, "PStakes: non-zero balance");
selfdestruct(payable(msg.sender));
}
//////////////////
//// Internal ////
//////////////////
/// @dev Returns the address of the default owner
// (declared `view` rather than `pure` to facilitate testing)
function _defaultOwner() internal view virtual override returns (address) {
return address(DefaultOwnerAddress);
}
/// @dev Returns Token contract address
// (declared `view` rather than `pure` to facilitate testing)
function _getToken() internal view virtual returns (IERC20) {
return IERC20(address(TokenAddress));
}
/// @dev Returns VestingPools contract address
// (declared `view` rather than `pure` to facilitate testing)
function _getVestingPools() internal view virtual returns (IVestingPools) {
return IVestingPools(address(VestingPoolsAddress));
}
/// @dev Returns the stake of the specified stakeholder reverting on errors
function _getStake(address holder) internal view returns (Stake memory) {
_throwZeroHolderAddress(holder);
Stake memory stake = stakes[holder];
require(stake.allocated != 0, "PStakes: unknown stake");
return stake;
}
/// @notice Initialize the contract
/// @dev May be called on a proxy only (but not on the implementation)
function _init(uint256 _poolId) internal {
_throwImplementation();
require(_poolId < 2**16, "PStakes:unsafePoolId");
IVestingPools pools = _getVestingPools();
address wallet = pools.getWallet(_poolId);
require(wallet == address(this), "PStakes:invalidPool");
PoolParams memory pool = pools.getPool(_poolId);
require(pool.sAllocation != 0, "PStakes:zeroPool");
poolId = uint16(_poolId);
allocation = _safe96(uint256(pool.sAllocation) * SCALE);
}
/// @dev Returns amount that may be released for the given stake and factor
function _releasableAmount(Stake memory stake, uint256 _factor)
internal
pure
returns (uint256)
{
uint256 share = (_factor * uint256(stake.allocated)) / SCALE;
if (share > stake.allocated) {
// imprecise division safeguard
share = uint256(stake.allocated);
}
return share - uint256(stake.released);
}
/// @dev Claims vesting to this contract from the vesting pool
function _claimVesting() internal {
// (reentrancy attack impossible - known contract called)
uint256 justVested = _getVestingPools().release(poolId, 0);
factor += uint160((justVested * SCALE) / uint256(allocation));
emit VestingClaimed(justVested);
}
/// @dev Sends the releasable amount of the specified placeholder
function _withdraw(address holder) internal {
Stake memory stake = _getStake(holder);
uint256 releasable = _releasableAmount(stake, uint256(factor));
require(releasable > 0, "PStakes: nothing to withdraw");
stakes[holder].released = _safe96(uint256(stake.released) + releasable);
released = _safe96(uint256(released) + releasable);
// (reentrancy attack impossible - known contract called)
require(_getToken().transfer(holder, releasable), "PStakes:E1");
emit Released(holder, releasable);
}
function _throwZeroHolderAddress(address holder) private pure {
require(holder != address(0), "PStakes: zero holder address");
}
}
// 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;
contract Constants {
// $ZKP token max supply
uint256 internal constant MAX_SUPPLY = 1e27;
// Scaling factor in token amount calculations
uint256 internal constant SCALE = 1e12;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev To save gas, params are packed to fit into a single storage slot.
* Some amounts are scaled (divided) by {SCALE} - note names starting with
* the letter "s" (stands for "scaled") followed by a capital letter.
*/
struct PoolParams {
// if `true`, allocation gets pre-minted, otherwise minted when vested
bool isPreMinted;
// if `true`, the owner may change {start} and {duration}
bool isAdjustable;
// (UNIX) time when vesting starts
uint32 start;
// period in days (since the {start}) of vesting
uint16 vestingDays;
// scaled total amount to (ever) vest from the pool
uint48 sAllocation;
// out of {sAllocation}, amount (also scaled) to be unlocked on the {start}
uint48 sUnlocked;
// amount vested from the pool so far (without scaling)
uint96 vested;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import { PoolParams } from "./Types.sol";
interface IVestingPools {
/**
* @notice Returns Token address.
*/
function token() external view returns (address);
/**
* @notice Returns the wallet address of the specified pool.
*/
function getWallet(uint256 poolId) external view returns (address);
/**
* @notice Returns parameters of the specified pool.
*/
function getPool(uint256 poolId) external view returns (PoolParams memory);
/**
* @notice Returns the amount that may be vested now from the given pool.
*/
function releasableAmount(uint256 poolId) external view returns (uint256);
/**
* @notice Returns the amount that has been vested from the given pool
*/
function vestedAmount(uint256 poolId) external view returns (uint256);
/**
* @notice Vests the specified amount from the given pool to the pool wallet.
* If the amount is zero, it vests the entire "releasable" amount.
* @dev Pool wallet may call only.
* @return released - Amount released.
*/
function release(uint256 poolId, uint256 amount)
external
returns (uint256 released);
/**
* @notice Vests the specified amount from the given pool to the given address.
* If the amount is zero, it vests the entire "releasable" amount.
* @dev Pool wallet may call only.
* @return released - Amount released.
*/
function releaseTo(
uint256 poolId,
address account,
uint256 amount
) external returns (uint256 released);
/**
* @notice Updates the wallet for the given pool.
* @dev (Current) wallet may call only.
*/
function updatePoolWallet(uint256 poolId, address newWallet) external;
/**
* @notice Adds new vesting pools with given wallets and parameters.
* @dev Owner may call only.
*/
function addVestingPools(
address[] memory wallets,
PoolParams[] memory params
) external;
/**
* @notice Update `start` and `duration` for the given pool.
* @param start - new (UNIX) time vesting starts at
* @param vestingDays - new period in days, when vesting lasts
* @dev Owner may call only.
*/
function updatePoolTime(
uint256 poolId,
uint32 start,
uint16 vestingDays
) external;
/// @notice Emitted on an amount vesting.
event Released(uint256 indexed poolId, address to, uint256 amount);
/// @notice Emitted on a pool wallet update.
event WalletUpdated(uint256 indexedpoolId, address indexed newWallet);
/// @notice Emitted on a new pool added.
event PoolAdded(
uint256 indexed poolId,
address indexed wallet,
uint256 allocation
);
/// @notice Emitted on a pool params update.
event PoolUpdated(
uint256 indexed poolId,
uint256 start,
uint256 vestingDays
);
}
// SPDX-License-Identifier: MIT
pragma solidity >0.8.0;
/**
* @title Claimable
* @notice It withdraws accidentally sent tokens from this contract.
* @dev It provides reentrancy guard. The code borrowed from openzeppelin-contracts.
* Unlike original code, this version does not require `constructor` call.
*/
contract Claimable {
bytes4 private constant SELECTOR_TRANSFER =
bytes4(keccak256(bytes("transfer(address,uint256)")));
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _reentrancyStatus;
/// @dev Withdraws ERC20 tokens from this contract
/// (take care of reentrancy attack risk mitigation)
function _claimErc20(
address token,
address to,
uint256 amount
) internal {
// solhint-disable avoid-low-level-calls
(bool success, bytes memory data) = token.call(
abi.encodeWithSelector(SELECTOR_TRANSFER, to, amount)
);
require(
success && (data.length == 0 || abi.decode(data, (bool))),
"claimErc20: TRANSFER_FAILED"
);
}
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_reentrancyStatus != _ENTERED, "claimErc20: reentrant call");
// Any calls to nonReentrant after this point will fail
_reentrancyStatus = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_reentrancyStatus = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
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.
*
* Inspired and borrowed by/from the openzeppelin/contracts` {Ownable}.
* Unlike openzeppelin` version:
* - by default, the owner account is the one returned by the {_defaultOwner}
* function, but not the deployer address;
* - this contract has no constructor and may run w/o initialization;
* - the {renounceOwnership} function removed.
*
* 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.
* The child contract must define the {_defaultOwner} function.
*/
abstract contract DefaultOwnable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/// @dev Returns the current owner address, if it's defined, or the default owner address otherwise.
function owner() public view virtual returns (address) {
return _owner == address(0) ? _defaultOwner() : _owner;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner() {
require(owner() == msg.sender, "Ownable: caller is not the owner");
_;
}
/// @dev Transfers ownership of the contract to the `newOwner`. The owner can only call.
function transferOwnership(address newOwner) external virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
function _defaultOwner() internal view virtual returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This file contains fake libs just for static linking.
* These fake libs' code is assumed to never run.
* On compilation of dependant contracts, instead of fake libs addresses,
* indicate addresses of deployed real contracts (or accounts).
*/
/// @dev Address of the ZKPToken contract ('../ZKPToken.sol') instance
library TokenAddress {
function neverCallIt() external pure {
revert("FAKE");
}
}
/// @dev Address of the VestingPools ('../VestingPools.sol') instance
library VestingPoolsAddress {
function neverCallIt() external pure {
revert("FAKE");
}
}
/// @dev Address of the PoolStakes._defaultOwner
// (NB: if it's not a multisig, transfer ownership to a Multisig contract)
library DefaultOwnerAddress {
function neverCallIt() external pure {
revert("FAKE");
}
}
// SPDX-License-Identifier: MIT
// solhint-disable no-inline-assembly
pragma solidity >0.8.0;
/**
* @title ProxyFactory
* @notice It "clones" the (child) contract deploying EIP-1167 proxies
* @dev Generated proxies:
* - being the EIP-1167 proxy, DELEGATECALL this (child) contract
* - support EIP-1967 specs for the "implementation slot"
* (it gives explorers/wallets more chances to "understand" it's a proxy)
*/
abstract contract ProxyFactory {
// Storage slot that the EIP-1967 defines for the "implementation" address
// (`uint256(keccak256('eip1967.proxy.implementation')) - 1`)
bytes32 private constant IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/// @dev Emits when a new proxy is created
event NewProxy(address proxy);
/**
* @notice Returns `true` if called on a proxy (rather than implementation)
*/
function isProxy() external view returns (bool) {
return _isProxy();
}
/**
* @notice Deploys a new proxy instance that DELEGATECALLs this contract
* @dev Must be called on the implementation (reverts if a proxy is called)
*/
function createProxy() external returns (address proxy) {
_throwProxy();
// CREATE an EIP-1167 proxy instance with the target being this contract
bytes20 target = bytes20(address(this));
assembly {
let initCode := mload(0x40)
mstore(
initCode,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(initCode, 0x14), target)
mstore(
add(initCode, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
// note, 0x37 (55 bytes) is the init bytecode length
// while the deployed bytecode length is 0x2d (45 bytes) only
proxy := create(0, initCode, 0x37)
}
// Write this contract address into the proxy' "implementation" slot
// (reentrancy attack impossible - this contract called)
ProxyFactory(proxy).initProxy(address(this));
emit NewProxy(proxy);
}
/**
* @dev Writes given address into the "implementation" slot of a new proxy.
* !!! It MUST (and may only) be called:
* - via the implementation instance with the {createProxy} method
* - on a newly deployed proxy only
* It reverts if called on the implementation or on initialized proxies.
*/
function initProxy(address impl) external {
_throwImplementation();
require(
_getImplementation() == address(0),
"ProxyFactory:ALREADY_INITIALIZED"
);
// write into the "implementation" slot
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
sstore(slot, impl)
}
}
/// @dev Returns true if called on a proxy instance
function _isProxy() internal view virtual returns (bool) {
// for a DELEGATECALLed contract, `this` and `extcodesize`
// are the address and the code size of the calling contract
// (for a CALLed contract, they are ones of that called contract)
uint256 _size;
address _this = address(this);
assembly {
_size := extcodesize(_this)
}
// shall be the same as the one the `createProxy` generates
return _size == 45;
}
/// @dev Returns the address stored in the "implementation" slot
function _getImplementation() internal view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/// @dev Throws if called on the implementation
function _throwImplementation() internal view {
require(_isProxy(), "ProxyFactory:IMPL_CALLED");
}
/// @dev Throws if called on a proxy
function _throwProxy() internal view {
require(!_isProxy(), "ProxyFactory:PROXY_CALLED");
}
}
// SPDX-License-Identifier: MIT
pragma solidity >0.8.0;
/**
* @title SafeUints
* @notice Util functions which throws if a uint256 can't fit into smaller uints.
*/
contract SafeUints {
// @dev Checks if the given uint256 does not overflow uint96
function _safe96(uint256 n) internal pure returns (uint96) {
require(n < 2**96, "VPools: Unsafe96");
return uint96(n);
}
}
|
Inits the contract and adds stakes Owner only may call on a proxy (but not on the implementation)
|
function addStakes(
uint256 _poolId,
address[] calldata holders,
uint256[] calldata allocations,
uint256 unallocated
) external onlyOwner {
if (allocation == 0) {
_init(_poolId);
require(_poolId == poolId, "PStakes: pool mismatch");
}
uint256 nEntries = holders.length;
require(nEntries == allocations.length, "PStakes: length mismatch");
uint256 updAllocated = uint256(allocated);
for (uint256 i = 0; i < nEntries; i++) {
_throwZeroHolderAddress(holders[i]);
require(
stakes[holders[i]].allocated == 0,
"PStakes: holder exists"
);
require(allocations[i] > 0, "PStakes: zero allocation");
updAllocated += allocations[i];
stakes[holders[i]] = Stake(_safe96(allocations[i]), 0);
emit StakeAdded(holders[i], allocations[i]);
}
require(
updAllocated + unallocated == allocation,
"PStakes: invalid allocation"
);
allocated = _safe96(updAllocated);
}
| 12,762,076
|
./partial_match/1/0x93A20D8EbA6997ABB53aE94bd01727C8e74c8734/sources/TokenCore.sol
|
removeOperator _operators addresses/
|
function revokeOperators(address[] memory _operators)
public onlySysOp returns (bool)
{
for (uint256 i=0; i < _operators.length; i++) {
delete operators[_operators[i]];
emit OperatorRevoked(_operators[i]);
}
return true;
}
event RoleDefined(bytes32 role);
event OperatorAssigned(bytes32 role, address operator);
event ProxyOperatorAssigned(address proxy, bytes32 role, address operator);
event OperatorRevoked(address operator);
| 3,566,172
|
/**
*Submitted for verification at Etherscan.io on 2021-07-02
*/
/**
Hello,
Welcome to $GOAT
*/
pragma solidity ^0.6.12;
// SPDX-License-Identifier: Unlicensed
interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
address private _previousOwner;
uint256 private _lockTime;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(
newOwner != address(0),
"Ownable: new owner is the zero address"
);
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
function geUnlockTime() public view returns (uint256) {
return _lockTime;
}
// //Locks the contract for owner for the amount of time provided
//
// function lock(uint256 time) public virtual onlyOwner {
// _previousOwner = _owner;
// _owner = address(0);
// _lockTime = now + time;
// emit OwnershipTransferred(_owner, address(0));
// }
// //Unlocks the contract for owner when _lockTime is exceeds
// function unlock() public virtual {
// require(
// _previousOwner == msg.sender,
// "You don't have permission to unlock"
// );
// require(now > _lockTime, "Contract is locked until 7 days");
// emit OwnershipTransferred(_owner, _previousOwner);
// _owner = _previousOwner;
// }
}
// pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(
address indexed token0,
address indexed token1,
address pair,
uint256
);
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(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function createPair(address tokenA, address tokenB)
external
returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
// pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event Transfer(address indexed from, address indexed to, uint256 value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 value) external returns (bool);
function transfer(address to, uint256 value) external returns (bool);
function transferFrom(
address from,
address to,
uint256 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 (uint256);
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
event Mint(address indexed sender, uint256 amount0, uint256 amount1);
event Burn(
address indexed sender,
uint256 amount0,
uint256 amount1,
address indexed to
);
event Swap(
address indexed sender,
uint256 amount0In,
uint256 amount1In,
uint256 amount0Out,
uint256 amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint256);
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 (uint256);
function price1CumulativeLast() external view returns (uint256);
function kLast() external view returns (uint256);
function mint(address to) external returns (uint256 liquidity);
function burn(address to)
external
returns (uint256 amount0, uint256 amount1);
function swap(
uint256 amount0Out,
uint256 amount1Out,
address to,
bytes calldata data
) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
// pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
}
contract GoatCoin is Context, IERC20, Ownable {
using SafeMath for uint256;
using Address for address;
mapping (address => bool) private _isSniper;
address[] private _confirmedSnipers;
mapping(address => uint256) private _rOwned;
mapping(address => uint256) private _tOwned;
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => bool) private _isExcludedFromFee;
mapping(address => bool) private _isExcluded;
address[] private _excluded;
uint256 private constant MAX = ~uint256(0);
uint256 private _tTotal = 10000000000 * 10**1 * 10**9;
uint256 private _rTotal = (MAX - (MAX % _tTotal));
uint256 private _tFeeTotal;
string private _name = "Goat";
string private _symbol = "GOAT \xF0\x9F\x90\x90";
uint8 private _decimals = 9;
address payable public _teamWalletAddress;
uint256 public _taxFee = 0;
uint256 private _previousTaxFee = _taxFee;
uint256 public _liquidityFee = 9;
uint256 private _previousLiquidityFee = _liquidityFee;
uint256 private _liqFeeRatio = 6;
IUniswapV2Router02 public immutable uniswapV2Router;
address public immutable uniswapV2Pair;
bool inSwapAndLiquify;
bool public swapAndLiquifyEnabled = true;
uint256 public _maxTxAmount = 100000000 * 10**1 * 10**9;
uint256 private numTokensSellToAddToLiquidity = 60000000 * 10**1 * 10**9;
event MinTokensBeforeSwapUpdated(uint256 minTokensBeforeSwap);
event SwapAndLiquifyEnabledUpdated(bool enabled);
event SwapAndLiquify(
uint256 tokensSwapped,
uint256 ethReceived,
uint256 tokensIntoLiqudity
);
event SwapToTeam(uint256 tokensSwapped);
modifier lockTheSwap {
inSwapAndLiquify = true;
_;
inSwapAndLiquify = false;
}
constructor(address payable teamAddress) public {
_teamWalletAddress = teamAddress;
_rOwned[_msgSender()] = _rTotal;
IUniswapV2Router02 _uniswapV2Router =
IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //uniswap router across all ETH
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
// set the rest of the contract variables
uniswapV2Router = _uniswapV2Router;
//exclude owner and this contract from fee
_isExcludedFromFee[owner()] = true;
_isExcludedFromFee[address(this)] = true;
// List of front-runner & sniper bots from t.me/FairLaunchCalls
_isSniper[address(0x7589319ED0fD750017159fb4E4d96C63966173C1)] = true;
_confirmedSnipers.push(address(0x7589319ED0fD750017159fb4E4d96C63966173C1));
_isSniper[address(0x65A67DF75CCbF57828185c7C050e34De64d859d0)] = true;
_confirmedSnipers.push(address(0x65A67DF75CCbF57828185c7C050e34De64d859d0));
_isSniper[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true;
_confirmedSnipers.push(address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce));
_isSniper[address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce)] = true;
_confirmedSnipers.push(address(0xE031b36b53E53a292a20c5F08fd1658CDdf74fce));
_isSniper[address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345)] = true;
_confirmedSnipers.push(address(0xe516bDeE55b0b4e9bAcaF6285130De15589B1345));
_isSniper[address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b)] = true;
_confirmedSnipers.push(address(0xa1ceC245c456dD1bd9F2815a6955fEf44Eb4191b));
_isSniper[address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95)] = true;
_confirmedSnipers.push(address(0xd7d3EE77D35D0a56F91542D4905b1a2b1CD7cF95));
_isSniper[address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964)] = true;
_confirmedSnipers.push(address(0xFe76f05dc59fEC04184fA0245AD0C3CF9a57b964));
_isSniper[address(0xDC81a3450817A58D00f45C86d0368290088db848)] = true;
_confirmedSnipers.push(address(0xDC81a3450817A58D00f45C86d0368290088db848));
_isSniper[address(0x45fD07C63e5c316540F14b2002B085aEE78E3881)] = true;
_confirmedSnipers.push(address(0x45fD07C63e5c316540F14b2002B085aEE78E3881));
_isSniper[address(0x27F9Adb26D532a41D97e00206114e429ad58c679)] = true;
_confirmedSnipers.push(address(0x27F9Adb26D532a41D97e00206114e429ad58c679));
_isSniper[address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7)] = true;
_confirmedSnipers.push(address(0x9282dc5c422FA91Ff2F6fF3a0b45B7BF97CF78E7));
_isSniper[address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533)] = true;
_confirmedSnipers.push(address(0xfad95B6089c53A0D1d861eabFaadd8901b0F8533));
_isSniper[address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d)] = true;
_confirmedSnipers.push(address(0x1d6E8BAC6EA3730825bde4B005ed7B2B39A2932d));
_isSniper[address(0x000000000000084e91743124a982076C59f10084)] = true;
_confirmedSnipers.push(address(0x000000000000084e91743124a982076C59f10084));
_isSniper[address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303)] = true;
_confirmedSnipers.push(address(0x6dA4bEa09C3aA0761b09b19837D9105a52254303));
_isSniper[address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595)] = true;
_confirmedSnipers.push(address(0x323b7F37d382A68B0195b873aF17CeA5B67cd595));
_isSniper[address(0x000000005804B22091aa9830E50459A15E7C9241)] = true;
_confirmedSnipers.push(address(0x000000005804B22091aa9830E50459A15E7C9241));
_isSniper[address(0xA3b0e79935815730d942A444A84d4Bd14A339553)] = true;
_confirmedSnipers.push(address(0xA3b0e79935815730d942A444A84d4Bd14A339553));
_isSniper[address(0xf6da21E95D74767009acCB145b96897aC3630BaD)] = true;
_confirmedSnipers.push(address(0xf6da21E95D74767009acCB145b96897aC3630BaD));
_isSniper[address(0x0000000000007673393729D5618DC555FD13f9aA)] = true;
_confirmedSnipers.push(address(0x0000000000007673393729D5618DC555FD13f9aA));
_isSniper[address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1)] = true;
_confirmedSnipers.push(address(0x00000000000003441d59DdE9A90BFfb1CD3fABf1));
_isSniper[address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6)] = true;
_confirmedSnipers.push(address(0x59903993Ae67Bf48F10832E9BE28935FEE04d6F6));
_isSniper[address(0x000000917de6037d52b1F0a306eeCD208405f7cd)] = true;
_confirmedSnipers.push(address(0x000000917de6037d52b1F0a306eeCD208405f7cd));
_isSniper[address(0x7100e690554B1c2FD01E8648db88bE235C1E6514)] = true;
_confirmedSnipers.push(address(0x7100e690554B1c2FD01E8648db88bE235C1E6514));
_isSniper[address(0x72b30cDc1583224381132D379A052A6B10725415)] = true;
_confirmedSnipers.push(address(0x72b30cDc1583224381132D379A052A6B10725415));
_isSniper[address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE)] = true;
_confirmedSnipers.push(address(0x9eDD647D7d6Eceae6bB61D7785Ef66c5055A9bEE));
_isSniper[address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F)] = true;
_confirmedSnipers.push(address(0xfe9d99ef02E905127239E85A611c29ad32c31c2F));
_isSniper[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true;
_confirmedSnipers.push(address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b));
_isSniper[address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9)] = true;
_confirmedSnipers.push(address(0xc496D84215d5018f6F53E7F6f12E45c9b5e8e8A9));
_isSniper[address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7)] = true;
_confirmedSnipers.push(address(0x59341Bc6b4f3Ace878574b05914f43309dd678c7));
_isSniper[address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF)] = true;
_confirmedSnipers.push(address(0xe986d48EfeE9ec1B8F66CD0b0aE8e3D18F091bDF));
_isSniper[address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290)] = true;
_confirmedSnipers.push(address(0x4aEB32e16DcaC00B092596ADc6CD4955EfdEE290));
_isSniper[address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5)] = true;
_confirmedSnipers.push(address(0x136F4B5b6A306091b280E3F251fa0E21b1280Cd5));
_isSniper[address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b)] = true;
_confirmedSnipers.push(address(0x39608b6f20704889C51C0Ae28b1FCA8F36A5239b));
_isSniper[address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7)] = true;
_confirmedSnipers.push(address(0x5B83A351500B631cc2a20a665ee17f0dC66e3dB7));
_isSniper[address(0xbCb05a3F85d34f0194C70d5914d5C4E28f11Cc02)] = true;
_confirmedSnipers.push(address(0xbCb05a3F85d34f0194C70d5914d5C4E28f11Cc02));
_isSniper[address(0x22246F9BCa9921Bfa9A3f8df5baBc5Bc8ee73850)] = true;
_confirmedSnipers.push(address(0x22246F9BCa9921Bfa9A3f8df5baBc5Bc8ee73850));
_isSniper[address(0x42d4C197036BD9984cA652303e07dD29fA6bdB37)] = true;
_confirmedSnipers.push(address(0x42d4C197036BD9984cA652303e07dD29fA6bdB37));
_isSniper[address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40)] = true;
_confirmedSnipers.push(address(0x00000000003b3cc22aF3aE1EAc0440BcEe416B40));
_isSniper[address(0x231DC6af3C66741f6Cf618884B953DF0e83C1A2A)] = true;
_confirmedSnipers.push(address(0x231DC6af3C66741f6Cf618884B953DF0e83C1A2A));
_isSniper[address(0xC6bF34596f74eb22e066a878848DfB9fC1CF4C65)] = true;
_confirmedSnipers.push(address(0xC6bF34596f74eb22e066a878848DfB9fC1CF4C65));
_isSniper[address(0x20f6fCd6B8813c4f98c0fFbD88C87c0255040Aa3)] = true;
_confirmedSnipers.push(address(0x20f6fCd6B8813c4f98c0fFbD88C87c0255040Aa3));
_isSniper[address(0xD334C5392eD4863C81576422B968C6FB90EE9f79)] = true;
_confirmedSnipers.push(address(0xD334C5392eD4863C81576422B968C6FB90EE9f79));
_isSniper[address(0xFFFFF6E70842330948Ca47254F2bE673B1cb0dB7)] = true;
_confirmedSnipers.push(address(0xFFFFF6E70842330948Ca47254F2bE673B1cb0dB7));
_isSniper[address(0xA39C50bf86e15391180240938F469a7bF4fDAe9a)] = true;
_confirmedSnipers.push(address(0xA39C50bf86e15391180240938F469a7bF4fDAe9a));
_isSniper[address(0xA39C50bf86e15391180240938F469a7bF4fDAe9a)] = true;
_confirmedSnipers.push(address(0xA39C50bf86e15391180240938F469a7bF4fDAe9a));
emit Transfer(address(0), _msgSender(), _tTotal);
}
function isRemovedSniper(address account) public view returns (bool) {
return _isSniper[account];
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _tTotal;
}
function balanceOf(address account) public view override returns (uint256) {
if (_isExcluded[account]) return _tOwned[account];
return tokenFromReflection(_rOwned[account]);
}
function transfer(address recipient, uint256 amount)
public
override
returns (bool)
{
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender)
public
view
override
returns (uint256)
{
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount)
public
override
returns (bool)
{
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(
address sender,
address recipient,
uint256 amount
) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(
amount,
"ERC20: transfer amount exceeds allowance"
)
);
return true;
}
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].add(addedValue)
);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue)
public
virtual
returns (bool)
{
_approve(
_msgSender(),
spender,
_allowances[_msgSender()][spender].sub(
subtractedValue,
"ERC20: decreased allowance below zero"
)
);
return true;
}
function isExcludedFromReward(address account) public view returns (bool) {
return _isExcluded[account];
}
function totalFees() public view returns (uint256) {
return _tFeeTotal;
}
function deliver(uint256 tAmount) public {
address sender = _msgSender();
require(
!_isExcluded[sender],
"Excluded addresses cannot call this function"
);
(uint256 rAmount, , , , , ) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rTotal = _rTotal.sub(rAmount);
_tFeeTotal = _tFeeTotal.add(tAmount);
}
function reflectionFromToken(uint256 tAmount, bool deductTransferFee)
public
view
returns (uint256)
{
require(tAmount <= _tTotal, "Amount must be less than supply");
if (!deductTransferFee) {
(uint256 rAmount, , , , , ) = _getValues(tAmount);
return rAmount;
} else {
(, uint256 rTransferAmount, , , , ) = _getValues(tAmount);
return rTransferAmount;
}
}
function tokenFromReflection(uint256 rAmount)
public
view
returns (uint256)
{
require(
rAmount <= _rTotal,
"Amount must be less than total reflections"
);
uint256 currentRate = _getRate();
return rAmount.div(currentRate);
}
function excludeFromReward(address account) public onlyOwner() {
// require(account != 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D, 'We can not exclude Uniswap router.');
require(!_isExcluded[account], "Account is already excluded");
if (_rOwned[account] > 0) {
_tOwned[account] = tokenFromReflection(_rOwned[account]);
}
_isExcluded[account] = true;
_excluded.push(account);
}
function includeInReward(address account) external onlyOwner() {
require(_isExcluded[account], "Account is already excluded");
for (uint256 i = 0; i < _excluded.length; i++) {
if (_excluded[i] == account) {
_excluded[i] = _excluded[_excluded.length - 1];
_tOwned[account] = 0;
_isExcluded[account] = false;
_excluded.pop();
break;
}
}
}
function _transferBothExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFee[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFee[account] = false;
}
function setTaxFeePercent(uint256 taxFee) external onlyOwner() {
require(taxFee <= 9, "TaxFee > 9");
_taxFee = taxFee;
}
function setLiquidityFeePercent(uint256 liquidityFee) external onlyOwner() {
require(liquidityFee <= 9, "liq fee > 9");
_liquidityFee = liquidityFee;
}
function setMaxTxPercent(uint256 maxTxPercent) external onlyOwner() {
require(maxTxPercent > 0, "Maxtx <= 0");
_maxTxAmount = _tTotal.mul(maxTxPercent).div(10**2);
}
function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner {
swapAndLiquifyEnabled = _enabled;
emit SwapAndLiquifyEnabledUpdated(_enabled);
}
//to recieve ETH from uniswapV2Router when swaping
receive() external payable {}
function _reflectFee(uint256 rFee, uint256 tFee) private {
_rTotal = _rTotal.sub(rFee);
_tFeeTotal = _tFeeTotal.add(tFee);
}
function _getValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256,
uint256
)
{
(uint256 tTransferAmount, uint256 tFee, uint256 tLiquidity) =
_getTValues(tAmount);
(uint256 rAmount, uint256 rTransferAmount, uint256 rFee) =
_getRValues(tAmount, tFee, tLiquidity, _getRate());
return (
rAmount,
rTransferAmount,
rFee,
tTransferAmount,
tFee,
tLiquidity
);
}
function _getTValues(uint256 tAmount)
private
view
returns (
uint256,
uint256,
uint256
)
{
uint256 tFee = calculateTaxFee(tAmount);
uint256 tLiquidity = calculateLiquidityFee(tAmount);
uint256 tTransferAmount = tAmount.sub(tFee).sub(tLiquidity);
return (tTransferAmount, tFee, tLiquidity);
}
function _getRValues(
uint256 tAmount,
uint256 tFee,
uint256 tLiquidity,
uint256 currentRate
)
private
pure
returns (
uint256,
uint256,
uint256
)
{
uint256 rAmount = tAmount.mul(currentRate);
uint256 rFee = tFee.mul(currentRate);
uint256 rLiquidity = tLiquidity.mul(currentRate);
uint256 rTransferAmount = rAmount.sub(rFee).sub(rLiquidity);
return (rAmount, rTransferAmount, rFee);
}
function _getRate() private view returns (uint256) {
(uint256 rSupply, uint256 tSupply) = _getCurrentSupply();
return rSupply.div(tSupply);
}
function _getCurrentSupply() private view returns (uint256, uint256) {
uint256 rSupply = _rTotal;
uint256 tSupply = _tTotal;
for (uint256 i = 0; i < _excluded.length; i++) {
if (
_rOwned[_excluded[i]] > rSupply ||
_tOwned[_excluded[i]] > tSupply
) return (_rTotal, _tTotal);
rSupply = rSupply.sub(_rOwned[_excluded[i]]);
tSupply = tSupply.sub(_tOwned[_excluded[i]]);
}
if (rSupply < _rTotal.div(_tTotal)) return (_rTotal, _tTotal);
return (rSupply, tSupply);
}
function _takeLiquidity(uint256 tLiquidity) private {
uint256 currentRate = _getRate();
uint256 rLiquidity = tLiquidity.mul(currentRate);
_rOwned[address(this)] = _rOwned[address(this)].add(rLiquidity);
if (_isExcluded[address(this)])
_tOwned[address(this)] = _tOwned[address(this)].add(tLiquidity);
}
function calculateTaxFee(uint256 _amount) private view returns (uint256) {
return _amount.mul(_taxFee).div(10**2);
}
function calculateLiquidityFee(uint256 _amount)
private
view
returns (uint256)
{
return _amount.mul(_liquidityFee).div(10**2);
}
function removeAllFee() private {
if (_taxFee == 0 && _liquidityFee == 0) return;
_previousTaxFee = _taxFee;
_previousLiquidityFee = _liquidityFee;
_taxFee = 0;
_liquidityFee = 0;
}
function restoreAllFee() private {
_taxFee = _previousTaxFee;
_liquidityFee = _previousLiquidityFee;
}
function isExcludedFromFee(address account) public view returns (bool) {
return _isExcludedFromFee[account];
}
function _approve(
address owner,
address spender,
uint256 amount
) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(!_isSniper[to], "You have no power here!");
require(!_isSniper[msg.sender], "You have no power here!");
require(amount > 0, "Transfer amount must be greater than zero");
if (from != owner() && to != owner())
require(
amount <= _maxTxAmount,
"Transfer amount exceeds the maxTxAmount."
);
// is the token balance of this contract address over the min number of
// tokens that we need to initiate a swap + liquidity lock?
// also, don't get caught in a circular liquidity event.
// also, don't swap & liquify if sender is uniswap pair.
uint256 contractTokenBalance = balanceOf(address(this));
if (contractTokenBalance >= _maxTxAmount) {
contractTokenBalance = _maxTxAmount;
}
bool overMinTokenBalance =
contractTokenBalance >= numTokensSellToAddToLiquidity;
if (
overMinTokenBalance &&
!inSwapAndLiquify &&
from != uniswapV2Pair &&
swapAndLiquifyEnabled
) {
contractTokenBalance = numTokensSellToAddToLiquidity;
//add liquidity
swapForFees(contractTokenBalance);
}
//indicates if fee should be deducted from transfer
bool takeFee = true;
//if any account belongs to _isExcludedFromFee account then remove the fee
if (_isExcludedFromFee[from] || _isExcludedFromFee[to]) {
takeFee = false;
}
//transfer amount, it will take tax, burn, liquidity fee
_tokenTransfer(from, to, amount, takeFee);
}
function swapForFees(uint256 contractTokenBalance) private lockTheSwap {
sendBNBToTeam(contractTokenBalance);
emit SwapToTeam(contractTokenBalance);
}
function swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function sendBNBToTeam(uint256 amount) private {
swapTokensForEth(amount);
_teamWalletAddress.transfer(address(this).balance);
}
function _setTeamWallet(address payable teamWalletAddress)
external
onlyOwner()
{
_teamWalletAddress = teamWalletAddress;
}
//this method is responsible for taking all fee, if takeFee is true
function _tokenTransfer(
address sender,
address recipient,
uint256 amount,
bool takeFee
) private {
if (!takeFee) removeAllFee();
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && _isExcluded[recipient]) {
_transferToExcluded(sender, recipient, amount);
} else if (!_isExcluded[sender] && !_isExcluded[recipient]) {
_transferStandard(sender, recipient, amount);
} else if (_isExcluded[sender] && _isExcluded[recipient]) {
_transferBothExcluded(sender, recipient, amount);
} else {
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
function _transferStandard(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferToExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_tOwned[recipient] = _tOwned[recipient].add(tTransferAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
function _transferFromExcluded(
address sender,
address recipient,
uint256 tAmount
) private {
(
uint256 rAmount,
uint256 rTransferAmount,
uint256 rFee,
uint256 tTransferAmount,
uint256 tFee,
uint256 tLiquidity
) = _getValues(tAmount);
_tOwned[sender] = _tOwned[sender].sub(tAmount);
_rOwned[sender] = _rOwned[sender].sub(rAmount);
_rOwned[recipient] = _rOwned[recipient].add(rTransferAmount);
_takeLiquidity(tLiquidity);
_reflectFee(rFee, tFee);
emit Transfer(sender, recipient, tTransferAmount);
}
}
|
SPDX-License-Identifier: Unlicensed
|
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount)
external
returns (bool);
function allowance(address owner, address spender)
external
view
returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
Hello,
}
| 15,239,171
|
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*
██████╗ █████╗ ███╗ ██╗██╗███████╗██╗
██╔══██╗██╔══██╗████╗ ██║██║██╔════╝██║
██║ ██║███████║██╔██╗ ██║██║█████╗ ██║
██║ ██║██╔══██║██║╚██╗██║██║██╔══╝ ██║
██████╔╝██║ ██║██║ ╚████║██║███████╗███████╗
╚═════╝ ╚═╝ ╚═╝╚═╝ ╚═══╝╚═╝╚══════╝╚══════╝
█████╗ ██████╗ ███████╗██╗ ██╗ █████╗ ███╗ ███╗
██╔══██╗██╔══██╗██╔════╝██║ ██║██╔══██╗████╗ ████║
███████║██████╔╝███████╗███████║███████║██╔████╔██║
██╔══██║██╔══██╗╚════██║██╔══██║██╔══██║██║╚██╔╝██║
██║ ██║██║ ██║███████║██║ ██║██║ ██║██║ ╚═╝ ██║
╚═╝ ╚═╝╚═╝ ╚═╝╚══════╝╚═╝ ╚═╝╚═╝ ╚═╝╚═╝ ╚═╝
______
/ /\
/ /##\
/ /####\
/ /######\
/ /########\
/ /##########\
/ /#####/\#####\
/ /#####/++\#####\
/ /#####/++++\#####\
/ /#####/\+++++\#####\
/ /#####/ \+++++\#####\
/ /#####/ \+++++\#####\
/ /#####/ \+++++\#####\
/ /#####/ \+++++\#####\
/ /#####/__________\+++++\#####\
/ \+++++\#####\
/__________________________\+++++\####/
\+++++++++++++++++++++++++++++++++\##/
\+++++++++++++++++++++++++++++++++\/
``````````````````````````````````
██████╗██╗ ██╗██╗██████╗
██╔════╝╚██╗██╔╝██║██╔══██╗
██║ ╚███╔╝ ██║██████╔╝
██║ ██╔██╗ ██║██╔═══╝
╚██████╗██╔╝ ██╗██║██║
╚═════╝╚═╝ ╚═╝╚═╝╚═╝
*/
import "./external/OpenSea.sol";
import "./interface/IERC165.sol";
import "./interface/ICxipERC721.sol";
import "./interface/ICxipIdentity.sol";
import "./interface/ICxipProvenance.sol";
import "./interface/ICxipRegistry.sol";
import "./interface/IPA1D.sol";
import "./library/Address.sol";
import "./library/Bytes.sol";
import "./library/Strings.sol";
import "./struct/CollectionData.sol";
import "./struct/TokenData.sol";
import "./struct/Verification.sol";
contract DanielArshamErodingAndReformingCars {
/**
* @dev Stores default collection data: name, symbol, and royalties.
*/
CollectionData private _collectionData;
/**
* @dev Internal last minted token id, to allow for auto-increment.
*/
uint256 private _currentTokenId;
/**
* @dev Array of all token ids in collection.
*/
uint256[] private _allTokens;
/**
* @dev Map of token id to array index of _ownedTokens.
*/
mapping(uint256 => uint256) private _ownedTokensIndex;
/**
* @dev Token id to wallet (owner) address map.
*/
mapping(uint256 => address) private _tokenOwner;
/**
* @dev 1-to-1 map of token id that was assigned an approved operator address.
*/
mapping(uint256 => address) private _tokenApprovals;
/**
* @dev Map of total tokens owner by a specific address.
*/
mapping(address => uint256) private _ownedTokensCount;
/**
* @dev Map of array of token ids owned by a specific address.
*/
mapping(address => uint256[]) private _ownedTokens;
/**
* @notice Map of full operator approval for a particular address.
* @dev Usually utilised for supporting marketplace proxy wallets.
*/
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Token data mapped by token id.
*/
mapping(uint256 => TokenData) private _tokenData;
/**
* @dev Address of admin user. Primarily used as an additional recover address.
*/
address private _admin;
/**
* @dev Address of contract owner. This address can run all onlyOwner functions.
*/
address private _owner;
/**
* @dev Simple tracker of all minted (not-burned) tokens.
*/
uint256 private _totalTokens;
/**
* @dev Mapping from token id to position in the allTokens array.
*/
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @notice Event emitted when an token is minted, transfered, or burned.
* @dev If from is empty, it's a mint. If to is empty, it's a burn. Otherwise, it's a transfer.
* @param from Address from where token is being transfered.
* @param to Address to where token is being transfered.
* @param tokenId Token id that is being minted, Transfered, or burned.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @notice Event emitted when an address delegates power, for a token, to another address.
* @dev Emits event that informs of address approving a third-party operator for a particular token.
* @param wallet Address of the wallet configuring a token operator.
* @param operator Address of the third-party operator approved for interaction.
* @param tokenId A specific token id that is being authorised to operator.
*/
event Approval(address indexed wallet, address indexed operator, uint256 indexed tokenId);
/**
* @notice Event emitted when an address authorises an operator (third-party).
* @dev Emits event that informs of address approving/denying a third-party operator.
* @param wallet Address of the wallet configuring it's operator.
* @param operator Address of the third-party operator that interacts on behalf of the wallet.
* @param approved A boolean indicating whether approval was granted or revoked.
*/
event ApprovalForAll(address indexed wallet, address indexed operator, bool approved);
/**
* @notice Constructor is empty and not utilised.
* @dev To make exact CREATE2 deployment possible, constructor is left empty. We utilize the "init" function instead.
*/
constructor() {}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "CXIP: caller not an owner");
_;
}
/**
* @dev Left empty on purpose to prevent out of gas errors.
*/
receive() external payable {}
/**
* @notice Enables royaltiy functionality at the ERC721 level no other function matches the call.
* @dev See implementation of _royaltiesFallback.
*/
fallback() external {
_royaltiesFallback();
}
function getIntervalConfig() public view returns (uint256[4] memory intervals) {
uint64 unpacked;
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.intervalConfig')) - 1);
assembly {
unpacked := sload(
/* slot */
0xf8883f7674e7099512a3eb674d514a03c06b3984f509bd9a7b34673ea2a79349
)
}
intervals[0] = uint256(uint16(unpacked >> 48));
intervals[1] = uint256(uint16(unpacked >> 32));
intervals[2] = uint256(uint16(unpacked >> 16));
intervals[3] = uint256(uint16(unpacked));
}
function setIntervalConfig(uint256[4] memory intervals) external onlyOwner {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.intervalConfig')) - 1);
uint256 packed = uint256((intervals[0] << 48) | (intervals[1] << 32) | (intervals[2] << 16) | intervals[3]);
assembly {
sstore(
/* slot */
0xf8883f7674e7099512a3eb674d514a03c06b3984f509bd9a7b34673ea2a79349,
packed
)
}
}
function _calculateRotation(uint256 tokenId) internal view returns (uint256 rotationIndex) {
uint256 configIndex = (tokenId / getTokenSeparator());
uint256 interval = getIntervalConfig()[configIndex - 1];
uint256 remainder = ((block.timestamp - getStartTimestamp()) / interval) % 2;
// (remainder == 0 ? "even" : "odd")
rotationIndex = (configIndex * 2) + remainder;
}
/**
* @notice Gets the URI of the NFT on Arweave.
* @dev Concatenates 2 sections of the arweave URI.
* @return string The URI.
*/
function arweaveURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return string(abi.encodePacked("https://arweave.net/", _tokenData[index].arweave, _tokenData[index].arweave2));
}
/**
* @notice Gets the URI of the NFT backup from CXIP.
* @dev Concatenates to https://nft.cxip.io/.
* @return string The URI.
*/
function contractURI() external view returns (string memory) {
return string(abi.encodePacked("https://nft.cxip.io/", Strings.toHexString(address(this)), "/"));
}
/**
* @notice Gets the creator's address.
* @dev If the token Id doesn't exist it will return zero address.
* @return address Creator's address.
*/
function creator(uint256 tokenId) external view returns (address) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return _tokenData[index].creator;
}
/**
* @notice Gets the HTTP URI of the token.
* @dev Concatenates to the baseURI.
* @return string The URI.
*/
function httpURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "CXIP: token does not exist");
return string(abi.encodePacked(baseURI(), "/", Strings.toHexString(tokenId)));
}
/**
* @notice Gets the IPFS URI
* @dev Concatenates to the IPFS domain.
* @return string The URI.
*/
function ipfsURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return string(abi.encodePacked("https://ipfs.io/ipfs/", _tokenData[index].ipfs, _tokenData[index].ipfs2));
}
/**
* @notice Gets the name of the collection.
* @dev Uses two names to extend the max length of the collection name in bytes
* @return string The collection name.
*/
function name() external view returns (string memory) {
return string(abi.encodePacked(Bytes.trim(_collectionData.name), Bytes.trim(_collectionData.name2)));
}
/**
* @notice Gets the hash of the NFT data used to create it.
* @dev Payload is used for verification.
* @param tokenId The Id of the token.
* @return bytes32 The hash.
*/
function payloadHash(uint256 tokenId) external view returns (bytes32) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return _tokenData[index].payloadHash;
}
/**
* @notice Gets the signature of the signed NFT data used to create it.
* @dev Used for signature verification.
* @param tokenId The Id of the token.
* @return Verification a struct containing v, r, s values of the signature.
*/
function payloadSignature(uint256 tokenId) external view returns (Verification memory) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return _tokenData[index].payloadSignature;
}
/**
* @notice Gets the address of the creator.
* @dev The creator signs a payload while creating the NFT.
* @param tokenId The Id of the token.
* @return address The creator.
*/
function payloadSigner(uint256 tokenId) external view returns (address) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return _tokenData[index].creator;
}
/**
* @notice Shows the interfaces the contracts support
* @dev Must add new 4 byte interface Ids here to acknowledge support
* @param interfaceId ERC165 style 4 byte interfaceId.
* @return bool True if supported.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool) {
if (
interfaceId == 0x01ffc9a7 || // ERC165
interfaceId == 0x80ac58cd || // ERC721
interfaceId == 0x780e9d63 || // ERC721Enumerable
interfaceId == 0x5b5e139f || // ERC721Metadata
interfaceId == 0x150b7a02 || // ERC721TokenReceiver
interfaceId == 0xe8a3d485 || // contractURI()
IPA1D(getRegistry().getPA1D()).supportsInterface(interfaceId)
) {
return true;
} else {
return false;
}
}
/**
* @notice Gets the collection's symbol.
* @dev Trims the symbol.
* @return string The symbol.
*/
function symbol() external view returns (string memory) {
return string(Bytes.trim(_collectionData.symbol));
}
/**
* @notice Get's the URI of the token.
* @dev Defaults the the Arweave URI
* @return string The URI.
*/
function tokenURI(uint256 tokenId) external view returns (string memory) {
require(_exists(tokenId), "CXIP: token does not exist");
uint256 index = _calculateRotation(tokenId);
return string(abi.encodePacked("https://arweave.net/", _tokenData[index].arweave, _tokenData[index].arweave2));
}
/**
* @notice Get list of tokens owned by wallet.
* @param wallet The wallet address to get tokens for.
* @return uint256[] Returns an array of token ids owned by wallet.
*/
function tokensOfOwner(address wallet) external view returns (uint256[] memory) {
return _ownedTokens[wallet];
}
/**
* @notice Adds a new address to the token's approval list.
* @dev Requires the sender to be in the approved addresses.
* @param to The address to approve.
* @param tokenId The affected token.
*/
function approve(address to, uint256 tokenId) public {
address tokenOwner = _tokenOwner[tokenId];
require(to != tokenOwner, "CXIP: can't approve self");
require(_isApproved(msg.sender, tokenId), "CXIP: not approved sender");
_tokenApprovals[tokenId] = to;
emit Approval(tokenOwner, to, tokenId);
}
/**
* @notice Burns the token.
* @dev The sender must be the owner or approved.
* @param tokenId The token to burn.
*/
function burn(uint256 tokenId) public {
require(_isApproved(msg.sender, tokenId), "CXIP: not approved sender");
address wallet = _tokenOwner[tokenId];
_clearApproval(tokenId);
_tokenOwner[tokenId] = address(0);
emit Transfer(wallet, address(0), tokenId);
_removeTokenFromOwnerEnumeration(wallet, tokenId);
}
/**
* @notice Initializes the collection.
* @dev Special function to allow a one time initialisation on deployment. Also configures and deploys royalties.
* @param newOwner The owner of the collection.
* @param collectionData The collection data.
*/
function init(address newOwner, CollectionData calldata collectionData) public {
require(Address.isZero(_admin), "CXIP: already initialized");
_admin = msg.sender;
// temporary set to self, to pass rarible royalties logic trap
_owner = address(this);
_collectionData = collectionData;
IPA1D(address(this)).init(0, payable(collectionData.royalties), collectionData.bps);
// set to actual owner
_owner = newOwner;
}
/**
* @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.
* @param from cannot be the zero address.
* @param to cannot be the zero address.
* @param tokenId token must exist and be owned by `from`.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public payable {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @notice Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings.
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
* @param from cannot be the zero address.
* @param to cannot be the zero address.
* @param tokenId token must exist and be owned by `from`.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) public payable {
require(_isApproved(msg.sender, tokenId), "CXIP: not approved sender");
_transferFrom(from, to, tokenId);
if (Address.isContract(to)) {
require(
IERC165(to).supportsInterface(0x01ffc9a7) &&
IERC165(to).supportsInterface(0x150b7a02) &&
ICxipERC721(to).onERC721Received(address(this), from, tokenId, data) == 0x150b7a02,
"CXIP: onERC721Received fail"
);
}
}
/**
* @notice Adds a new approved operator.
* @dev Allows platforms to sell/transfer all your NFTs. Used with proxy contracts like OpenSea/Rarible.
* @param to The address to approve.
* @param approved Turn on or off approval status.
*/
function setApprovalForAll(address to, bool approved) public {
require(to != msg.sender, "CXIP: can't approve self");
_operatorApprovals[msg.sender][to] = approved;
emit ApprovalForAll(msg.sender, to, approved);
}
/**
* @notice Transfers `tokenId` token from `from` to `to`.
* @dev WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* @param from cannot be the zero address.
* @param to cannot be the zero address.
* @param tokenId token must be owned by `from`.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public payable {
transferFrom(from, to, tokenId, "");
}
/**
* @notice Transfers `tokenId` token from `from` to `to`.
* @dev WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
* @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings.
* @param from cannot be the zero address.
* @param to cannot be the zero address.
* @param tokenId token must be owned by `from`.
*/
function transferFrom(
address from,
address to,
uint256 tokenId,
bytes memory /*_data*/
) public payable {
require(_isApproved(msg.sender, tokenId), "CXIP: not approved sender");
_transferFrom(from, to, tokenId);
}
/**
* @notice Mints batches of NFTs.
* @dev Limited to maximum number of NFTs that can be minted for this drop. Needs to be called in tokenId sequence.
* @param creatorWallet The wallet address of the NFT creator.
* @param startId The tokenId from which to start batch mint.
* @param length The total number of NFTs to mint starting from the startId.
* @param recipient Optional parameter, to send the token to a recipient right after minting.
*/
function batchMint(
address creatorWallet,
uint256 startId,
uint256 length,
address recipient
) public onlyOwner {
require(!getMintingClosed(), "CXIP: minting is now closed");
require(_allTokens.length + length <= getTokenLimit(), "CXIP: over token limit");
require(isIdentityWallet(creatorWallet), "CXIP: creator not in identity");
bool hasRecipient = !Address.isZero(recipient);
uint256 tokenId;
for (uint256 i = 0; i < length; i++) {
tokenId = (startId + i);
if (hasRecipient) {
require(!_exists(tokenId), "CXIP: token already exists");
emit Transfer(address(0), creatorWallet, tokenId);
emit Transfer(creatorWallet, recipient, tokenId);
_tokenOwner[tokenId] = recipient;
_addTokenToOwnerEnumeration(recipient, tokenId);
} else {
_mint(creatorWallet, tokenId);
}
}
if (_allTokens.length == getTokenLimit()) {
setMintingClosed();
}
}
function getStartTimestamp() public view returns (uint256 _timestamp) {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.startTimestamp')) - 1);
assembly {
_timestamp := sload(
/* slot */
0xf2aaccfcfa4e77d7601ed4ebe139368f313960f63d25a2f26ec905d019eba48b
)
}
}
/**
* @dev Gets the minting status from storage slot.
* @return mintingClosed Whether minting is open or closed permanently.
*/
function getMintingClosed() public view returns (bool mintingClosed) {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.mintingClosed')) - 1);
uint256 data;
assembly {
data := sload(
/* slot */
0xab90edbe8f424080ec4ee1e9062e8b7540cbbfd5f4287285e52611030e58b8d4
)
}
mintingClosed = (data == 1);
}
/**
* @dev Sets the minting status to closed in storage slot.
*/
function setMintingClosed() public onlyOwner {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.mintingClosed')) - 1);
uint256 data = 1;
assembly {
sstore(
/* slot */
0xab90edbe8f424080ec4ee1e9062e8b7540cbbfd5f4287285e52611030e58b8d4,
data
)
}
}
/**
* @dev Gets the token limit from storage slot.
* @return tokenLimit Maximum number of tokens that can be minted.
*/
function getTokenLimit() public view returns (uint256 tokenLimit) {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.tokenLimit')) - 1);
assembly {
tokenLimit := sload(
/* slot */
0xb63653e470fa8e7fcc528e0068173a1969fdee5ae0ee29dd58e7b6111b829c56
)
}
}
/**
* @dev Sets the token limit to storage slot.
* @param tokenLimit Maximum number of tokens that can be minted.
*/
function setTokenLimit(uint256 tokenLimit) public onlyOwner {
require(getTokenLimit() == 0, "CXIP: token limit already set");
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.tokenLimit')) - 1);
assembly {
sstore(
/* slot */
0xb63653e470fa8e7fcc528e0068173a1969fdee5ae0ee29dd58e7b6111b829c56,
tokenLimit
)
}
}
/**
* @dev Gets the token separator from storage slot.
* @return tokenSeparator The number of tokens before separation.
*/
function getTokenSeparator() public view returns (uint256 tokenSeparator) {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.tokenSeparator')) - 1);
assembly {
tokenSeparator := sload(
/* slot */
0x988145eec05de02f4c5d4ecd419a9617237db574d35b27207657cbd8c5b1f045
)
}
}
/**
* @dev Sets the token separator to storage slot.
* @param tokenSeparator The number of tokens before separation.
*/
function setTokenSeparator(uint256 tokenSeparator) public onlyOwner {
require(getTokenSeparator() == 0, "CXIP: separator already set");
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.tokenSeparator')) - 1);
assembly {
sstore(
/* slot */
0x988145eec05de02f4c5d4ecd419a9617237db574d35b27207657cbd8c5b1f045,
tokenSeparator
)
}
}
/**
* @notice Set an NFT state.
* @dev Time-based states will be retrieved by index.
* @param id The index of time slot to set for.
* @param tokenData The token data for the particular time slot.
*/
function prepareMintData(uint256 id, TokenData calldata tokenData) public onlyOwner {
require(Address.isZero(_tokenData[id].creator), "CXIP: token data already set");
_tokenData[id] = tokenData;
}
function prepareMintDataBatch(uint256[] calldata ids, TokenData[] calldata tokenData) public onlyOwner {
require(ids.length == tokenData.length, "CXIP: array lengths missmatch");
for (uint256 i = 0; i < ids.length; i++) {
require(Address.isZero(_tokenData[ids[i]].creator), "CXIP: token data already set");
_tokenData[ids[i]] = tokenData[i];
}
}
/**
* @notice Sets a name for the collection.
* @dev The name is split in two for gas optimization.
* @param newName First part of name.
* @param newName2 Second part of name.
*/
function setName(bytes32 newName, bytes32 newName2) public onlyOwner {
_collectionData.name = newName;
_collectionData.name2 = newName2;
}
/**
* @notice Sets the start timestamp for token rotations.
* @dev All rotation calculations will use this timestamp as the origin point from which to calculate.
* @param _timestamp UNIX timestamp in seconds.
*/
function setStartTimestamp(uint256 _timestamp) public onlyOwner {
// The slot hash has been precomputed for gas optimizaion
// bytes32 slot = bytes32(uint256(keccak256('eip1967.CXIP.DanielArshamErosions.startTimestamp')) - 1);
assembly {
sstore(
/* slot */
0xf2aaccfcfa4e77d7601ed4ebe139368f313960f63d25a2f26ec905d019eba48b,
_timestamp
)
}
}
/**
* @notice Set a symbol for the collection.
* @dev This is the ticker symbol for smart contract that shows up on EtherScan.
* @param newSymbol The ticker symbol to set for smart contract.
*/
function setSymbol(bytes32 newSymbol) public onlyOwner {
_collectionData.symbol = newSymbol;
}
/**
* @notice Transfers ownership of the collection.
* @dev Can't be the zero address.
* @param newOwner Address of new owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(!Address.isZero(newOwner), "CXIP: zero address");
_owner = newOwner;
}
/**
* @notice Get total number of tokens owned by wallet.
* @dev Used to see total amount of tokens owned by a specific wallet.
* @param wallet Address for which to get token balance.
* @return uint256 Returns an integer, representing total amount of tokens held by address.
*/
function balanceOf(address wallet) public view returns (uint256) {
require(!Address.isZero(wallet), "CXIP: zero address");
return _ownedTokensCount[wallet];
}
/**
* @notice Get a base URI for the token.
* @dev Concatenates with the CXIP domain name.
* @return string the token URI.
*/
function baseURI() public view returns (string memory) {
return string(abi.encodePacked("https://nft.cxip.io/", Strings.toHexString(address(this))));
}
/**
* @notice Gets the approved address for the token.
* @dev Single operator set for a specific token. Usually used for one-time very specific authorisations.
* @param tokenId Token id to get approved operator for.
* @return address Approved address for token.
*/
function getApproved(uint256 tokenId) public view returns (address) {
return _tokenApprovals[tokenId];
}
/**
* @notice Get the associated identity for the collection.
* @dev Goes up the chain to read from the registry.
* @return address Identity contract address.
*/
function getIdentity() public view returns (address) {
return ICxipProvenance(getRegistry().getProvenance()).getWalletIdentity(_owner);
}
/**
* @notice Checks if the address is approved.
* @dev Includes references to OpenSea and Rarible marketplace proxies.
* @param wallet Address of the wallet.
* @param operator Address of the marketplace operator.
* @return bool True if approved.
*/
function isApprovedForAll(address wallet, address operator) public view returns (bool) {
return _operatorApprovals[wallet][operator];
}
/**
* @notice Check if the sender is the owner.
* @dev The owner could also be the admin or identity contract of the owner.
* @return bool True if owner.
*/
function isOwner() public view returns (bool) {
return (msg.sender == _owner || msg.sender == _admin || isIdentityWallet(msg.sender));
}
/**
* @notice Gets the owner's address.
* @dev _owner is first set in init.
* @return address Of ower.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @notice Checks who the owner of a token is.
* @dev The token must exist.
* @param tokenId The token to look up.
* @return address Owner of the token.
*/
function ownerOf(uint256 tokenId) public view returns (address) {
address tokenOwner = _tokenOwner[tokenId];
require(!Address.isZero(tokenOwner), "ERC721: token does not exist");
return tokenOwner;
}
/**
* @notice Get token by index.
* @dev Used in conjunction with totalSupply function to iterate over all tokens in collection.
* @param index Index of token in array.
* @return uint256 Returns the token id of token located at that index.
*/
function tokenByIndex(uint256 index) public view returns (uint256) {
require(index < totalSupply(), "CXIP: index out of bounds");
return _allTokens[index];
}
/**
* @notice Get token from wallet by index instead of token id.
* @dev Helpful for wallet token enumeration where token id info is not yet available. Use in conjunction with balanceOf function.
* @param wallet Specific address for which to get token for.
* @param index Index of token in array.
* @return uint256 Returns the token id of token located at that index in specified wallet.
*/
function tokenOfOwnerByIndex(address wallet, uint256 index) public view returns (uint256) {
require(index < balanceOf(wallet), "CXIP: index out of bounds");
return _ownedTokens[wallet][index];
}
/**
* @notice Total amount of tokens in the collection.
* @dev Ignores burned tokens.
* @return uint256 Returns the total number of active (not burned) tokens.
*/
function totalSupply() public view returns (uint256) {
return _allTokens.length;
}
/**
* @notice Empty function that is triggered by external contract on NFT transfer.
* @dev We have this blank function in place to make sure that external contract sending in NFTs don't error out.
* @dev Since it's not being used, the _operator variable is commented out to avoid compiler warnings.
* @dev Since it's not being used, the _from variable is commented out to avoid compiler warnings.
* @dev Since it's not being used, the _tokenId variable is commented out to avoid compiler warnings.
* @dev Since it's not being used, the _data variable is commented out to avoid compiler warnings.
* @return bytes4 Returns the interfaceId of onERC721Received.
*/
function onERC721Received(
address,
/*_operator*/
address,
/*_from*/
uint256,
/*_tokenId*/
bytes calldata /*_data*/
) public pure returns (bytes4) {
return 0x150b7a02;
}
/**
* @notice Allows retrieval of royalties from the contract.
* @dev This is a default fallback to ensure the royalties are available.
*/
function _royaltiesFallback() internal {
address _target = getRegistry().getPA1D();
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), _target, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {
revert(0, returndatasize())
}
default {
return(0, returndatasize())
}
}
}
/**
* @notice Checks if an address is an identity contract.
* @dev It must also be registred.
* @param sender Address to check if registered to identity.
* @return bool True if registred identity.
*/
function isIdentityWallet(address sender) internal view returns (bool) {
address identity = getIdentity();
if (Address.isZero(identity)) {
return false;
}
return ICxipIdentity(identity).isWalletRegistered(sender);
}
/**
* @dev Get the top-level CXIP Registry smart contract. Function must always be internal to prevent miss-use/abuse through bad programming practices.
* @return ICxipRegistry The address of the top-level CXIP Registry smart contract.
*/
function getRegistry() internal pure returns (ICxipRegistry) {
return ICxipRegistry(0xC267d41f81308D7773ecB3BDd863a902ACC01Ade);
}
/**
* @dev Add a newly minted token into managed list of tokens.
* @param to Address of token owner for which to add the token.
* @param tokenId Id of token to add.
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
_ownedTokensIndex[tokenId] = _ownedTokensCount[to];
_ownedTokensCount[to]++;
_ownedTokens[to].push(tokenId);
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @notice Deletes a token from the approval list.
* @dev Removes from count.
* @param tokenId T.
*/
function _clearApproval(uint256 tokenId) private {
delete _tokenApprovals[tokenId];
}
/**
* @notice Mints an NFT.
* @dev Can to mint the token to the zero address and the token cannot already exist.
* @param to Address to mint to.
* @param tokenId The new token.
*/
function _mint(address to, uint256 tokenId) private {
require(!Address.isZero(to), "CXIP: can't mint a burn");
require(!_exists(tokenId), "CXIP: token already exists");
_tokenOwner[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId;
_allTokensIndex[lastTokenId] = tokenIndex;
delete _allTokensIndex[tokenId];
delete _allTokens[lastTokenIndex];
_allTokens.pop();
}
/**
* @dev Remove a token from managed list of tokens.
* @param from Address of token owner for which to remove the token.
* @param tokenId Id of token to remove.
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
_removeTokenFromAllTokensEnumeration(tokenId);
_ownedTokensCount[from]--;
uint256 lastTokenIndex = _ownedTokensCount[from];
uint256 tokenIndex = _ownedTokensIndex[tokenId];
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId;
_ownedTokensIndex[lastTokenId] = tokenIndex;
}
if (lastTokenIndex == 0) {
delete _ownedTokens[from];
} else {
delete _ownedTokens[from][lastTokenIndex];
_ownedTokens[from].pop();
}
}
/**
* @dev Primary internal function that handles the transfer/mint/burn functionality.
* @param from Address from where token is being transferred. Zero address means it is being minted.
* @param to Address to whom the token is being transferred. Zero address means it is being burned.
* @param tokenId Id of token that is being transferred/minted/burned.
*/
function _transferFrom(
address from,
address to,
uint256 tokenId
) private {
require(_tokenOwner[tokenId] == from, "CXIP: not from's token");
require(!Address.isZero(to), "CXIP: use burn instead");
_clearApproval(tokenId);
_tokenOwner[tokenId] = to;
emit Transfer(from, to, tokenId);
_removeTokenFromOwnerEnumeration(from, tokenId);
_addTokenToOwnerEnumeration(to, tokenId);
}
/**
* @notice Checks if the token owner exists.
* @dev If the address is the zero address no owner exists.
* @param tokenId The affected token.
* @return bool True if it exists.
*/
function _exists(uint256 tokenId) private view returns (bool) {
address tokenOwner = _tokenOwner[tokenId];
return !Address.isZero(tokenOwner);
}
/**
* @notice Checks if the address is an approved one.
* @dev Uses inlined checks for different usecases of approval.
* @param spender Address of the spender.
* @param tokenId The affected token.
* @return bool True if approved.
*/
function _isApproved(address spender, uint256 tokenId) private view returns (bool) {
require(_exists(tokenId));
address tokenOwner = _tokenOwner[tokenId];
return (spender == tokenOwner || getApproved(tokenId) == spender || isApprovedForAll(tokenOwner, spender));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
contract OpenSeaOwnableDelegateProxy {}
contract OpenSeaProxyRegistry {
mapping(address => OpenSeaOwnableDelegateProxy) public proxies;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
interface IERC165 {
function supportsInterface(bytes4 interfaceID) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
import "../struct/CollectionData.sol";
import "../struct/TokenData.sol";
import "../struct/Verification.sol";
interface ICxipERC721 {
function arweaveURI(uint256 tokenId) external view returns (string memory);
function contractURI() external view returns (string memory);
function creator(uint256 tokenId) external view returns (address);
function httpURI(uint256 tokenId) external view returns (string memory);
function ipfsURI(uint256 tokenId) external view returns (string memory);
function name() external view returns (string memory);
function payloadHash(uint256 tokenId) external view returns (bytes32);
function payloadSignature(uint256 tokenId) external view returns (Verification memory);
function payloadSigner(uint256 tokenId) external view returns (address);
function supportsInterface(bytes4 interfaceId) external view returns (bool);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
function tokensOfOwner(address wallet) external view returns (uint256[] memory);
function verifySHA256(bytes32 hash, bytes calldata payload) external pure returns (bool);
function approve(address to, uint256 tokenId) external;
function burn(uint256 tokenId) external;
function init(address newOwner, CollectionData calldata collectionData) external;
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external payable;
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) external payable;
function setApprovalForAll(address to, bool approved) external;
function transferFrom(
address from,
address to,
uint256 tokenId
) external payable;
function transferFrom(
address from,
address to,
uint256 tokenId,
bytes memory data
) external payable;
function cxipMint(uint256 id, TokenData calldata tokenData) external returns (uint256);
function setApprovalForAll(
address from,
address to,
bool approved
) external;
function setName(bytes32 newName, bytes32 newName2) external;
function setSymbol(bytes32 newSymbol) external;
function transferOwnership(address newOwner) external;
function balanceOf(address wallet) external view returns (uint256);
function baseURI() external view returns (string memory);
function getApproved(uint256 tokenId) external view returns (address);
function getIdentity() external view returns (address);
function isApprovedForAll(address wallet, address operator) external view returns (bool);
function isOwner() external view returns (bool);
function owner() external view returns (address);
function ownerOf(uint256 tokenId) external view returns (address);
function tokenByIndex(uint256 index) external view returns (uint256);
function tokenOfOwnerByIndex(address wallet, uint256 index) external view returns (uint256);
function totalSupply() external view returns (uint256);
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external pure returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
import "../struct/CollectionData.sol";
import "../struct/InterfaceType.sol";
import "../struct/Token.sol";
import "../struct/TokenData.sol";
interface ICxipIdentity {
function addSignedWallet(
address newWallet,
uint8 v,
bytes32 r,
bytes32 s
) external;
function addWallet(address newWallet) external;
function connectWallet() external;
function createERC721Token(
address collection,
uint256 id,
TokenData calldata tokenData,
Verification calldata verification
) external returns (uint256);
function createERC721Collection(
bytes32 saltHash,
address collectionCreator,
Verification calldata verification,
CollectionData calldata collectionData
) external returns (address);
function createCustomERC721Collection(
bytes32 saltHash,
address collectionCreator,
Verification calldata verification,
CollectionData calldata collectionData,
bytes32 slot,
bytes memory bytecode
) external returns (address);
function init(address wallet, address secondaryWallet) external;
function getAuthorizer(address wallet) external view returns (address);
function getCollectionById(uint256 index) external view returns (address);
function getCollectionType(address collection) external view returns (InterfaceType);
function getWallets() external view returns (address[] memory);
function isCollectionCertified(address collection) external view returns (bool);
function isCollectionRegistered(address collection) external view returns (bool);
function isNew() external view returns (bool);
function isOwner() external view returns (bool);
function isTokenCertified(address collection, uint256 tokenId) external view returns (bool);
function isTokenRegistered(address collection, uint256 tokenId) external view returns (bool);
function isWalletRegistered(address wallet) external view returns (bool);
function listCollections(uint256 offset, uint256 length)
external
view
returns (address[] memory);
function nextNonce(address wallet) external view returns (uint256);
function totalCollections() external view returns (uint256);
function isCollectionOpen(address collection) external pure returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
interface ICxipProvenance {
function createIdentity(
bytes32 saltHash,
address wallet,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256, address);
function createIdentityBatch(
bytes32 saltHash,
address[] memory wallets,
uint8[] memory V,
bytes32[] memory RS
) external returns (uint256, address);
function getIdentity() external view returns (address);
function getWalletIdentity(address wallet) external view returns (address);
function informAboutNewWallet(address newWallet) external;
function isIdentityValid(address identity) external view returns (bool);
function nextNonce(address wallet) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
interface ICxipRegistry {
function getAsset() external view returns (address);
function getAssetSigner() external view returns (address);
function getAssetSource() external view returns (address);
function getCopyright() external view returns (address);
function getCopyrightSource() external view returns (address);
function getCustomSource(bytes32 name) external view returns (address);
function getCustomSourceFromString(string memory name) external view returns (address);
function getERC1155CollectionSource() external view returns (address);
function getERC721CollectionSource() external view returns (address);
function getIdentitySource() external view returns (address);
function getPA1D() external view returns (address);
function getPA1DSource() external view returns (address);
function getProvenance() external view returns (address);
function getProvenanceSource() external view returns (address);
function owner() external view returns (address);
function setAsset(address proxy) external;
function setAssetSigner(address source) external;
function setAssetSource(address source) external;
function setCopyright(address proxy) external;
function setCopyrightSource(address source) external;
function setCustomSource(string memory name, address source) external;
function setERC1155CollectionSource(address source) external;
function setERC721CollectionSource(address source) external;
function setIdentitySource(address source) external;
function setPA1D(address proxy) external;
function setPA1DSource(address source) external;
function setProvenance(address proxy) external;
function setProvenanceSource(address source) external;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
import "../library/Zora.sol";
interface IPA1D {
function init(
uint256 tokenId,
address payable receiver,
uint256 bp
) external;
function configurePayouts(address payable[] memory addresses, uint256[] memory bps) external;
function getPayoutInfo()
external
view
returns (address payable[] memory addresses, uint256[] memory bps);
function getEthPayout() external;
function getTokenPayout(address tokenAddress) external;
function getTokenPayoutByName(string memory tokenName) external;
function getTokensPayout(address[] memory tokenAddresses) external;
function getTokensPayoutByName(string[] memory tokenNames) external;
function supportsInterface(bytes4 interfaceId) external pure returns (bool);
function setRoyalties(
uint256 tokenId,
address payable receiver,
uint256 bp
) external;
function royaltyInfo(uint256 tokenId, uint256 value) external view returns (address, uint256);
function getFeeBps(uint256 tokenId) external view returns (uint256[] memory);
function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory);
function getRoyalties(uint256 tokenId)
external
view
returns (address payable[] memory, uint256[] memory);
function getFees(uint256 tokenId)
external
view
returns (address payable[] memory, uint256[] memory);
function tokenCreator(address contractAddress, uint256 tokenId) external view returns (address);
function calculateRoyaltyFee(
address contractAddress,
uint256 tokenId,
uint256 amount
) external view returns (uint256);
function marketContract() external view returns (address);
function tokenCreators(uint256 tokenId) external view returns (address);
function bidSharesForToken(uint256 tokenId)
external
view
returns (Zora.BidShares memory bidShares);
function getStorageSlot(string calldata slot) external pure returns (bytes32);
function getTokenAddress(string memory tokenName) external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
library Address {
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
assembly {
codehash := extcodehash(account)
}
return (codehash != 0x0 &&
codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
function isZero(address account) internal pure returns (bool) {
return (account == address(0));
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
library Bytes {
function getBoolean(uint192 _packedBools, uint192 _boolNumber) internal pure returns (bool) {
uint192 flag = (_packedBools >> _boolNumber) & uint192(1);
return (flag == 1 ? true : false);
}
function setBoolean(
uint192 _packedBools,
uint192 _boolNumber,
bool _value
) internal pure returns (uint192) {
if (_value) {
return _packedBools | (uint192(1) << _boolNumber);
} else {
return _packedBools & ~(uint192(1) << _boolNumber);
}
}
function slice(
bytes memory _bytes,
uint256 _start,
uint256 _length
) internal pure returns (bytes memory) {
require(_length + 31 >= _length, "slice_overflow");
require(_bytes.length >= _start + _length, "slice_outOfBounds");
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
tempBytes := mload(0x40)
let lengthmod := and(_length, 31)
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
mstore(0x40, and(add(mc, 31), not(31)))
}
default {
tempBytes := mload(0x40)
mstore(tempBytes, 0)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function trim(bytes32 source) internal pure returns (bytes memory) {
uint256 temp = uint256(source);
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return slice(abi.encodePacked(source), 32 - length, length);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
library Strings {
function toHexString(address account) internal pure returns (string memory) {
return toHexString(uint256(uint160(account)));
}
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);
}
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] = bytes16("0123456789abcdef")[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
import "./UriType.sol";
struct CollectionData {
bytes32 name;
bytes32 name2;
bytes32 symbol;
address royalties;
uint96 bps;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
import "./Verification.sol";
struct TokenData {
bytes32 payloadHash;
Verification payloadSignature;
address creator;
bytes32 arweave;
bytes11 arweave2;
bytes32 ipfs;
bytes14 ipfs2;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
struct Verification {
bytes32 r;
bytes32 s;
uint8 v;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
// This is a 256 value limit (uint8)
enum UriType {
ARWEAVE, // 0
IPFS, // 1
HTTP // 2
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
// This is a 256 value limit (uint8)
enum InterfaceType {
NULL, // 0
ERC20, // 1
ERC721, // 2
ERC1155 // 3
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
import "./InterfaceType.sol";
struct Token {
address collection;
uint256 tokenId;
InterfaceType tokenType;
address creator;
}
// SPDX-License-Identifier: MIT
pragma solidity 0.8.12;
/*______/\\\\\\\\\__/\\\_______/\\\__/\\\\\\\\\\\__/\\\\\\\\\\\\\___
_____/\\\////////__\///\\\___/\\\/__\/////\\\///__\/\\\/////////\\\_
___/\\\/_____________\///\\\\\\/________\/\\\_____\/\\\_______\/\\\_
__/\\\_________________\//\\\\__________\/\\\_____\/\\\\\\\\\\\\\/__
_\/\\\__________________\/\\\\__________\/\\\_____\/\\\/////////____
_\//\\\_________________/\\\\\\_________\/\\\_____\/\\\_____________
__\///\\\_____________/\\\////\\\_______\/\\\_____\/\\\_____________
____\////\\\\\\\\\__/\\\/___\///\\\__/\\\\\\\\\\\_\/\\\_____________
_______\/////////__\///_______\///__\///////////__\///____________*/
library Zora {
struct Decimal {
uint256 value;
}
struct BidShares {
// % of sale value that goes to the _previous_ owner of the nft
Decimal prevOwner;
// % of sale value that goes to the original creator of the nft
Decimal creator;
// % of sale value that goes to the seller (current owner) of the nft
Decimal owner;
}
}
|
Transfers ownership of the collection. Can't be the zero address. newOwner Address of new owner./
|
function transferOwnership(address newOwner) public onlyOwner {
require(!Address.isZero(newOwner), "CXIP: zero address");
_owner = newOwner;
}
| 1,359,583
|
pragma solidity ^0.5.0;
import './ERCX.sol';
import '../Interface/IERCXMetadata.sol';
contract ERCXMetadata is ERC165, ERCX, IERCXMetadata {
// item name
string internal _name;
// item symbol
string internal _symbol;
// Base URI
string private _baseURI;
// Optional mapping for item URIs
mapping(uint256 => string) private _itemURIs;
bytes4 private constant InterfaceId_ERCXMetadata =
bytes4(keccak256('name()')) ^
bytes4(keccak256('symbol()')) ^
bytes4(keccak256('itemURI(uint256)'));
/**
* @dev Constructor function
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
// register the supported interfaces to conform to ERCX via ERC165
_registerInterface(InterfaceId_ERCXMetadata);
}
/**
* @dev Gets the item name
* @return string representing the item name
*/
function name() external view returns (string memory) {
return _name;
}
/**
* @dev Gets the item symbol
* @return string representing the item symbol
*/
function symbol() external view returns (string memory) {
return _symbol;
}
/**
* @dev Returns an URI for a given item ID
* Throws if the item ID does not exist. May return an empty string.
* @param itemId uint256 ID of the item to query
*/
function itemURI(uint256 itemId) public view returns (string memory) {
require(
_exists(itemId,1),
"URI query for nonexistent item");
string memory _itemURI = _itemURIs[itemId];
// Even if there is a base URI, it is only appended to non-empty item-specific URIs
if (bytes(_itemURI).length == 0) {
return "";
} else {
// abi.encodePacked is being used to concatenate strings
return string(abi.encodePacked(_baseURI, _itemURI));
}
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a preffix in {itemURI} to each item's URI, when
* they are non-empty.
*/
function baseURI() external view returns (string memory) {
return _baseURI;
}
/**
* @dev Internal function to set the item URI for a given item
* Reverts if the item ID does not exist
* @param itemId uint256 ID of the item to set its URI
* @param uri string URI to assign
*/
function _setItemURI(uint256 itemId, string memory uri) internal {
require(_exists(itemId,1));
_itemURIs[itemId] = uri;
}
/**
* @dev Internal function to set the base URI for all item IDs. It is
* automatically added as a prefix to the value returned in {itemURI}.
*
* _Available since v2.5.0._
*/
function _setBaseURI(string memory baseUri) internal {
_baseURI = baseUri;
}
/**
* @dev Internal function to burn a specific item
* Reverts if the item does not exist
* @param itemId uint256 ID of the item being burned by the msg.sender
*/
function _burn(uint256 itemId) internal {
super._burn(itemId);
// Clear metadata (if any)
if (bytes(_itemURIs[itemId]).length != 0) {
delete _itemURIs[itemId];
}
}
}
|
Internal function to set the base URI for all item IDs. It is automatically added as a prefix to the value returned in {itemURI}. _Available since v2.5.0._/
|
function _setBaseURI(string memory baseUri) internal {
_baseURI = baseUri;
}
| 12,610,834
|
// SPDX-License-Identifier: GPL-2.0
pragma solidity 0.8.8;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/security/ReentrancyGuard.sol";
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/utils/structs/EnumerableSet.sol";
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
interface IWETH {
function deposit() external payable;
function transfer(address to, uint256 value) external returns (bool);
function withdraw(uint256) external;
}
interface IUniswapV2Factory {
function getPair(address tokenA, address tokenB)
external
view
returns (address);
}
interface IUniswapV2Pair {
function token0() external pure returns (address);
function token1() external pure returns (address);
function getReserves()
external
view
returns (
uint112 _reserve0,
uint112 _reserve1,
uint32 _blockTimestampLast
);
}
interface IUniswapV2Router02 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityETH(
address token,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETH(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityETHWithPermit(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
function swapExactTokensForTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactETHForTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function swapTokensForExactETH(
uint256 amountOut,
uint256 amountInMax,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapExactTokensForETH(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external returns (uint256[] memory amounts);
function swapETHForExactTokens(
uint256 amountOut,
address[] calldata path,
address to,
uint256 deadline
) external payable returns (uint256[] memory amounts);
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint256 amountIn,
uint256 amountOutMin,
address[] calldata path,
address to,
uint256 deadline
) external;
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
function getAmountOut(
uint256 amountIn,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountOut);
function getAmountIn(
uint256 amountOut,
uint256 reserveIn,
uint256 reserveOut
) external pure returns (uint256 amountIn);
function getAmountsOut(uint256 amountIn, address[] calldata path)
external
view
returns (uint256[] memory amounts);
function getAmountsIn(uint256 amountOut, address[] calldata path)
external
view
returns (uint256[] memory amounts);
}
abstract contract Zap {
using SafeERC20 for IERC20;
using SafeMath for uint256;
IERC20 public immutable koromaru; // Koromaru token
IERC20 public immutable koromaruUniV2; // Uniswap V2 LP token for Koromaru
IUniswapV2Factory public immutable UniSwapV2FactoryAddress;
IUniswapV2Router02 public uniswapRouter;
address public immutable WETHAddress;
uint256 private constant swapDeadline =
0xf000000000000000000000000000000000000000000000000000000000000000;
struct ZapVariables {
uint256 LP;
uint256 koroAmount;
uint256 wethAmount;
address tokenToZap;
uint256 amountToZap;
}
event ZappedIn(address indexed account, uint256 amount);
event ZappedOut(
address indexed account,
uint256 amount,
uint256 koroAmount,
uint256 Eth
);
constructor(
address _koromaru,
address _koromaruUniV2,
address _UniSwapV2FactoryAddress,
address _uniswapRouter
) {
koromaru = IERC20(_koromaru);
koromaruUniV2 = IERC20(_koromaruUniV2);
UniSwapV2FactoryAddress = IUniswapV2Factory(_UniSwapV2FactoryAddress);
uniswapRouter = IUniswapV2Router02(_uniswapRouter);
WETHAddress = uniswapRouter.WETH();
}
function ZapIn(uint256 _amount, bool _multi)
internal
returns (
uint256 _LP,
uint256 _WETHBalance,
uint256 _KoromaruBalance
)
{
(uint256 _koroAmount, uint256 _ethAmount) = _moveTokensToContract(
_amount
);
_approveRouterIfNotApproved();
(_LP, _WETHBalance, _KoromaruBalance) = !_multi
? _zapIn(_koroAmount, _ethAmount)
: _zapInMulti(_koroAmount, _ethAmount);
require(_LP > 0, "ZapIn: Invalid LP amount");
emit ZappedIn(msg.sender, _LP);
}
function zapOut(uint256 _koroLPAmount)
internal
returns (uint256 _koroTokens, uint256 _ether)
{
_approveRouterIfNotApproved();
uint256 balanceBefore = koromaru.balanceOf(address(this));
_ether = uniswapRouter.removeLiquidityETHSupportingFeeOnTransferTokens(
address(koromaru),
_koroLPAmount,
1,
1,
address(this),
swapDeadline
);
require(_ether > 0, "ZapOut: Eth Output Low");
uint256 balanceAfter = koromaru.balanceOf(address(this));
require(balanceAfter > balanceBefore, "ZapOut: Nothing to ZapOut");
_koroTokens = balanceAfter.sub(balanceBefore);
emit ZappedOut(msg.sender, _koroLPAmount, _koroTokens, _ether);
}
//-------------------- Zap Utils -------------------------
function _zapIn(uint256 _koroAmount, uint256 _wethAmount)
internal
returns (
uint256 _LP,
uint256 _WETHBalance,
uint256 _KoromaruBalance
)
{
ZapVariables memory zapVars;
zapVars.tokenToZap; // koro or eth
zapVars.amountToZap; // koro or weth
(address _Token0, address _Token1) = _getKoroLPPairs(
address(koromaruUniV2)
);
if (_koroAmount > 0 && _wethAmount < 1) {
// if only koro
zapVars.amountToZap = _koroAmount;
zapVars.tokenToZap = address(koromaru);
} else if (_wethAmount > 0 && _koroAmount < 1) {
// if only weth
zapVars.amountToZap = _wethAmount;
zapVars.tokenToZap = WETHAddress;
}
(uint256 token0Out, uint256 token1Out) = _executeSwapForPairs(
zapVars.tokenToZap,
_Token0,
_Token1,
zapVars.amountToZap
);
(_LP, _WETHBalance, _KoromaruBalance) = _toLiquidity(
_Token0,
_Token1,
token0Out,
token1Out
);
}
function _zapInMulti(uint256 _koroAmount, uint256 _wethAmount)
internal
returns (
uint256 _LPToken,
uint256 _WETHBalance,
uint256 _KoromaruBalance
)
{
ZapVariables memory zapVars;
zapVars.koroAmount = _koroAmount;
zapVars.wethAmount = _wethAmount;
zapVars.tokenToZap; // koro or eth
zapVars.amountToZap; // koro or weth
{
(
uint256 _kLP,
uint256 _kWETHBalance,
uint256 _kKoromaruBalance
) = _zapIn(zapVars.koroAmount, 0);
_LPToken += _kLP;
_WETHBalance += _kWETHBalance;
_KoromaruBalance += _kKoromaruBalance;
}
{
(
uint256 _kLP,
uint256 _kWETHBalance,
uint256 _kKoromaruBalance
) = _zapIn(0, zapVars.wethAmount);
_LPToken += _kLP;
_WETHBalance += _kWETHBalance;
_KoromaruBalance += _kKoromaruBalance;
}
}
function _toLiquidity(
address _Token0,
address _Token1,
uint256 token0Out,
uint256 token1Out
)
internal
returns (
uint256 _LP,
uint256 _WETHBalance,
uint256 _KoromaruBalance
)
{
_approveToken(_Token0, address(uniswapRouter), token0Out);
_approveToken(_Token1, address(uniswapRouter), token1Out);
(uint256 amountA, uint256 amountB, uint256 LP) = uniswapRouter
.addLiquidity(
_Token0,
_Token1,
token0Out,
token1Out,
1,
1,
address(this),
swapDeadline
);
_LP = LP;
_WETHBalance = token0Out.sub(amountA);
_KoromaruBalance = token1Out.sub(amountB);
}
function _approveRouterIfNotApproved() private {
if (koromaru.allowance(address(this), address(uniswapRouter)) == 0) {
koromaru.approve(address(uniswapRouter), type(uint256).max);
}
if (
koromaruUniV2.allowance(address(this), address(uniswapRouter)) == 0
) {
koromaruUniV2.approve(address(uniswapRouter), type(uint256).max);
}
}
function _moveTokensToContract(uint256 _amount)
internal
returns (uint256 _koroAmount, uint256 _ethAmount)
{
_ethAmount = msg.value;
if (msg.value > 0) IWETH(WETHAddress).deposit{value: _ethAmount}();
if (msg.value < 1) {
// ZapIn must have either both Koro and Eth, just Eth or just Koro
require(_amount > 0, "KOROFARM: Invalid ZapIn Call");
}
if (_amount > 0) {
koromaru.safeTransferFrom(msg.sender, address(this), _amount);
}
_koroAmount = _amount;
}
function _getKoroLPPairs(address _pairAddress)
internal
pure
returns (address token0, address token1)
{
IUniswapV2Pair uniPair = IUniswapV2Pair(_pairAddress);
token0 = uniPair.token0();
token1 = uniPair.token1();
}
function _executeSwapForPairs(
address _inToken,
address _token0,
address _token1,
uint256 _amount
) internal returns (uint256 _token0Out, uint256 _token1Out) {
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
if (_inToken == _token0) {
uint256 swapAmount = determineSwapInAmount(resv0, _amount);
if (swapAmount < 1) swapAmount = _amount.div(2);
// swap Weth tokens to koro
_token1Out = _swapTokenForToken(_inToken, _token1, swapAmount);
_token0Out = _amount.sub(swapAmount);
} else {
uint256 swapAmount = determineSwapInAmount(resv1, _amount);
if (swapAmount < 1) swapAmount = _amount.div(2);
_token0Out = _swapTokenForToken(_inToken, _token0, swapAmount);
_token1Out = _amount.sub(swapAmount);
}
}
function _swapTokenForToken(
address _swapFrom,
address _swapTo,
uint256 _tokensToSwap
) internal returns (uint256 tokenBought) {
if (_swapFrom == _swapTo) {
return _tokensToSwap;
}
_approveToken(
_swapFrom,
address(uniswapRouter),
_tokensToSwap.mul(1e12)
);
address pair = UniSwapV2FactoryAddress.getPair(_swapFrom, _swapTo);
require(pair != address(0), "SwapTokenForToken: Swap path error");
address[] memory path = new address[](2);
path[0] = _swapFrom;
path[1] = _swapTo;
uint256 balanceBefore = IERC20(_swapTo).balanceOf(address(this));
uniswapRouter.swapExactTokensForTokensSupportingFeeOnTransferTokens(
_tokensToSwap,
0,
path,
address(this),
swapDeadline
);
uint256 balanceAfter = IERC20(_swapTo).balanceOf(address(this));
tokenBought = balanceAfter.sub(balanceBefore);
// Ideal, but fails to work with Koromary due to fees
// tokenBought = uniswapRouter.swapExactTokensForTokens(
// _tokensToSwap,
// 1,
// path,
// address(this),
// swapDeadline
// )[path.length - 1];
// }
require(tokenBought > 0, "SwapTokenForToken: Error Swapping Tokens 2");
}
function determineSwapInAmount(uint256 _pairResIn, uint256 _userAmountIn)
internal
pure
returns (uint256)
{
return
(_sqrt(
_pairResIn *
((_userAmountIn * 3988000) + (_pairResIn * 3988009))
) - (_pairResIn * 1997)) / 1994;
}
function _sqrt(uint256 _val) internal pure returns (uint256 z) {
if (_val > 3) {
z = _val;
uint256 x = _val / 2 + 1;
while (x < z) {
z = x;
x = (_val / x + x) / 2;
}
} else if (_val != 0) {
z = 1;
}
}
function _approveToken(
address token,
address spender,
uint256 amount
) internal {
IERC20 _token = IERC20(token);
_token.safeApprove(spender, 0);
_token.safeApprove(spender, amount);
}
//---------------- End of Zap Utils ----------------------
}
contract KoroFarms is Ownable, Pausable, ReentrancyGuard, Zap {
using SafeERC20 for IERC20;
using SafeMath for uint256;
using EnumerableSet for EnumerableSet.AddressSet;
struct UserInfo {
uint256 amount;
uint256 koroDebt;
uint256 ethDebt;
uint256 unpaidKoro;
uint256 unpaidEth;
uint256 lastRewardHarvestedTime;
}
struct FarmInfo {
uint256 accKoroRewardsPerShare;
uint256 accEthRewardsPerShare;
uint256 lastRewardTimestamp;
}
AggregatorV3Interface internal priceFeed;
uint256 internal immutable koromaruDecimals;
uint256 internal constant EthPriceFeedDecimal = 1e8;
uint256 internal constant precisionScaleUp = 1e30;
uint256 internal constant secsPerDay = 1 days / 1 seconds;
uint256 private taxRefundPercentage;
uint256 internal constant _1hundred_Percent = 10000;
uint256 public APR; // 100% = 10000, 50% = 5000, 15% = 1500
uint256 rewardHarvestingInterval;
uint256 public koroRewardAllocation;
uint256 public ethRewardAllocation;
uint256 internal maxLPLimit;
uint256 internal zapKoroLimit;
FarmInfo public farmInfo;
mapping(address => UserInfo) public userInfo;
uint256 public totalEthRewarded; // total amount of eth given as rewards
uint256 public totalKoroRewarded; // total amount of Koro given as rewards
//---------------- Contract Events -------------------
event Compound(address indexed account, uint256 koro, uint256 eth);
event Withdraw(address indexed account, uint256 amount);
event Deposit(address indexed account, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 amount);
event KoroRewardsHarvested(address indexed account, uint256 Kororewards);
event EthRewardsHarvested(address indexed account, uint256 Ethrewards);
event APRUpdated(uint256 OldAPR, uint256 NewAPR);
event Paused();
event Unpaused();
event IncreaseKoroRewardPool(uint256 amount);
event IncreaseEthRewardPool(uint256 amount);
//------------- End of Contract Events ----------------
constructor(
address _koromaru,
address _koromaruUniV2,
address _UniSwapV2FactoryAddress,
address _uniswapRouter,
uint256 _apr,
uint256 _taxToRefund,
uint256 _koromaruTokenDecimals,
uint256 _koroRewardAllocation,
uint256 _rewardHarvestingInterval,
uint256 _zapKoroLimit
) Zap(_koromaru, _koromaruUniV2, _UniSwapV2FactoryAddress, _uniswapRouter) {
require(
_koroRewardAllocation <= 10000,
"setRewardAllocations: Invalid rewards allocation"
);
require(_apr <= 10000, "SetDailyAPR: Invalid APR Value");
approveRouterIfNotApproved();
koromaruDecimals = 10**_koromaruTokenDecimals;
zapKoroLimit = _zapKoroLimit * 10**_koromaruTokenDecimals;
APR = _apr;
koroRewardAllocation = _koroRewardAllocation;
ethRewardAllocation = _1hundred_Percent.sub(_koroRewardAllocation);
taxRefundPercentage = _taxToRefund;
farmInfo = FarmInfo({
lastRewardTimestamp: block.timestamp,
accKoroRewardsPerShare: 0,
accEthRewardsPerShare: 0
});
rewardHarvestingInterval = _rewardHarvestingInterval * 1 seconds;
priceFeed = AggregatorV3Interface(
0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419
);
}
//---------------- Contract Owner ----------------------
/**
* @notice Update chainLink Eth Price feed
*/
function updatePriceFeed(address _usdt_eth_aggregator) external onlyOwner {
priceFeed = AggregatorV3Interface(_usdt_eth_aggregator);
}
/**
* @notice Set's tax refund percentage for Koromaru
* @dev User 100% = 10000, 50% = 5000, 15% = 1500 etc.
*/
function setTaxRefundPercent(uint256 _taxToRefund) external onlyOwner {
taxRefundPercentage = _taxToRefund;
}
/**
* @notice Set's max koromaru per transaction
* @dev Decimals will be added automatically
*/
function setZapLimit(uint256 _limit) external onlyOwner {
zapKoroLimit = _limit * koromaruDecimals;
}
/**
* @notice Set's daily ROI percentage for the farm
* @dev User 100% = 10000, 50% = 5000, 15% = 1500 etc.
*/
function setDailyAPR(uint256 _dailyAPR) external onlyOwner {
updateFarm();
require(_dailyAPR <= 10000, "SetDailyAPR: Invalid APR Value");
uint256 oldAPr = APR;
APR = _dailyAPR;
emit APRUpdated(oldAPr, APR);
}
/**
* @notice Set's reward allocation for reward pool
* @dev Set for Koromaru only, eth's allocation will be calcuated. User 100% = 10000, 50% = 5000, 15% = 1500 etc.
*/
function setRewardAllocations(uint256 _koroAllocation) external onlyOwner {
// setting 10000 (100%) will set eth rewards to 0.
require(
_koroAllocation <= 10000,
"setRewardAllocations: Invalid rewards allocation"
);
koroRewardAllocation = _koroAllocation;
ethRewardAllocation = _1hundred_Percent.sub(_koroAllocation);
}
/**
* @notice Set's maximum amount of LPs that can be staked in this farm
* @dev When 0, no limit is imposed. When max is reached farmers cannot stake more LPs or compound.
*/
function setMaxLPLimit(uint256 _maxLPLimit) external onlyOwner {
// A new user’s stake cannot cause the amount of LP tokens in the farm to exceed this value
// MaxLP can be set to 0(nomax)
maxLPLimit = _maxLPLimit;
}
/**
* @notice Reset's the chainLink price feed to the default price feed
*/
function resetPriceFeed() external onlyOwner {
priceFeed = AggregatorV3Interface(
0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419
);
}
/**
* @notice Withdraw foreign tokens sent to this contract
* @dev Can only withdraw none koromaru tokens and KoroV2 tokens
*/
function withdrawForeignToken(address _token)
external
nonReentrant
onlyOwner
{
require(_token != address(0), "KOROFARM: Invalid Token");
require(
_token != address(koromaru),
"KOROFARM: Token cannot be same as koromaru tokens"
);
require(
_token != address(koromaruUniV2),
"KOROFARM: Token cannot be same as farmed tokens"
);
uint256 amount = IERC20(_token).balanceOf(address(this));
if (amount > 0) {
IERC20(_token).safeTransfer(msg.sender, amount);
}
}
/**
* @notice Deposit Koromaru tokens into reward pool
*/
function depositKoroRewards(uint256 _amount)
external
onlyOwner
nonReentrant
{
require(_amount > 0, "KOROFARM: Invalid Koro Amount");
koromaru.safeTransferFrom(msg.sender, address(this), _amount);
emit IncreaseKoroRewardPool(_amount);
}
/**
* @notice Deposit Eth tokens into reward pool
*/
function depositEthRewards() external payable onlyOwner nonReentrant {
require(msg.value > 0, "KOROFARM: Invalid Eth Amount");
emit IncreaseEthRewardPool(msg.value);
}
/**
* @notice This function will pause the farm and withdraw all rewards in case of failure or emergency
*/
function pauseAndRemoveRewardPools() external onlyOwner whenNotPaused {
// only to be used by admin in critical situations
uint256 koroBalance = koromaru.balanceOf(address(this));
uint256 ethBalance = payable(address(this)).balance;
if (koroBalance > 0) {
koromaru.safeTransfer(msg.sender, koroBalance);
}
if (ethBalance > 0) {
(bool sent, ) = payable(msg.sender).call{value: ethBalance}("");
require(sent, "Failed to send Ether");
}
}
/**
* @notice Initiate stopped state
* @dev Only possible when contract not paused.
*/
function pause() external onlyOwner whenNotPaused {
_pause();
emit Paused();
}
/**
* @notice Initiate normal state
* @dev Only possible when contract is paused.
*/
function unpause() external onlyOwner whenPaused {
_unpause();
emit Unpaused();
}
//-------------- End Contract Owner --------------------
//---------------- Contract Farmer ----------------------
/**
* @notice Calculates and returns pending rewards for a farmer
*/
function getPendingRewards(address _farmer)
public
view
returns (uint256 pendinKoroTokens, uint256 pendingEthWei)
{
UserInfo storage user = userInfo[_farmer];
uint256 accKoroRewardsPerShare = farmInfo.accKoroRewardsPerShare;
uint256 accEthRewardsPerShare = farmInfo.accEthRewardsPerShare;
uint256 stakedTVL = getStakedTVL();
if (block.timestamp > farmInfo.lastRewardTimestamp && stakedTVL != 0) {
uint256 timeElapsed = block.timestamp.sub(
farmInfo.lastRewardTimestamp
);
uint256 koroReward = timeElapsed.mul(
getNumberOfKoroRewardsPerSecond(koroRewardAllocation)
);
uint256 ethReward = timeElapsed.mul(
getAmountOfEthRewardsPerSecond(ethRewardAllocation)
);
accKoroRewardsPerShare = accKoroRewardsPerShare.add(
koroReward.mul(precisionScaleUp).div(stakedTVL)
);
accEthRewardsPerShare = accEthRewardsPerShare.add(
ethReward.mul(precisionScaleUp).div(stakedTVL)
);
}
pendinKoroTokens = user
.amount
.mul(accKoroRewardsPerShare)
.div(precisionScaleUp)
.sub(user.koroDebt)
.add(user.unpaidKoro);
pendingEthWei = user
.amount
.mul(accEthRewardsPerShare)
.div(precisionScaleUp)
.sub(user.ethDebt)
.add(user.unpaidEth);
}
/**
* @notice Calculates and returns the TVL in USD staked in the farm
* @dev Uses the price of 1 Koromaru to calculate the TVL in USD
*/
function getStakedTVL() public view returns (uint256) {
uint256 stakedLP = koromaruUniV2.balanceOf(address(this));
uint256 totalLPsupply = koromaruUniV2.totalSupply();
return stakedLP.mul(getTVLUsingKoro()).div(totalLPsupply);
}
/**
* @notice Calculates and updates the farm's rewards per share
* @dev Called by other function to update the function state
*/
function updateFarm() public whenNotPaused returns (FarmInfo memory farm) {
farm = farmInfo;
uint256 WETHBalance = IERC20(WETHAddress).balanceOf(address(this));
if (WETHBalance > 0) IWETH(WETHAddress).withdraw(WETHBalance);
if (block.timestamp > farm.lastRewardTimestamp) {
uint256 stakedTVL = getStakedTVL();
if (stakedTVL > 0) {
uint256 timeElapsed = block.timestamp.sub(
farm.lastRewardTimestamp
);
uint256 koroReward = timeElapsed.mul(
getNumberOfKoroRewardsPerSecond(koroRewardAllocation)
);
uint256 ethReward = timeElapsed.mul(
getAmountOfEthRewardsPerSecond(ethRewardAllocation)
);
farm.accKoroRewardsPerShare = farm.accKoroRewardsPerShare.add(
(koroReward.mul(precisionScaleUp) / stakedTVL)
);
farm.accEthRewardsPerShare = farm.accEthRewardsPerShare.add(
(ethReward.mul(precisionScaleUp) / stakedTVL)
);
}
farm.lastRewardTimestamp = block.timestamp;
farmInfo = farm;
}
}
/**
* @notice Deposit Koromaru tokens into farm
* @dev Deposited Koromaru will zap into Koro/WETH LP tokens, a refund of TX fee % will be issued
*/
function depositKoroTokensOnly(uint256 _amount)
external
whenNotPaused
nonReentrant
{
require(_amount > 0, "KOROFARM: Invalid Koro Amount");
require(
_amount <= zapKoroLimit,
"KOROFARM: Can't deposit more than Zap Limit"
);
(uint256 lpZappedIn, , ) = ZapIn(_amount, false);
// do tax refund
userInfo[msg.sender].unpaidKoro += _amount.mul(taxRefundPercentage).div(
_1hundred_Percent
);
onDeposit(msg.sender, lpZappedIn);
}
/**
* @notice Deposit Koro/WETH LP tokens into farm
*/
function depositKoroLPTokensOnly(uint256 _amount)
external
whenNotPaused
nonReentrant
{
require(_amount > 0, "KOROFARM: Invalid KoroLP Amount");
koromaruUniV2.safeTransferFrom(msg.sender, address(this), _amount);
onDeposit(msg.sender, _amount);
}
/**
* @notice Deposit Koromaru, Koromaru/Eth LP and Eth at once into farm requires all 3
*/
function depositMultipleAssets(uint256 _koro, uint256 _koroLp)
external
payable
whenNotPaused
nonReentrant
{
// require(_koro > 0, "KOROFARM: Invalid Koro Amount");
// require(_koroLp > 0, "KOROFARM: Invalid LP Amount");
require(
_koro <= zapKoroLimit,
"KOROFARM: Can't deposit more than Zap Limit"
);
// execute the zap
// (uint256 lpZappedIn,uint256 wethBalance, uint256 korobalance)= ZapIn(_koro, true);
(uint256 lpZappedIn, , ) = msg.value > 0
? ZapIn(_koro, true)
: ZapIn(_koro, false);
// transfer the lp in
if (_koroLp > 0)
koromaruUniV2.safeTransferFrom(
address(msg.sender),
address(this),
_koroLp
);
uint256 sumOfLps = lpZappedIn + _koroLp;
// do tax refund
userInfo[msg.sender].unpaidKoro += _koro.mul(taxRefundPercentage).div(
_1hundred_Percent
);
onDeposit(msg.sender, sumOfLps);
}
/**
* @notice Deposit Eth only into farm
* @dev Deposited Eth will zap into Koro/WETH LP tokens
*/
function depositEthOnly() external payable whenNotPaused nonReentrant {
require(msg.value > 0, "KOROFARM: Invalid Eth Amount");
// (uint256 lpZappedIn, uint256 wethBalance, uint256 korobalance)= ZapIn(0, false);
(uint256 lpZappedIn, , ) = ZapIn(0, false);
onDeposit(msg.sender, lpZappedIn);
}
/**
* @notice Withdraw all staked LP tokens + rewards from farm. Only possilbe after harvest interval.
Use emergency withdraw if you want to withdraw before harvest interval. No rewards will be returned.
* @dev Farmer's can choose to get back LP tokens or Zap out to get Koromaru and Eth
*/
function withdraw(bool _useZapOut) external whenNotPaused nonReentrant {
uint256 balance = userInfo[msg.sender].amount;
require(balance > 0, "Withdraw: You have no balance");
updateFarm();
if (_useZapOut) {
zapLPOut(balance);
} else {
koromaruUniV2.transfer(msg.sender, balance);
}
onWithdraw(msg.sender);
emit Withdraw(msg.sender, balance);
}
/**
* @notice Harvest all rewards from farm
*/
function harvest() external whenNotPaused nonReentrant {
updateFarm();
harvestRewards(msg.sender);
}
/**
* @notice Compounds rewards from farm. Only available after harvest interval is reached for farmer.
*/
function compound() external whenNotPaused nonReentrant {
updateFarm();
UserInfo storage user = userInfo[msg.sender];
require(
block.timestamp - user.lastRewardHarvestedTime >=
rewardHarvestingInterval,
"HarvestRewards: Not yet ripe"
);
uint256 koroCompounded;
uint256 ethCompounded;
uint256 pendinKoroTokens = user
.amount
.mul(farmInfo.accKoroRewardsPerShare)
.div(precisionScaleUp)
.sub(user.koroDebt)
.add(user.unpaidKoro);
uint256 pendingEthWei = user
.amount
.mul(farmInfo.accEthRewardsPerShare)
.div(precisionScaleUp)
.sub(user.ethDebt)
.add(user.unpaidEth);
{
uint256 koromaruBalance = koromaru.balanceOf(address(this));
if (pendinKoroTokens > 0) {
if (pendinKoroTokens > koromaruBalance) {
// not enough koro balance to reward farmer
user.unpaidKoro = pendinKoroTokens.sub(koromaruBalance);
totalKoroRewarded = totalKoroRewarded.add(koromaruBalance);
koroCompounded = koromaruBalance;
} else {
user.unpaidKoro = 0;
totalKoroRewarded = totalKoroRewarded.add(pendinKoroTokens);
koroCompounded = pendinKoroTokens;
}
}
}
{
uint256 ethBalance = getEthBalance();
if (pendingEthWei > ethBalance) {
// not enough Eth balance to reward farmer
user.unpaidEth = pendingEthWei.sub(ethBalance);
totalEthRewarded = totalEthRewarded.add(ethBalance);
IWETH(WETHAddress).deposit{value: ethBalance}();
ethCompounded = ethBalance;
} else {
user.unpaidEth = 0;
totalEthRewarded = totalEthRewarded.add(pendingEthWei);
IWETH(WETHAddress).deposit{value: pendingEthWei}();
ethCompounded = pendingEthWei;
}
}
(uint256 LP, , ) = _zapInMulti(koroCompounded, ethCompounded);
onCompound(msg.sender, LP);
emit Compound(msg.sender, koroCompounded, ethCompounded);
}
/**
* @notice Returns time in seconds to next harvest.
*/
function timeToHarvest(address _user)
public
view
whenNotPaused
returns (uint256)
{
UserInfo storage user = userInfo[_user];
if (
block.timestamp - user.lastRewardHarvestedTime >=
rewardHarvestingInterval
) {
return 0;
}
return
user.lastRewardHarvestedTime.sub(
block.timestamp.sub(rewardHarvestingInterval)
);
}
/**
* @notice Withdraw all staked LP tokens without rewards.
*/
function emergencyWithdraw() external nonReentrant {
UserInfo storage user = userInfo[msg.sender];
koromaruUniV2.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, user.amount);
userInfo[msg.sender] = UserInfo(0, 0, 0, 0, 0, 0);
}
//--------------- End Contract Farmer -------------------
//---------------- Contract Utils ----------------------
/**
* @notice Calculates the total amount of rewards per day in USD
* @dev The returned value is in USD * 1e18 (WETH decimals), actual USD value is calculated by dividing the value by 1e18
*/
function getUSDDailyRewards() public view whenNotPaused returns (uint256) {
uint256 stakedLP = koromaruUniV2.balanceOf(address(this));
uint256 totalLPsupply = koromaruUniV2.totalSupply();
uint256 stakedTVL = stakedLP.mul(getTVLUsingKoro()).div(totalLPsupply);
return APR.mul(stakedTVL).div(_1hundred_Percent);
}
/**
* @notice Calculates the total amount of rewards per second in USD
* @dev The returned value is in USD * 1e18 (WETH decimals), actual USD value is calculated by dividing the value by 1e18
*/
function getUSDRewardsPerSecond() internal view returns (uint256) {
// final return value should be divided by (1e18) (i.e WETH decimals) to get USD value
uint256 dailyRewards = getUSDDailyRewards();
return dailyRewards.div(secsPerDay);
}
/**
* @notice Calculates the total number of koromaru token rewards per second
* @dev The returned value must be divided by the koromaru token decimals to get the actual value
*/
function getNumberOfKoroRewardsPerSecond(uint256 _koroRewardAllocation)
internal
view
returns (uint256)
{
uint256 priceOfUintKoro = getLatestKoroPrice(); // 1e18
uint256 rewardsPerSecond = getUSDRewardsPerSecond(); // 1e18
return
rewardsPerSecond
.mul(_koroRewardAllocation)
.mul(koromaruDecimals)
.div(priceOfUintKoro)
.div(_1hundred_Percent); //to be div by koro decimals (i.e 1**(18-18+korodecimals)
}
/**
* @notice Calculates the total amount of Eth rewards per second
* @dev The returned value must be divided by the 1e18 to get the actual value
*/
function getAmountOfEthRewardsPerSecond(uint256 _ethRewardAllocation)
internal
view
returns (uint256)
{
uint256 priceOfUintEth = getLatestEthPrice(); // 1e8
uint256 rewardsPerSecond = getUSDRewardsPerSecond(); // 1e18
uint256 scaleUpToWei = 1e8;
return
rewardsPerSecond
.mul(_ethRewardAllocation)
.mul(scaleUpToWei)
.div(priceOfUintEth)
.div(_1hundred_Percent); // to be div by 1e18 (i.e 1**(18-8+8)
}
/**
* @notice Returns the rewards rate/second for both koromaru and eth
*/
function getRewardsPerSecond()
public
view
whenNotPaused
returns (uint256 koroRewards, uint256 ethRewards)
{
require(
koroRewardAllocation.add(ethRewardAllocation) == _1hundred_Percent,
"getRewardsPerSecond: Invalid reward allocation ratio"
);
koroRewards = getNumberOfKoroRewardsPerSecond(koroRewardAllocation);
ethRewards = getAmountOfEthRewardsPerSecond(ethRewardAllocation);
}
/**
* @notice Calculates and returns the TVL in USD (actaul TVL, not staked TVL)
* @dev Uses Eth price from price feed to calculate the TVL in USD
*/
function getTVL() public view returns (uint256 tvl) {
// final return value should be divided by (1e18) (i.e WETH decimals) to get USD value
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
address token0 = koroPair.token0();
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
uint256 TVLEth = 2 *
(address(token0) == address(koromaru) ? resv1 : resv0);
uint256 priceOfEth = getLatestEthPrice();
tvl = TVLEth.mul(priceOfEth).div(EthPriceFeedDecimal);
}
/**
* @notice Calculates and returns the TVL in USD (actaul TVL, not staked TVL)
* @dev Uses minimum Eth price in USD for 1 koromaru token to calculate the TVL in USD
*/
function getTVLUsingKoro() public view whenNotPaused returns (uint256 tvl) {
// returned value should be divided by (1e18) (i.e WETH decimals) to get USD value
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
address token0 = koroPair.token0();
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
uint256 TVLKoro = 2 *
(address(token0) == address(koromaru) ? resv0 : resv1);
uint256 priceOfKoro = getLatestKoroPrice();
tvl = TVLKoro.mul(priceOfKoro).div(koromaruDecimals);
}
/**
* @notice Get's the latest Eth price in USD
* @dev Uses ChainLink price feed to get the latest Eth price in USD
*/
function getLatestEthPrice() internal view returns (uint256) {
// final return value should be divided by 1e8 to get USD value
(, int256 price, , , ) = priceFeed.latestRoundData();
return uint256(price);
}
/**
* @notice Get's the latest Unit Koro price in USD
* @dev Uses estimated price per koromaru token in USD
*/
function getLatestKoroPrice() internal view returns (uint256) {
// returned value must be divided by 1e18 (i.e WETH decimals) to get USD value
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
address token0 = koroPair.token0();
bool isKoro = address(token0) == address(koromaru);
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
uint256 oneKoro = 1 * koromaruDecimals;
uint256 optimalWethAmount = uniswapRouter.getAmountOut(
oneKoro,
isKoro ? resv0 : resv1,
isKoro ? resv1 : resv0
); //uniswapRouter.quote(oneKoro, isKoro ? resv1 : resv0, isKoro ? resv0 : resv1);
uint256 priceOfEth = getLatestEthPrice();
return optimalWethAmount.mul(priceOfEth).div(EthPriceFeedDecimal);
}
function onDeposit(address _user, uint256 _amount) internal {
require(!reachedMaxLimit(), "KOROFARM: Farm is full");
UserInfo storage user = userInfo[_user];
updateFarm();
if (user.amount > 0) {
// record as unpaid
user.unpaidKoro = user
.amount
.mul(farmInfo.accKoroRewardsPerShare)
.div(precisionScaleUp)
.sub(user.koroDebt)
.add(user.unpaidKoro);
user.unpaidEth = user
.amount
.mul(farmInfo.accEthRewardsPerShare)
.div(precisionScaleUp)
.sub(user.ethDebt)
.add(user.unpaidEth);
}
user.amount = user.amount.add(_amount);
user.koroDebt = user.amount.mul(farmInfo.accKoroRewardsPerShare).div(
precisionScaleUp
);
user.ethDebt = user.amount.mul(farmInfo.accEthRewardsPerShare).div(
precisionScaleUp
);
if (
(block.timestamp - user.lastRewardHarvestedTime >=
rewardHarvestingInterval) || (rewardHarvestingInterval == 0)
) {
user.lastRewardHarvestedTime = block.timestamp;
}
emit Deposit(_user, _amount);
}
function onWithdraw(address _user) internal {
harvestRewards(_user);
userInfo[msg.sender].amount = 0;
userInfo[msg.sender].koroDebt = 0;
userInfo[msg.sender].ethDebt = 0;
}
function onCompound(address _user, uint256 _amount) internal {
require(!reachedMaxLimit(), "KOROFARM: Farm is full");
UserInfo storage user = userInfo[_user];
user.amount = user.amount.add(_amount);
user.koroDebt = user.amount.mul(farmInfo.accKoroRewardsPerShare).div(
precisionScaleUp
);
user.ethDebt = user.amount.mul(farmInfo.accEthRewardsPerShare).div(
precisionScaleUp
);
user.lastRewardHarvestedTime = block.timestamp;
}
function harvestRewards(address _user) internal {
UserInfo storage user = userInfo[_user];
require(
block.timestamp - user.lastRewardHarvestedTime >=
rewardHarvestingInterval,
"HarvestRewards: Not yet ripe"
);
uint256 pendinKoroTokens = user
.amount
.mul(farmInfo.accKoroRewardsPerShare)
.div(precisionScaleUp)
.sub(user.koroDebt)
.add(user.unpaidKoro);
uint256 pendingEthWei = user
.amount
.mul(farmInfo.accEthRewardsPerShare)
.div(precisionScaleUp)
.sub(user.ethDebt)
.add(user.unpaidEth);
{
uint256 koromaruBalance = koromaru.balanceOf(address(this));
if (pendinKoroTokens > 0) {
if (pendinKoroTokens > koromaruBalance) {
// not enough koro balance to reward farmer
koromaru.safeTransfer(_user, koromaruBalance);
user.unpaidKoro = pendinKoroTokens.sub(koromaruBalance);
totalKoroRewarded = totalKoroRewarded.add(koromaruBalance);
emit KoroRewardsHarvested(_user, koromaruBalance);
} else {
koromaru.safeTransfer(_user, pendinKoroTokens);
user.unpaidKoro = 0;
totalKoroRewarded = totalKoroRewarded.add(pendinKoroTokens);
emit KoroRewardsHarvested(_user, pendinKoroTokens);
}
}
}
{
uint256 ethBalance = getEthBalance();
if (pendingEthWei > ethBalance) {
// not enough Eth balance to reward farmer
(bool sent, ) = _user.call{value: ethBalance}("");
require(sent, "Failed to send Ether");
user.unpaidEth = pendingEthWei.sub(ethBalance);
totalEthRewarded = totalEthRewarded.add(ethBalance);
emit EthRewardsHarvested(_user, ethBalance);
} else {
(bool sent, ) = _user.call{value: pendingEthWei}("");
require(sent, "Failed to send Ether");
user.unpaidEth = 0;
totalEthRewarded = totalEthRewarded.add(pendingEthWei);
emit EthRewardsHarvested(_user, pendingEthWei);
}
}
user.koroDebt = user.amount.mul(farmInfo.accKoroRewardsPerShare).div(
precisionScaleUp
);
user.ethDebt = user.amount.mul(farmInfo.accEthRewardsPerShare).div(
precisionScaleUp
);
user.lastRewardHarvestedTime = block.timestamp;
}
/**
* @notice Convert's Koro LP tokens back to Koro and Eth
*/
function zapLPOut(uint256 _amount)
private
returns (uint256 _koroTokens, uint256 _ether)
{
(_koroTokens, _ether) = zapOut(_amount);
(bool sent, ) = msg.sender.call{value: _ether}("");
require(sent, "Failed to send Ether");
koromaru.safeTransfer(msg.sender, _koroTokens);
}
function getEthBalance() public view returns (uint256) {
return address(this).balance;
}
function getUserInfo(address _user)
public
view
returns (
uint256 amount,
uint256 stakedInUsd,
uint256 timeToHarves,
uint256 pendingKoro,
uint256 pendingEth
)
{
amount = userInfo[_user].amount;
timeToHarves = timeToHarvest(_user);
(pendingKoro, pendingEth) = getPendingRewards(_user);
uint256 stakedLP = koromaruUniV2.balanceOf(address(this));
stakedInUsd = stakedLP > 0
? userInfo[_user].amount.mul(getStakedTVL()).div(stakedLP)
: 0;
}
function getFarmInfo()
public
view
returns (
uint256 tvl,
uint256 totalStaked,
uint256 circSupply,
uint256 dailyROI,
uint256 ethDistribution,
uint256 koroDistribution
)
{
tvl = getStakedTVL();
totalStaked = koromaruUniV2.balanceOf(address(this));
circSupply = getCirculatingSupplyLocked();
dailyROI = APR;
ethDistribution = ethRewardAllocation;
koroDistribution = koroRewardAllocation;
}
function getCirculatingSupplyLocked() public view returns (uint256) {
address deadWallet = address(
0x000000000000000000000000000000000000dEaD
);
IUniswapV2Pair koroPair = IUniswapV2Pair(address(koromaruUniV2));
address token0 = koroPair.token0();
(uint256 resv0, uint256 resv1, ) = koroPair.getReserves();
uint256 koroResv = address(token0) == address(koromaru) ? resv0 : resv1;
uint256 lpSupply = koromaruUniV2.totalSupply();
uint256 koroCirculatingSupply = koromaru.totalSupply().sub(
koromaru.balanceOf(deadWallet)
);
uint256 stakedLp = koromaruUniV2.balanceOf(address(this));
return
(stakedLp.mul(koroResv).mul(1e18).div(lpSupply)).div(
koroCirculatingSupply
); // divide by 1e18
}
function approveRouterIfNotApproved() private {
if (koromaru.allowance(address(this), address(uniswapRouter)) == 0) {
koromaru.safeApprove(address(uniswapRouter), type(uint256).max);
}
if (
koromaruUniV2.allowance(address(this), address(uniswapRouter)) == 0
) {
koromaruUniV2.approve(address(uniswapRouter), type(uint256).max);
}
}
function reachedMaxLimit() public view returns (bool) {
uint256 lockedLP = koromaruUniV2.balanceOf(address(this));
if (maxLPLimit < 1) return false; // unlimited
if (lockedLP >= maxLPLimit) return true;
return false;
}
//--------------- End Contract Utils -------------------
receive() external payable {
emit IncreaseEthRewardPool(msg.value);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/structs/EnumerableSet.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function _values(Set storage set) private view returns (bytes32[] memory) {
return set._values;
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(Bytes32Set storage set) internal view returns (bytes32[] memory) {
return _values(set._inner);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(AddressSet storage set) internal view returns (address[] memory) {
bytes32[] memory store = _values(set._inner);
address[] memory result;
assembly {
result := store
}
return result;
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
/**
* @dev Return the entire set in an array
*
* WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed
* to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that
* this function has an unbounded cost, and using it as part of a state-changing function may render the function
* uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block.
*/
function values(UintSet storage set) internal view returns (uint256[] memory) {
bytes32[] memory store = _values(set._inner);
uint256[] memory result;
assembly {
result := store
}
return result;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.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 `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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.0 (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.0 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.0 (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;
}
}
|
Deposit Koromaru tokens into farm Deposited Koromaru will zap into Koro/WETH LP tokens, a refund of TX fee % will be issued/ do tax refund
|
function depositKoroTokensOnly(uint256 _amount)
external
whenNotPaused
nonReentrant
{
require(_amount > 0, "KOROFARM: Invalid Koro Amount");
require(
_amount <= zapKoroLimit,
"KOROFARM: Can't deposit more than Zap Limit"
);
(uint256 lpZappedIn, , ) = ZapIn(_amount, false);
userInfo[msg.sender].unpaidKoro += _amount.mul(taxRefundPercentage).div(
_1hundred_Percent
);
onDeposit(msg.sender, lpZappedIn);
}
| 12,599,158
|
pragma solidity ^0.5.0;
//Functions for retrieving min and Max in 51 length array (requestQ)
//Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol
library Utilities {
/**
* @dev Returns the minimum value in an array.
*/
function getMax(uint256[51] memory data) internal pure returns (uint256 max, uint256 maxIndex) {
max = data[1];
maxIndex;
for (uint256 i = 1; i < data.length; i++) {
if (data[i] > max) {
max = data[i];
maxIndex = i;
}
}
}
/**
* @dev Returns the minimum value in an array.
*/
function getMin(uint256[51] memory data) internal pure returns (uint256 min, uint256 minIndex) {
minIndex = data.length - 1;
min = data[minIndex];
for (uint256 i = data.length - 1; i > 0; i--) {
if (data[i] < min) {
min = data[i];
minIndex = i;
}
}
}
}
/**
* @title Tellor Getters Library
* @dev This is the getter library for all variables in the Tellor Tributes system. TellorGetters references this
* libary for the getters logic
*/
library TellorGettersLibrary {
using SafeMath for uint256;
/*Functions*/
/*Tellor Getters*/
/**
* @dev This function gets the 5 miners currently selected for providing data
* @return miners an array of the miner addresses
*/
function getCurrentMiners(TellorStorage.TellorStorageStruct storage self) internal view returns(address[] memory miners){
return self.selectedValidators;
}
/**
* @dev This function tells you if a given challenge has been completed by a given miner
* @param _challenge the challenge to search for
* @param _miner address that you want to know if they solved the challenge
* @return true if the _miner address provided solved the
*/
function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge, address _miner)
internal
view
returns (bool)
{
return self.minersByChallenge[_challenge][_miner];
}
/**
* @dev Checks if an address voted in a dispute
* @param _disputeId to look up
* @param _address of voting party to look up
* @return bool of whether or not party voted
*/
function didVote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, address _address)
internal
view
returns (bool)
{
return self.disputesById[_disputeId].voted[_address];
}
/**
* @dev allows Tellor to read data from the addressVars mapping
* @param _data is the keccak256("variable_name") of the variable that is being accessed.
* These are examples of how the variables are saved within other functions:
* addressVars[keccak256("_owner")]
* addressVars[keccak256("tellorContract")]
*/
function getAddressVars(TellorStorage.TellorStorageStruct storage self, bytes32 _data)
internal
view
returns (address)
{
return self.addressVars[_data];
}
/**
* @dev Gets all dispute variables
* @param _disputeId to look up
* @return bytes32 hash of dispute
* @return bool executed where true if it has been voted on
* @return bool disputeVotePassed
* @return address of reportedMiner
* @return address of reportingParty
* @return address of proposedForkAddress
* @return uint of requestId
* @return uint of timestamp
* @return uint of value
* @return uint of minExecutionDate
* @return uint of numberOfVotes
* @return uint of blocknumber
* @return uint of minerSlot
* @return uint of quorum
* @return uint of fee
* @return int count of the current tally
*/
function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId)
internal
view
returns (bytes32, bool, bool, address, address, uint256[9] memory, int256)
{
TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
return (
disp.hash,
disp.executed,
disp.disputeVotePassed,
disp.reportedMiner,
disp.reportingParty,
[
disp.disputeUintVars[keccak256("requestId")],
disp.disputeUintVars[keccak256("timestamp")],
disp.disputeUintVars[keccak256("value")],
disp.disputeUintVars[keccak256("minExecutionDate")],
disp.disputeUintVars[keccak256("numberOfVotes")],
disp.disputeUintVars[keccak256("blockNumber")],
disp.disputeUintVars[keccak256("minerSlot")],
disp.disputeUintVars[keccak256("quorum")],
disp.disputeUintVars[keccak256("fee")]
],
disp.tally
);
}
/**
* @dev Getter function for variables for the requestId being currently mined(currentRequestId)
* @return current challenge, currentRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request
*/
function getCurrentVariables(TellorStorage.TellorStorageStruct storage self)
internal
view
returns (bytes32, uint256, uint256)
{
return (
self.currentChallenge,
self.uintVars[keccak256("currentRequestId")],
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")]
);
}
/**
* @dev Checks if a given hash of miner,requestId has been disputed
* @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId));
* @return uint disputeId
*/
function getDisputeIdsByDisputeHash(TellorStorage.TellorStorageStruct storage self, bytes32 _hash)
internal
view
returns (uint256[] memory)
{
return self.disputeIdsByDisputeHash[_hash];
}
/**
* @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId
* @param _disputeId is the dispute id;
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the disputeUintVars under the Dispute struct
* @return uint value for the bytes32 data submitted
*/
function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bytes32 _data)
internal
view
returns (uint256)
{
return self.disputesById[_disputeId].disputeUintVars[_data];
}
/**
* @dev Gets the a value for the latest timestamp available
* @return value for timestamp of last proof of work submited
* @return true if the is a timestamp for the lastNewValue
*/
function getLastNewValue(TellorStorage.TellorStorageStruct storage self)
internal
view
returns (uint256, bool)
{
return (
retrieveData(
self,
self.requestIdByTimestamp[self.uintVars[keccak256("timeOfLastNewValue")]],
self.uintVars[keccak256("timeOfLastNewValue")]
),
true
);
}
/**
* @dev Gets the a value for the latest timestamp available
* @param _requestId being requested
* @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't
*/
function getLastNewValueById(TellorStorage.TellorStorageStruct storage self, uint256 _requestId)
internal
view
returns (uint256, bool) {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
if (_request.requestTimestamps.length > 0) {
return (retrieveData(self, _requestId, _request.requestTimestamps[_request.requestTimestamps.length - 1]), true);
} else {
return (0, false);
}
}
/**
* @dev Gets blocknumber for mined timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up blocknumber
* @return uint of the blocknumber which the dispute was mined
*/
function getMinedBlockNum(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (uint256)
{
return self.requestDetails[_requestId].minedBlockNum[_timestamp];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return the 5 miners' addresses
*/
function getMinersByRequestIdAndTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (address[5] memory)
{
return self.requestDetails[_requestId].minersByValue[_timestamp];
}
/**
* @dev Counts the number of values that have been submited for the request
* if called for the currentRequest being mined it can tell you how many miners have submitted a value for that
* request so far
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, uint256 _requestId)
internal
view
returns (uint256)
{
return self.requestDetails[_requestId].requestTimestamps.length;
}
/**
* @dev Getter function for the specified requestQ index
* @param _index to look up in the requestQ array
* @return uint of reqeuestId
*/
function getRequestIdByRequestQIndex(TellorStorage.TellorStorageStruct storage self, uint256 _index)
internal
view
returns (uint256)
{
require(_index <= 50, "RequestQ index is above 50");
return self.requestIdByRequestQIndex[_index];
}
/**
* @dev Getter function for requestId based on timestamp
* @param _timestamp to check requestId
* @return uint of reqeuestId
*/
function getRequestIdByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _timestamp)
internal
view
returns (uint256)
{
return self.requestIdByTimestamp[_timestamp];
}
/**
* @dev Getter function for the requestQ array
* @return the requestQ arrray
*/
function getRequestQ(TellorStorage.TellorStorageStruct storage self)
internal
view
returns (uint256[51] memory)
{
return self.requestQ;
}
/**
* @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct
* for the requestId specified
* @param _requestId to look up
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the apiUintVars under the requestDetails struct
* @return uint value of the apiUintVars specified in _data for the requestId specified
*/
function getRequestUintVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, bytes32 _data)
internal
view
returns (uint256)
{
return self.requestDetails[_requestId].apiUintVars[_data];
}
/**
* @dev Gets the API struct variables that are not mappings
* @param _requestId to look up
* @return uint of index in requestQ array
* @return uint of current payout/tip for this requestId
*/
function getRequestVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId)
internal
view
returns (uint256, uint256)
{
TellorStorage.Request storage _request = self.requestDetails[_requestId];
return (
_request.apiUintVars[keccak256("requestQPosition")],
_request.apiUintVars[keccak256("totalTip")]
);
}
/**
* @dev This function allows users to retireve all information about a staker
* @param _staker address of staker inquiring about
* @return uint current state of staker
* @return uint startDate of staking
* @return uint stakePosition for the staker
*/
function getStakerInfo(TellorStorage.TellorStorageStruct storage self, address _staker)
internal
view
returns (uint256, uint256,uint256)
{
return (self.stakerDetails[_staker].currentStatus, self.stakerDetails[_staker].startDate, self.stakerDetails[_staker].stakePosition.length);
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestampt to look up miners for
* @return address[5] array of 5 addresses ofminers that mined the requestId
*/
function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (uint256[5] memory)
{
return self.requestDetails[_requestId].valuesByTimestamp[_timestamp];
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestID is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self, uint256 _requestID, uint256 _index)
internal
view
returns (uint256)
{
return self.requestDetails[_requestID].requestTimestamps[_index];
}
/**
* @dev Getter for the variables saved under the TellorStorageStruct uintVars variable
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the uintVars under the TellorStorageStruct struct
* This is an example of how data is saved into the mapping within other functions:
* self.uintVars[keccak256("stakerCount")]
* @return uint of specified variable
*/
function getUintVar(TellorStorage.TellorStorageStruct storage self, bytes32 _data)
internal
view
returns (uint256)
{
return self.uintVars[_data];
}
/**
* @dev Getter function for next requestId on queue/request with highest payout at time the function is called
* @return onDeck/info on request with highest payout-- RequestId, Totaltips
*/
function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self)
internal
view
returns (uint256, uint256)
{
uint256 newRequestId = getTopRequestID(self);
return (
newRequestId,
self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")]
);
}
/**
* @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function
* @return uint _requestId of request with highest payout at the time the function is called
*/
function getTopRequestID(TellorStorage.TellorStorageStruct storage self)
internal
view
returns (uint256 _requestId)
{
uint256 _max;
uint256 _index;
(_max, _index) = Utilities.getMax(self.requestQ);
_requestId = self.requestIdByRequestQIndex[_index];
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (bool)
{
return self.requestDetails[_requestId].inDispute[_timestamp];
}
/**
* @dev Retreive value from oracle based on requestId/timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return uint value for requestId/timestamp submitted
*/
function retrieveData(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (uint256)
{
return self.requestDetails[_requestId].finalValues[_timestamp];
}
}
/**
* @title Tellor Oracle System Library
* @dev Contains the functions' logic for the Tellor contract where miners can submit the proof of work
* along with the value and smart contracts can requestData and tip miners.
*/
library TellorLibrary {
using SafeMath for uint256;
//emits when a tip is added to a requestId
event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips);
//emits when a new challenge is created (either on mined block or when a new request is pushed forward on waiting system)
event NewChallenge(
bytes32 indexed _currentChallenge,
uint256 indexed _currentRequestId,
uint256 _totalTips
);
//emits when a the payout of another request is higher after adding to the payoutPool or submitting a request
event NewRequestOnDeck(uint256 indexed _requestId, uint256 _onDeckTotalTips);
//Emits upon a successful Mine, indicates the blocktime at point of the mine and the value mined
event NewValue(uint256 indexed _requestId, uint256 _time, uint256 _value, uint256 _totalTips, bytes32 _currentChallenge);
//Emits upon each mine (5 total) and shows the miner, and value submitted
event SolutionSubmitted(address indexed _miner, uint256 indexed _requestId, uint256 _value, bytes32 _currentChallenge);
//emits when a new validator is selected
event NewValidatorsSelected(address _validator);
/*Functions*/
/**
* @dev Add tip to Request value from oracle
* @param _requestId being requested to be mined
* @param _tip amount the requester is willing to pay to be get on queue. Miners
* mine the onDeckQueryHash, or the api with the highest payout pool
*/
function addTip(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) public {
require(_requestId > 0, "RequestId is 0");
TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]);
require(tellorToken.allowance(msg.sender,address(this)) >= _tip,"Allowance must be set");
//If the tip > 0 transfer the tip to this contract
require (_tip >= 5, "Tip must be greater than 5");//must be greater than 5 loyas so each miner gets at least 1 loya
tellorToken.transferFrom(msg.sender, address(this), _tip);
//Update the information for the request that should be mined next based on the tip submitted
updateOnDeck(self, _requestId, _tip);
emit TipAdded(msg.sender, _requestId, _tip, self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")]);
}
/**
* @dev This function is called by submitMiningSolution and adjusts the difficulty, sorts and stores the first
* 5 values received, pays the miners, the dev share and assigns a new challenge
* @param _requestId for the current request being mined
*/
function newBlock(TellorStorage.TellorStorageStruct storage self, uint256 _requestId) internal {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]);
uint256 _timeOfLastNewValue = now - (now % 1 minutes);
self.uintVars[keccak256("timeOfLastNewValue")] = _timeOfLastNewValue;
//The sorting algorithm that sorts the values of the first five values that come in
TellorStorage.Details[5] memory a = self.currentMiners;
uint256 i;
for (i = 1; i < 5; i++) {
uint256 temp = a[i].value;
address temp2 = a[i].miner;
uint256 j = i;
while (j > 0 && temp < a[j - 1].value) {
a[j].value = a[j - 1].value;
a[j].miner = a[j - 1].miner;
j--;
}
if (j < i) {
a[j].value = temp;
a[j].miner = temp2;
}
}
//Pay the miners
for (i = 0; i < 5; i++) {
tellorToken.transfer(a[i].miner, self.uintVars[keccak256("currentTotalTips")] / 5);
}
emit NewValue(
_requestId,
_timeOfLastNewValue,
a[2].value,
self.uintVars[keccak256("currentTotalTips")] - (self.uintVars[keccak256("currentTotalTips")] % 5),
self.currentChallenge
);
//Save the official(finalValue), timestamp of it, 5 miners and their submitted values for it, and its block number
_request.finalValues[_timeOfLastNewValue] = a[2].value;
_request.requestTimestamps.push(_timeOfLastNewValue);
//these are miners by timestamp
_request.minersByValue[_timeOfLastNewValue] = [a[0].miner, a[1].miner, a[2].miner, a[3].miner, a[4].miner];
_request.valuesByTimestamp[_timeOfLastNewValue] = [a[0].value, a[1].value, a[2].value, a[3].value, a[4].value];
_request.minedBlockNum[_timeOfLastNewValue] = block.number;
//map the timeOfLastValue to the requestId that was just mined
self.requestIdByTimestamp[_timeOfLastNewValue] = _requestId;
//add timeOfLastValue to the newValueTimestamps array
self.newValueTimestamps.push(_timeOfLastNewValue);
//re-start the count for the slot progress to zero before the new request mining starts
self.uintVars[keccak256("slotProgress")] = 0;
uint256 _topId = TellorGettersLibrary.getTopRequestID(self);
self.uintVars[keccak256("currentRequestId")] = _topId;
//if the currentRequestId is not zero(currentRequestId exists/something is being mined) select the requestId with the hightest payout
//else wait for a new tip to mine
if (_topId > 0) {
selectNewValidators(self,true);
self.currentChallenge = keccak256(abi.encodePacked(randomnumber(self,_timeOfLastNewValue,a[2].value), self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof
//Update the current request to be mined to the requestID with the highest payout
self.uintVars[keccak256("currentTotalTips")] = self.requestDetails[_topId].apiUintVars[keccak256("totalTip")];
//Remove the currentRequestId/onDeckRequestId from the requestQ array containing the rest of the 50 requests
self.requestQ[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0;
//unmap the currentRequestId/onDeckRequestId from the requestIdByRequestQIndex
self.requestIdByRequestQIndex[self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")]] = 0;
//Remove the requestQposition for the currentRequestId/onDeckRequestId since it will be mined next
self.requestDetails[_topId].apiUintVars[keccak256("requestQPosition")] = 0;
//Reset the requestId TotalTip to 0 for the currentRequestId/onDeckRequestId since it will be mined next
//and the tip is going to the current timestamp miners. The tip for the API needs to be reset to zero
self.requestDetails[_topId].apiUintVars[keccak256("totalTip")] = 0;
//gets the max tip in the in the requestQ[51] array and its index within the array??
uint256 newRequestId = TellorGettersLibrary.getTopRequestID(self);
//Issue the the next requestID
emit NewChallenge(
self.currentChallenge,
_topId,
self.uintVars[keccak256("currentTotalTips")]
);
emit NewRequestOnDeck(
newRequestId,
self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")]
);
} else {
self.uintVars[keccak256("currentTotalTips")] = 0;
self.currentChallenge = "";
self.selectedValidators.length = 0;
}
}
/**
* @dev Proof of work is called by the miner when they submit the solution (proof of work and value)
* @param _requestId the apiId being mined
* @param _value of api query
*/
function submitMiningSolution(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _value)
public
{
//requre miner is staked
require(self.stakerDetails[msg.sender].currentStatus == 1, "Miner status is not staker");
//Check the miner is submitting the pow for the current request Id
require(_requestId == self.uintVars[keccak256("currentRequestId")], "RequestId is wrong");
//Check the validator submitting data is one of the selected validators
require(self.validValidator[msg.sender] == true, "Not a selected validator");
//Make sure the miner does not submit a value more than once
require(self.minersByChallenge[self.currentChallenge][msg.sender] == false, "Miner already submitted the value");
//Save the miner and value received
self.currentMiners[self.uintVars[keccak256("slotProgress")]].value = _value;
self.currentMiners[self.uintVars[keccak256("slotProgress")]].miner = msg.sender;
//Add to the count how many values have been submitted, since only 5 are taken per request
self.uintVars[keccak256("slotProgress")]++;
//Update the miner status to true once they submit a value so they don't submit more than once
self.minersByChallenge[self.currentChallenge][msg.sender] = true;
emit SolutionSubmitted(msg.sender, _requestId, _value, self.currentChallenge);
//If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received
//Once a validator submits data set their status back to false
self.validValidator[msg.sender] = false;
if (self.uintVars[keccak256("slotProgress")] == 5) {
newBlock(self, _requestId);
}
}
/**
* @dev This function updates APIonQ and the requestQ when requestData or addTip are ran
* @param _requestId being requested
* @param _tip is the tip to add
*/
function updateOnDeck(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _tip) internal {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
uint256 onDeckRequestId = TellorGettersLibrary.getTopRequestID(self);
_request.apiUintVars[keccak256("totalTip")] = _request.apiUintVars[keccak256("totalTip")].add(_tip);
//Set _payout for the submitted request
uint256 _payout = _request.apiUintVars[keccak256("totalTip")];
//If there is no current request being mined
//then set the currentRequestId to the requestid of the requestData or addtip requestId submitted,
// the totalTips to the payout/tip submitted, and issue a new mining challenge
if (self.uintVars[keccak256("currentRequestId")] == 0) {
self.uintVars[keccak256("currentRequestId")] = _requestId;
self.uintVars[keccak256("currentTotalTips")] = _payout;
self.currentChallenge = keccak256(abi.encodePacked(_payout, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof
selectNewValidators(self,true);
emit NewChallenge(
self.currentChallenge,
self.uintVars[keccak256("currentRequestId")],
self.uintVars[keccak256("currentTotalTips")]
);
} else if (_requestId == self.uintVars[keccak256("currentRequestId")]) {
self.uintVars[keccak256("currentTotalTips")] = self.uintVars[keccak256("currentTotalTips")] + _payout;
}else {
//If there is no OnDeckRequestId
//then replace/add the requestId to be the OnDeckRequestId, queryHash and OnDeckTotalTips(current highest payout, aside from what
//is being currently mined)
if (_payout > self.requestDetails[onDeckRequestId].apiUintVars[keccak256("totalTip")]) {
//let everyone know the next on queue has been replaced
emit NewRequestOnDeck(_requestId, _payout);
}
//if the request is not part of the requestQ[51] array
//then add to the requestQ[51] only if the _payout/tip is greater than the minimum(tip) in the requestQ[51] array
if (_request.apiUintVars[keccak256("requestQPosition")] == 0) {
uint256 _min;
uint256 _index;
(_min, _index) = Utilities.getMin(self.requestQ);
//we have to zero out the oldOne
//if the _payout is greater than the current minimum payout in the requestQ[51] or if the minimum is zero
//then add it to the requestQ array aand map its index information to the requestId and the apiUintvars
if (_payout > _min) {
self.requestQ[_index] = _payout;
self.requestDetails[self.requestIdByRequestQIndex[_index]].apiUintVars[keccak256("requestQPosition")] = 0;
self.requestIdByRequestQIndex[_index] = _requestId;
_request.apiUintVars[keccak256("requestQPosition")] = _index;
}
// else if the requestid is part of the requestQ[51] then update the tip for it
} else{
self.requestQ[_request.apiUintVars[keccak256("requestQPosition")]] = _payout;
}
}
}
/**
* @dev Reselects validators if any of the first five fail to submit data
*/
function reselectNewValidators(TellorStorage.TellorStorageStruct storage self) public{
require( self.uintVars[keccak256("lastSelection")] < now - 30, "has not been long enough reselect");
selectNewValidators(self,false);// ??? Does false mean to select new validators?
}
/**
* @dev Generates a random number to select validators
*/
function randomnumber(TellorStorage.TellorStorageStruct storage self, uint _max, uint _nonce) internal view returns (uint){
return uint(keccak256(abi.encodePacked(_nonce,now,self.uintVars[keccak256("totalTip")],msg.sender,block.difficulty,self.stakers.length))) % _max;
}
/**
* @dev Selects validators
* @param _reset true to delete existing validators and re-selected
*/
function selectNewValidators(TellorStorage.TellorStorageStruct storage self, bool _reset) public{
if(_reset){
self.selectedValidators.length = 0;
}
uint j=0;
uint i=0;
uint r;
address potentialValidator;
while(j < 5 && self.stakers.length > self.selectedValidators.length){
i++;
r = randomnumber(self,self.stakers.length,i);
potentialValidator = self.stakers[r];
if(!self.validValidator[potentialValidator]){
self.selectedValidators.push(potentialValidator);
emit NewValidatorsSelected(potentialValidator);
self.validValidator[potentialValidator] = true;//used to check if they are a selectedvalidator (better than looping through array)
j++;
}
}
self.uintVars[keccak256("lastSelected")] = now;
}
}
//Slightly modified SafeMath library - includes a min and max function, removes useless div function
library SafeMath {
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
function add(int256 a, int256 b) internal pure returns (int256 c) {
if (b > 0) {
c = a + b;
assert(c >= a);
} else {
c = a + b;
assert(c <= a);
}
}
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a > b ? a : b;
}
function max(int256 a, int256 b) internal pure returns (uint256) {
return a > b ? uint256(a) : uint256(b);
}
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function sub(int256 a, int256 b) internal pure returns (int256 c) {
if (b > 0) {
c = a - b;
assert(c <= a);
} else {
c = a - b;
assert(c >= a);
}
}
}
/**
* @title Tellor Oracle Storage Library
* @dev Contains all the variables/structs used by Tellor
*/
library TellorStorage {
//Internal struct for use in proof-of-work submission
struct Details {
uint256 value;
address miner;
}
struct Dispute {
bytes32 hash; //unique hash of dispute: keccak256(_miner,_requestId,_timestamp)
int256 tally; //current tally of votes for - against measure
bool executed; //is the dispute settled
bool disputeVotePassed; //did the vote pass?
address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails
address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes
mapping(bytes32 => uint256) disputeUintVars;
//Each of the variables below is saved in the mapping disputeUintVars for each disputeID
//e.g. TellorStorageStruct.DisputeById[disputeID].disputeUintVars[keccak256("requestId")]
//These are the variables saved in this mapping:
// uint keccak256("requestId");//apiID of disputed value
// uint keccak256("timestamp");//timestamp of distputed value
// uint keccak256("value"); //the value being disputed
// uint keccak256("minExecutionDate");//7 days from when dispute initialized
// uint keccak256("numberOfVotes");//the number of parties who have voted on the measure
// uint keccak256("blockNumber");// the blocknumber for which votes will be calculated from
// uint keccak256("minerSlot"); //index in dispute array
// uint keccak256("quorum"); //quorum for dispute vote NEW
// uint keccak256("fee"); //fee paid corresponding to dispute
mapping(address => bool) voted; //mapping of address to whether or not they voted
}
struct StakeInfo {
uint256 currentStatus; //0-not Staked, 1=Staked, 2=LockedForWithdraw 3= OnDispute
uint256 startDate; //stake start date
uint256 withdrawDate;
uint256 withdrawAmount;
uint[] stakePosition;
mapping(uint => uint) stakePositionArrayIndex;
}
//Internal struct to allow balances to be queried by blocknumber for voting purposes
struct Checkpoint {
uint128 fromBlock; // fromBlock is the block number that the value was generated from
uint128 value; // value is the amount of tokens at a specific block number
}
struct Request {
uint256[] requestTimestamps; //array of all newValueTimestamps requested
mapping(bytes32 => uint256) apiUintVars;
//Each of the variables below is saved in the mapping apiUintVars for each api request
//e.g. requestDetails[_requestId].apiUintVars[keccak256("totalTip")]
//These are the variables saved in this mapping:
// uint keccak256("requestQPosition"); //index in requestQ
// uint keccak256("totalTip");//bonus portion of payout
mapping(uint256 => uint256) minedBlockNum; //[apiId][minedTimestamp]=>block.number
//This the time series of finalValues stored by the contract where uint UNIX timestamp is mapped to value
mapping(uint256 => uint256) finalValues;
mapping(uint256 => bool) inDispute; //checks if API id is in dispute or finalized.
mapping(uint256 => address[5]) minersByValue;
mapping(uint256 => uint256[5]) valuesByTimestamp;
}
struct TellorStorageStruct {
address[] selectedValidators;
address[] stakers;
mapping(address => uint) missedCalls;//if your missed calls gets up to 3, you lose a TRB. A successful retrieval resets its
mapping(address => bool) validValidator; //ensures only selected validators can sumbmit data
bytes32 currentChallenge; //current challenge to be solved
uint256[51] requestQ; //uint50 array of the top50 requests by payment amount
uint256[] newValueTimestamps; //array of all timestamps requested
Details[5] currentMiners; //This struct is for organizing the five mined values to find the median
mapping(bytes32 => address) addressVars;
//Address fields in the Tellor contract are saved the addressVars mapping
//e.g. addressVars[keccak256("tellorContract")] = address
//These are the variables saved in this mapping:
// address keccak256("tellorContract");//Tellor address
// address keccak256("_deity");//Tellor Owner that can do things at will
mapping(bytes32 => uint256) uintVars;
//uint fields in the Tellor contract are saved the uintVars mapping
//e.g. uintVars[keccak256("decimals")] = uint
//These are the variables saved in this mapping:
// keccak256("decimals"); //18 decimal standard ERC20
// keccak256("disputeFee");//cost to dispute a mined value
// keccak256("disputeCount");//totalHistoricalDisputes
// keccak256("total_supply"); //total_supply of the token in circulation
// keccak256("stakeAmount");//stakeAmount for miners (we can cut gas if we just hardcode it in...or should it be variable?)
// keccak256("stakerCount"); //number of parties currently staked
// keccak256("timeOfLastNewValue"); // time of last challenge solved
// keccak256("difficulty"); // Difficulty of current block
// keccak256("currentTotalTips"); //value of highest api/timestamp PayoutPool
// keccak256("currentRequestId"); //API being mined--updates with the ApiOnQ Id
// keccak256("requestCount"); // total number of requests through the system
// keccak256("slotProgress");//Number of miners who have mined this value so far
// keccak256("miningReward");//Mining Reward in PoWo tokens given to all miners per value
// keccak256("timeTarget"); //The time between blocks (mined Oracle values)
//keccak256("minimumPayment") //The minimum payment in TRB for a data request
// keccak256("uniqueStakers")//Number of unique stakers
// keccak256("lastSelected") //Time we last selected validators
//This is a boolean that tells you if a given challenge has been completed by a given miner
mapping(bytes32 => mapping(address => bool)) minersByChallenge;
mapping(uint256 => uint256) requestIdByTimestamp; //minedTimestamp to apiId
mapping(uint256 => uint256) requestIdByRequestQIndex; //link from payoutPoolIndex (position in payout pool array) to apiId
mapping(uint256 => Dispute) disputesById; //disputeId=> Dispute details
mapping(address => Checkpoint[]) balances; //balances of a party given blocks
mapping(address => mapping(address => uint256)) allowed; //allowance for a given party and approver
mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info
mapping(uint256 => Request) requestDetails; //mapping of apiID to details
mapping(bytes32 => uint256[]) disputeIdsByDisputeHash; //maps a hash to an ID for each dispute
}
}
/**
* @title Tellor Transfer
* @dev Contais the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol
* reference this library for function's logic.
*/
library TellorTransfer {
using SafeMath for uint256;
/*Functions*/
/**
* @dev Gets balance of owner specified
* @param _user is the owner address used to look up the balance
* @return Returns the balance associated with the passed in _user
*/
function balanceOf(TellorStorage.TellorStorageStruct storage self, address _user) public view returns (uint256) {
return balanceOfAt(self, _user, block.number);
}
/**
* @dev Completes POWO transfers by updating the balances on the current block number
* @param _from address to transfer from
* @param _to addres to transfer to
* @param _amount to transfer
*/
function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) internal {
require(_amount > 0, "Tried to send non-positive amount");
uint256 previousBalance;
if(_from != address(this)){
require(balanceOf(self, _from).sub(_amount) >= 0, "Stake amount was not removed from balance");
previousBalance = balanceOfAt(self, _from, block.number);
updateBalanceAtNow(self.balances[_from], previousBalance - _amount);
}
previousBalance = balanceOfAt(self, _to, block.number);
require(previousBalance + _amount >= previousBalance, "Overflow happened"); // Check for overflow
updateBalanceAtNow(self.balances[_to], previousBalance + _amount);
}
/**
* @dev Queries the balance of _user at a specific _blockNumber
* @param _user The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at _blockNumber specified
*/
function balanceOfAt(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _blockNumber) public view returns (uint256) {
if ((self.balances[_user].length == 0) || (self.balances[_user][0].fromBlock > _blockNumber)) {
return 0;
} else {
return getBalanceAt(self.balances[_user], _blockNumber);
}
}
/**
* @dev Getter for balance for owner on the specified _block number
* @param checkpoints gets the mapping for the balances[owner]
* @param _block is the block number to search the balance on
* @return the balance at the checkpoint
*/
function getBalanceAt(TellorStorage.Checkpoint[] storage checkpoints, uint256 _block) public view returns (uint256) {
if (checkpoints.length == 0) return 0;
if (_block >= checkpoints[checkpoints.length - 1].fromBlock) return checkpoints[checkpoints.length - 1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint256 min = 0;
uint256 max = checkpoints.length - 1;
while (max > min) {
uint256 mid = (max + min + 1) / 2;
if (checkpoints[mid].fromBlock <= _block) {
min = mid;
} else {
max = mid - 1;
}
}
return checkpoints[min].value;
}
/**
* @dev Updates balance for from and to on the current block number via doTransfer
* @param checkpoints gets the mapping for the balances[owner]
* @param _value is the new balance
*/
function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, uint256 _value) public {
if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) {
TellorStorage.Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
TellorStorage.Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1];
oldCheckPoint.value = uint128(_value);
}
}
}
/**
* itle Tellor Stake
* @dev Contains the methods related to miners staking and unstaking. Tellor.sol
* references this library for function's logic.
*/
library TellorStake {
event NewStake(address indexed _sender); //Emits upon new staker
event StakeWithdrawn(address indexed _sender); //Emits when a staker is now no longer staked
event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period
/*Functions*/
/**
* @dev This function allows stakers to request to withdraw their stake (no longer stake)
* once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they
* can withdraw the deposit
*/
function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self, uint _amount) public {
TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender];
require(stakes.currentStatus == 1, "Miner is not staked");
require(_amount % self.uintVars[keccak256("minimumStake")] == 0, "Must be divisible by minimumStake");
require(_amount <= TellorTransfer.balanceOf(self,msg.sender));
for(uint i=0; i < _amount / self.uintVars[keccak256("minimumStake")]; i++) {
removeFromStakerArray(self, stakes.stakePosition[i],msg.sender);
}
//Change the miner staked to locked to be withdrawStake
if (TellorTransfer.balanceOf(self,msg.sender) - _amount == 0){
stakes.currentStatus = 2;
}
stakes.withdrawDate = now - (now % 86400);
stakes.withdrawAmount = _amount;
emit StakeWithdrawRequested(msg.sender);
}
/**
* @dev This function allows users to withdraw their stake after a 7 day waiting period from request
*/
function withdrawStake(TellorStorage.TellorStorageStruct storage self) public {
TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender];
//Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have
//passed by since they locked for withdraw
require(now - (now % 86400) - stakes.withdrawDate >= 7 days, "7 days didn't pass");
require(stakes.currentStatus !=3 , "Miner is under dispute");
TellorTransfer.doTransfer(self,msg.sender,address(0),stakes.withdrawAmount);
if (TellorTransfer.balanceOf(self,msg.sender) == 0){
stakes.currentStatus =0 ;
self.uintVars[keccak256("stakerCount")] -= 1;
self.uintVars[keccak256("uniqueStakers")] -= 1;
}
self.uintVars[keccak256("totalStaked")] -= stakes.withdrawAmount;
TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]);
tellorToken.transfer(msg.sender,stakes.withdrawAmount);
emit StakeWithdrawn(msg.sender);
}
/**
* @dev This function allows miners to deposit their stake
* @param _amount is the amount to be staked
*/
function depositStake(TellorStorage.TellorStorageStruct storage self, uint _amount) public {
TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]);
require(tellorToken.allowance(msg.sender,address(this)) >= _amount, "Proper amount must be allowed to this contract");
tellorToken.transferFrom(msg.sender, address(this), _amount);
//Ensure they can only stake if they are not currrently staked or if their stake time frame has ended
//and they are currently locked for witdhraw
require(self.stakerDetails[msg.sender].currentStatus == 0 || self.stakerDetails[msg.sender].currentStatus == 1, "Miner is in the wrong state");
//if this is the first time this addres stakes count, then add them to the stake count
if(TellorTransfer.balanceOf(self,msg.sender) == 0){
self.uintVars[keccak256("uniqueStakers")] += 1;
}
require(_amount >= self.uintVars[keccak256("minimumStake")], "You must stake a certain amount");
require(_amount % self.uintVars[keccak256("minimumStake")] == 0, "Must be divisible by minimumStake");
for(uint i=0; i < _amount / self.uintVars[keccak256("minimumStake")]; i++){
self.stakerDetails[msg.sender].stakePosition.push(self.stakers.length);
//self.stakerDetails[msg.sender].stakePositionArrayIndex[self.stakerDetails[msg.sender].stakerPosition.length] = self.stakers.length;
self.stakers.push(msg.sender);
self.uintVars[keccak256("stakerCount")] += 1;
}
self.stakerDetails[msg.sender].currentStatus = 1;
self.stakerDetails[msg.sender].startDate = now - (now % 86400);
TellorTransfer.doTransfer(self,address(this),msg.sender,_amount);
self.uintVars[keccak256("totalStaked")] += _amount;
emit NewStake(msg.sender);
}
/**
* @dev This function is used by requestStakingWithdraw to remove the staker from the stakers array
* @param _pos is the staker's position in the array
* @param _staker is the staker's address
*/
function removeFromStakerArray(TellorStorage.TellorStorageStruct storage self, uint _pos, address _staker) internal{
address lastAdd;
if(_pos == self.stakers.length-1){
self.stakers.length--;
self.stakerDetails[_staker].stakePosition.length--;
}
else{
lastAdd = self.stakers[self.stakers.length-1];
self.stakers[_pos] = lastAdd;
self.stakers.length--;
self.stakerDetails[_staker].stakePosition.length--;
}
}
}
interface TokenInterface {
function totalSupply() external view returns (uint);
function balanceOf(address tokenOwner) external view returns (uint balance);
function balanceOfAt(address tokenOwner, uint256 blockNumber) external view returns (uint balance);
function allowance(address tokenOwner, address spender) external view returns (uint remaining);
function transfer(address to, uint tokens) external returns (bool success);
function approve(address spender, uint tokens) external returns (bool success);
function transferFrom(address from, address to, uint tokens) external returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
/**
* @title Tellor Dispute
* @dev Contains the methods related to disputes. Tellor.sol references this library for function's logic.
*/
library TellorDispute {
using SafeMath for uint256;
using SafeMath for int256;
//emitted when a new dispute is initialized
event NewDispute(uint256 indexed _disputeId, uint256 indexed _requestId, uint256 _timestamp, address _miner);
//emitted when a new vote happens
event Voted(uint256 indexed _disputeID, bool _position, address indexed _voter);
//emitted upon dispute tally
event DisputeVoteTallied(uint256 indexed _disputeID, int256 _result, address indexed _reportedMiner, address _reportingParty, bool _active);
/*Functions*/
/**
* @dev Helps initialize a dispute by assigning it a disputeId
* when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the
* invalidated value information to POS voting
* @param _requestId being disputed
* @param _timestamp being disputed
* @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value
* requires 5 miners to submit a value.
*/
function beginDispute(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) public {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
//require that no more than a day( (24 hours * 60 minutes)/10minutes=144 blocks) has gone by since the value was "mined"
//require(now - _timestamp <= 1 days, "The value was mined more than a day ago");
require(_request.minedBlockNum[_timestamp] > 0, "Mined block is 0");
require(_minerIndex < 5, "Miner index is wrong");
//_miner is the miner being disputed. For every mined value 5 miners are saved in an array and the _minerIndex
//provided by the party initiating the dispute
address _miner = _request.minersByValue[_timestamp][_minerIndex];
bytes32 _hash = keccak256(abi.encodePacked(_miner, _requestId, _timestamp));
if (self.disputeIdsByDisputeHash[_hash].length > 0){
uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1];
require(self.disputesById[_finalId].executed, "previous vote must be over with");
}
//Increase the dispute count by 1
self.uintVars[keccak256("disputeCount")] = self.uintVars[keccak256("disputeCount")] + 1;
//Sets the new disputeCount as the disputeId
uint256 disputeId = self.uintVars[keccak256("disputeCount")];
//maps the dispute hash to the disputeId
uint256 _fee = self.uintVars[keccak256("disputeFee")] * 2**self.disputeIdsByDisputeHash[_hash].length;
self.disputeIdsByDisputeHash[_hash].push(disputeId);
//Ensures that a dispute is not already open for the that miner, requestId and timestamp
require(self.disputesById[self.disputeIdsByDisputeHash[_hash][0]].disputeUintVars[keccak256("minExecutionDate")] < now, "Dispute is already open");
//Transfer dispute fee
TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]);
require(tellorToken.balanceOf(msg.sender) >= _fee, "Balance is too low to cover dispute fee");
require(tellorToken.allowance(msg.sender,address(this)) >= _fee, "Proper amount must be allowed to this contract");
tellorToken.transferFrom(msg.sender, address(this), _fee);
//maps the dispute to the Dispute struct
self.disputesById[disputeId] = TellorStorage.Dispute({
hash: _hash,
reportedMiner: _miner,
reportingParty: msg.sender,
executed: false,
disputeVotePassed: false,
tally: 0
});
//Saves all the dispute variables for the disputeId
self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId;
self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp;
self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex];
self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 2 days * self.disputeIdsByDisputeHash[_hash].length;
self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number;
self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex;
self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = _fee;
//Values are sorted as they come in and the official value is the median of the first five
//So the "official value" miner is always minerIndex==2. If the official value is being
//disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute
if (_minerIndex == 2) {
_request.inDispute[_timestamp] = true;
_request.finalValues[_timestamp] = 0;
}
self.stakerDetails[_miner].currentStatus = 3;
emit NewDispute(disputeId, _requestId, _timestamp, _miner);
}
/**
* @dev Allows token holders to vote
* @param _disputeId is the dispute id
* @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute)
*/
function vote(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId, bool _supportsDispute) public {
TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
//Get the voteWeight or the balance of the user at the time/blockNumber the disupte began
//if they are staked weigh vote based on their staked + unstaked balance of TRB on the side chain
uint256 voteWeight;
TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]);
voteWeight = TellorTransfer.balanceOfAt(self, msg.sender, disp.disputeUintVars[keccak256("blockNumber")]) + tellorToken.balanceOfAt(msg.sender,disp.disputeUintVars[keccak256("blockNumber")]);
//Require that the msg.sender has not voted
require(disp.voted[msg.sender] != true, "Sender has already voted");
//Requre that the user had a balance >0 at time/blockNumber the disupte began
require(voteWeight > 0, "User balance is 0");
//ensures miners that are under dispute cannot vote
require(self.stakerDetails[msg.sender].currentStatus != 3, "Miner is under dispute");
//Update user voting status to true
disp.voted[msg.sender] = true;
//Update the number of votes for the dispute
disp.disputeUintVars[keccak256("numberOfVotes")] += 1;
//If the user supports the dispute increase the tally for the dispute by the voteWeight
if (_supportsDispute) {
disp.tally = disp.tally.add(int256(voteWeight));
} else {
disp.tally = disp.tally.sub(int256(voteWeight));
}
//Let the network know the user has voted on the dispute and their casted vote
emit Voted(_disputeId, _supportsDispute, msg.sender);
}
/**
* @dev tallies the votes.
* @param _disputeId is the dispute id
*/
function tallyVotes(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId) public {
TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
//Ensure this has not already been executed/tallied
require(disp.executed == false, "Dispute has been already executed");
require(disp.reportingParty != address(0));
//Ensure the time for voting has elapsed
require(now > disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't elapsed");
TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner];
//If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported
// miner and transfer the stakeAmount and dispute fee to the reporting party
if (disp.tally > 0) {
//Set the dispute state to passed/true
disp.disputeVotePassed = true;
}
if (stakes.currentStatus == 3){
stakes.currentStatus = 4;
}
//update the dispute status to executed
disp.executed = true;
disp.disputeUintVars[keccak256("tallyDate")] = now;
emit DisputeVoteTallied(_disputeId, disp.tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed);
}
/**
* @dev Unlocks the dispute fee
* @param _disputeId is the dispute id
*/
function unlockDisputeFee (TellorStorage.TellorStorageStruct storage self, uint _disputeId) public {
bytes32 _hash = self.disputesById[_disputeId].hash;
uint256 _finalId = self.disputeIdsByDisputeHash[_hash][self.disputeIdsByDisputeHash[_hash].length - 1];
TellorStorage.Dispute storage disp = self.disputesById[_finalId];
require(disp.disputeUintVars[keccak256("paid")] == 0,"already paid out");
require(now - disp.disputeUintVars[keccak256("tallyDate")] > 1 days, "Time for voting haven't elapsed");
TokenInterface tellorToken = TokenInterface(self.addressVars[keccak256("tellorToken")]);
TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner];
disp.disputeUintVars[keccak256("paid")] = 1;
if (disp.disputeVotePassed == true){
//if reported miner stake has not been slashed yet, slash them and return the fee to reporting party
if (stakes.currentStatus == 4) {
//Changing the currentStatus and startDate unstakes the reported miner and transfers the stakeAmount
self.uintVars[keccak256("stakerCount")] -= 1;
stakes.startDate = now - (now % 86400);
TellorStake.removeFromStakerArray(self, stakes.stakePosition[0],disp.reportedMiner);
//Decreases the stakerCount since the miner's stake is being slashed
TellorTransfer.doTransfer(self,disp.reportedMiner,address(0),self.uintVars[keccak256("minimumStake")]);
if (TellorTransfer.balanceOf(self,disp.reportedMiner) == 0){
stakes.currentStatus =0 ;
self.uintVars[keccak256("uniqueStakers")] -= 1;
}else{
stakes.currentStatus = 1;
}
self.uintVars[keccak256("totalStaked")] -= self.uintVars[keccak256("minimumStake")];
for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){
uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1];
disp = self.disputesById[_id];
if(i == 1){
tellorToken.transfer(disp.reportingParty,self.uintVars[keccak256("minimumStake")] + disp.disputeUintVars[keccak256("fee")]);
}
else{
tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]);
}
}
//if reported miner stake was already slashed, return the fee to other reporting paties
} else {
for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){
uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1];
disp = self.disputesById[_id];
tellorToken.transfer(disp.reportingParty,disp.disputeUintVars[keccak256("fee")]);
}
}
}
else {
if (stakes.currentStatus == 4){
stakes.currentStatus = 1;
}
TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]];
if(disp.disputeUintVars[keccak256("minerSlot")] == 2) {
//note we still don't put timestamp back into array (is this an issue? (shouldn't be))
_request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = disp.disputeUintVars[keccak256("value")];
}
//tranfer the dispute fee to the miner
if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) {
_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false;
}
for(uint i = 1; i <= self.disputeIdsByDisputeHash[disp.hash].length;i++){
uint256 _id = self.disputeIdsByDisputeHash[_hash][i-1];
disp = self.disputesById[_id];
tellorToken.transfer(disp.reportedMiner,disp.disputeUintVars[keccak256("fee")]);
}
}
}
}
/**
* @title Tellor Getters
* @dev Oracle contract with all tellor getter functions. The logic for the functions on this contract
* is saved on the TellorGettersLibrary, TellorTransfer, TellorGettersLibrary, and TellorStake
*/
contract TellorGetters {
using SafeMath for uint256;
using TellorTransfer for TellorStorage.TellorStorageStruct;
using TellorGettersLibrary for TellorStorage.TellorStorageStruct;
using TellorStake for TellorStorage.TellorStorageStruct;
using TellorDispute for TellorStorage.TellorStorageStruct;
using TellorLibrary for TellorStorage.TellorStorageStruct;
TellorStorage.TellorStorageStruct tellor;
/**
* @dev This function tells you if a given challenge has been completed by a given miner
* @param _challenge the challenge to search for
* @param _miner address that you want to know if they solved the challenge
* @return true if the _miner address provided solved the
*/
function didMine(bytes32 _challenge, address _miner) external view returns (bool) {
return tellor.didMine(_challenge, _miner);
}
/**
* @dev This function gets the balance of the specified user address
* @param _user is the address to check the balance for
*/
function balanceOf(address _user) external view returns(uint256){
return tellor.balanceOf(_user);
}
/**
* @dev This function gets the currently selected validators
* @return an array of the currently selected validators
*/
function getCurrentMiners() external view returns(address[] memory miners){
return tellor.getCurrentMiners();
}
/**
* @dev Checks if an address voted in a given dispute
* @param _disputeId to look up
* @param _address to look up
* @return bool of whether or not party voted
*/
function didVote(uint256 _disputeId, address _address) external view returns (bool) {
return tellor.didVote(_disputeId, _address);
}
/**
* @dev allows Tellor to read data from the addressVars mapping
* @param _data is the keccak256("variable_name") of the variable that is being accessed.
* These are examples of how the variables are saved within other functions:
* addressVars[keccak256("_owner")]
* addressVars[keccak256("tellorContract")]
*/
function getAddressVars(bytes32 _data) external view returns (address) {
return tellor.getAddressVars(_data);
}
/**
* @dev Gets all dispute variables
* @param _disputeId to look up
* @return bytes32 hash of dispute
* @return bool executed where true if it has been voted on
* @return bool disputeVotePassed
* @return address of reportedMiner
* @return address of reportingParty
* @return uint of requestId
* @return uint of timestamp
* @return uint of value
* @return uint of minExecutionDate
* @return uint of numberOfVotes
* @return uint of blocknumber
* @return uint of minerSlot
* @return uint of quorum
* @return uint of fee
* @return int count of the current tally
*/
function getAllDisputeVars(uint256 _disputeId)
public
view
returns (bytes32, bool, bool, address, address, uint256[9] memory, int256)
{
return tellor.getAllDisputeVars(_disputeId);
}
/**
* @dev Getter function for variables for the requestId validators are currently providing data for
* @return current challenge, curretnRequestId, total tip for the request
*/
function getCurrentVariables() external view returns (bytes32, uint256, uint256) {
return tellor.getCurrentVariables();
}
/**
* @dev Checks if a given hash of validator,requestId has been disputed
* @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId));
* @return uint array of disputeIds
*/
function getDisputeIdsByDisputeHash(bytes32 _hash) external view returns (uint256[] memory) {
return tellor.getDisputeIdsByDisputeHash(_hash);
}
/**
* @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId
* @param _disputeId is the dispute id;
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the disputeUintVars under the Dispute struct
* @return uint value for the bytes32 data submitted
*/
function getDisputeUintVars(uint256 _disputeId, bytes32 _data) external view returns (uint256) {
return tellor.getDisputeUintVars(_disputeId, _data);
}
/**
* @dev Gets the a value for the latest timestamp available
* @return value for timestamp of last proof of work submited
* @return true if the is a timestamp for the lastNewValue
*/
function getLastNewValue() external view returns (uint256, bool) {
return tellor.getLastNewValue();
}
/**
* @dev Gets the a value for the latest timestamp available
* @param _requestId being requested
* @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't
*/
function getLastNewValueById(uint256 _requestId) external view returns (uint256, bool) {
return tellor.getLastNewValueById(_requestId);
}
/**
* @dev Gets blocknumber for mined timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up blocknumber
* @return uint of the blocknumber which the dispute was mined
*/
function getMinedBlockNum(uint256 _requestId, uint256 _timestamp) external view returns (uint256) {
return tellor.getMinedBlockNum(_requestId, _timestamp);
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return the 5 miners' addresses
*/
function getMinersByRequestIdAndTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (address[5] memory) {
return tellor.getMinersByRequestIdAndTimestamp(_requestId, _timestamp);
}
/**
* @dev Counts the number of values that have been submited for the request
* if called for the currentRequest being mined it can tell you how many miners have submitted a value for that
* request so far
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(uint256 _requestId) external view returns (uint256) {
return tellor.getNewValueCountbyRequestId(_requestId);
}
/**
* @dev Getter function for the specified requestQ index
* @param _index to look up in the requestQ array
* @return uint of reqeuestId
*/
function getRequestIdByRequestQIndex(uint256 _index) external view returns (uint256) {
return tellor.getRequestIdByRequestQIndex(_index);
}
/**
* @dev Getter function for requestId based on timestamp
* @param _timestamp to check requestId
* @return uint of reqeuestId
*/
function getRequestIdByTimestamp(uint256 _timestamp) external view returns (uint256) {
return tellor.getRequestIdByTimestamp(_timestamp);
}
/**
* @dev Getter function for the requestQ array
* @return the requestQ arrray
*/
function getRequestQ() public view returns (uint256[51] memory) {
return tellor.getRequestQ();
}
/**
* @dev Allows access to the uint variables saved in the apiUintVars under the requestDetails struct
* for the requestId specified
* @param _requestId to look up
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the apiUintVars under the requestDetails struct
* @return uint value of the apiUintVars specified in _data for the requestId specified
*/
function getRequestUintVars(uint256 _requestId, bytes32 _data) external view returns (uint256) {
return tellor.getRequestUintVars(_requestId, _data);
}
/**
* @dev Gets the API struct variables that are not mappings
* @param _requestId to look up
* @return uint of index in requestQ array
* @return uint of current payout/tip for this requestId
*/
function getRequestVars(uint256 _requestId) external view returns (uint256, uint256) {
return tellor.getRequestVars(_requestId);
}
/**
* @dev This function allows users to retireve all information about a staker
* @param _staker address of staker inquiring about
* @return uint current state of staker
* @return uint startDate of staking
* @return uint stakePosition for the staker
*/
function getStakerInfo(address _staker) external view returns (uint256, uint256,uint256) {
return tellor.getStakerInfo(_staker);
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestampt to look up miners for
* @return address[5] array of 5 addresses ofminers that mined the requestId
*/
function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp) external view returns (uint256[5] memory) {
return tellor.getSubmissionsByTimestamp(_requestId, _timestamp);
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestID is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index) external view returns (uint256) {
return tellor.getTimestampbyRequestIDandIndex(_requestID, _index);
}
/**
* @dev Getter for the variables saved under the TellorStorageStruct uintVars variable
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the uintVars under the TellorStorageStruct struct
* This is an example of how data is saved into the mapping within other functions:
* self.uintVars[keccak256("stakerCount")]
* @return uint of specified variable
*/
function getUintVar(bytes32 _data) public view returns (uint256) {
return tellor.getUintVar(_data);
}
/**
* @dev Getter function for next requestId on queue/request with highest payout at time the function is called
* @return onDeck/info on request with highest payout-- RequestId, Totaltips
*/
function getVariablesOnDeck() external view returns (uint256, uint256) {
return tellor.getVariablesOnDeck();
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(uint256 _requestId, uint256 _timestamp) external view returns (bool) {
return tellor.isInDispute(_requestId, _timestamp);
}
/**
* @dev Retreive value from oracle based on timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return value for timestamp submitted
*/
function retrieveData(uint256 _requestId, uint256 _timestamp) external view returns (uint256) {
return tellor.retrieveData(_requestId, _timestamp);
}
}
/**
* @title Tellor Oracle System
* @dev Oracle contract where miners can submit the proof of work along with the value.
* The logic for this contract is in TellorLibrary.sol, TellorDispute.sol, TellorStake.sol,
* and TellorTransfer.sol
*/
contract Tellor is TellorGetters{
using SafeMath for uint256;
event NewTellorToken(address _token);
/*Functions*/
constructor (address _tellorToken) public {
tellor.uintVars[keccak256("decimals")] = 18;
tellor.uintVars[keccak256("disputeFee")] = 10e18;
tellor.uintVars[keccak256("minimumStake")] = 100e18;
tellor.addressVars[keccak256("tellorToken")] = _tellorToken;
emit NewTellorToken(_tellorToken);
}
/**
* @dev Helps initialize a dispute by assigning it a disputeId
* when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the
* invalidated value information to POS voting
* @param _requestId being disputed
* @param _timestamp being disputed
* @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value
* requires 5 miners to submit a value.
*/
function beginDispute(uint256 _requestId, uint256 _timestamp, uint256 _minerIndex) external {
tellor.beginDispute(_requestId, _timestamp, _minerIndex);
}
/**
* @dev Allows token holders to vote
* @param _disputeId is the dispute id
* @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute)
*/
function vote(uint256 _disputeId, bool _supportsDispute) external {
tellor.vote(_disputeId, _supportsDispute);
}
/**
* @dev tallies the votes.
* @param _disputeId is the dispute id
*/
function tallyVotes(uint256 _disputeId) external {
tellor.tallyVotes(_disputeId);
}
/**
* @dev Add tip to Request value from oracle
* @param _requestId being requested to be mined
* @param _tip amount the requester is willing to pay to be get on queue. Miners
* mine the onDeckQueryHash, or the api with the highest payout pool
*/
function addTip(uint256 _requestId, uint256 _tip) external {
tellor.addTip(_requestId, _tip);
}
/**
* @dev Proof of work is called by the miner when they submit the solution (proof of work and value)
* @param _requestId the apiId being mined
* @param _value of api query
*/
function submitMiningSolution(uint256 _requestId, uint256 _value) external {
tellor.submitMiningSolution(_requestId, _value);
}
/**
* @dev This function allows miners to deposit their stake.
* @param _amount is the amount the sender wants to stake
*/
function depositStake(uint _amount) external {
tellor.depositStake(_amount);
}
/**
* @dev This function reselects validators if the originals did not complete the block
*/
function reselectNewValidators() external{
tellor.reselectNewValidators();
}
/**
* @dev This function allows stakers to request to withdraw their stake (no longer stake)
* once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they
* can withdraw the stake
* @param _amount to unstake
*/
function requestStakingWithdraw(uint _amount) external {
tellor.requestStakingWithdraw(_amount);
}
/**
* @dev This function allows for the dispute fee to be unlocked after the dispute vote has elapsed
* @param _disputeId is the disputeId to unlock the fee from
*/
function unlockDisputeFee (uint _disputeId) external{
tellor.unlockDisputeFee(_disputeId);
}
/**
* @dev This function allows users to withdraw their stake after a 7 day waiting period from request
*/
function withdrawStake() external {
tellor.withdrawStake();
}
/**
* @dev Allows users to access the token's name
*/
function name() external pure returns (string memory) {
return "Tellor Tributes";
}
/**
* @dev Allows users to access the token's symbol
*/
function symbol() external pure returns (string memory) {
return "TRB";
}
/**
* @dev Allows users to access the number of decimals
*/
function decimals() external pure returns (uint8) {
return 18;
}
}
|
Gets all dispute variables _disputeId to look up return bytes32 hash of dispute return bool executed where true if it has been voted on return bool disputeVotePassed return address of reportedMiner return address of reportingParty return address of proposedForkAddress return uint of requestId return uint of timestamp return uint of value return uint of minExecutionDate return uint of numberOfVotes return uint of blocknumber return uint of minerSlot return uint of quorum return uint of fee return int count of the current tally/
|
function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId)
internal
view
returns (bytes32, bool, bool, address, address, uint256[9] memory, int256)
{
TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
return (
disp.hash,
disp.executed,
disp.disputeVotePassed,
disp.reportedMiner,
disp.reportingParty,
[
disp.disputeUintVars[keccak256("requestId")],
disp.disputeUintVars[keccak256("timestamp")],
disp.disputeUintVars[keccak256("value")],
disp.disputeUintVars[keccak256("minExecutionDate")],
disp.disputeUintVars[keccak256("numberOfVotes")],
disp.disputeUintVars[keccak256("blockNumber")],
disp.disputeUintVars[keccak256("minerSlot")],
disp.disputeUintVars[keccak256("quorum")],
disp.disputeUintVars[keccak256("fee")]
],
disp.tally
);
}
| 12,578,965
|
pragma solidity ^0.4.23;
/// @title Listing
/// @dev An indiviual O2OProtocol Listing representing an offer for booking/purchase
import "./Purchase.sol";
import "./PurchaseLibrary.sol";
contract Listing {
uint public DEFAULT_EXPIRATION = 60 days;
/*
* Events
*/
event ListingPurchased(Purchase _purchaseContract);
event ListingChange();
/*
* Storage
*/
address public owner;
address public listingRegistry; // TODO: Define interface for real ListingRegistry ?
// Assume IPFS defaults for hash: function:0x12=sha2, size:0x20=256 bits
// See: https://ethereum.stackexchange.com/a/17112/20332
// This assumption may have to change in future, but saves space now
bytes32 public ipfsHash;
uint public price;
uint public unitsAvailable;
uint public created;
uint public expiration;
Purchase[] public purchases;
constructor (
address _owner,
bytes32 _ipfsHash,
uint _price,
uint _unitsAvailable
)
public
{
owner = _owner;
listingRegistry = msg.sender; // ListingRegistry(msg.sender);
ipfsHash = _ipfsHash;
price = _price;
unitsAvailable = _unitsAvailable;
created = now;
expiration = created + DEFAULT_EXPIRATION;
}
/*
* Modifiers
*/
modifier isSeller() {
require(msg.sender == owner);
_;
}
/*
* Public functions
*/
function data()
public
view
returns (address _owner, bytes32 _ipfsHash, uint _price, uint _unitsAvailable, uint _created, uint _expiration)
{
return (owner, ipfsHash, price, unitsAvailable, created, expiration);
}
/// @dev buyListing(): Buy a listing
/// @param _unitsToBuy Number of units to buy
function buyListing(uint _unitsToBuy)
public
payable
{
// Ensure that this is not trying to purchase more than is available.
require(_unitsToBuy <= unitsAvailable);
// Ensure that we are not past the expiration
require(now < expiration);
// Create purchase contract
Purchase purchaseContract = PurchaseLibrary.newPurchase(this, msg.sender);
// Count units as sold
unitsAvailable -= _unitsToBuy;
purchases.push(purchaseContract);
//TODO: How to call function *AND* transfer value??
purchaseContract.pay.value(msg.value)();
emit ListingPurchased(purchaseContract);
emit ListingChange();
}
/// @dev close(): Allows a seller to close the listing from further purchases
function close()
public
isSeller
{
unitsAvailable = 0;
emit ListingChange();
}
/// @dev purchasesLength(): Return number of purchases for a given listing
function purchasesLength()
public
constant
returns (uint)
{
return purchases.length;
}
/// @dev getPurchase(): Return purchase info for a given listing
/// @param _index the index of the listing we want info about
function getPurchase(uint _index)
public
constant
returns (Purchase)
{
return (
purchases[_index]
);
}
}
|
close(): Allows a seller to close the listing from further purchases
|
function close()
public
isSeller
{
unitsAvailable = 0;
emit ListingChange();
}
| 12,737,851
|
// SPDX-License-Identifier: Apache-2.0
/******************************************************************************
* Copyright 2020 IEXEC BLOCKCHAIN TECH *
* *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
******************************************************************************/
pragma solidity ^0.6.0;
import "./CounterfactualFactory.sol";
contract GenericFactory is CounterfactualFactory
{
event NewContract(address indexed addr);
function predictAddress(bytes memory _code, bytes32 _salt)
public view returns(address)
{
return predictAddressWithCall(_code, _salt, bytes(""));
}
function createContract(bytes memory _code, bytes32 _salt)
public returns(address)
{
return createContractAndCall(_code, _salt, bytes(""));
}
function predictAddressWithCall(bytes memory _code, bytes32 _salt, bytes memory _call)
public view returns(address)
{
return _predictAddress(_code, keccak256(abi.encodePacked(_salt, _call)));
}
function createContractAndCall(bytes memory _code, bytes32 _salt, bytes memory _call)
public returns(address)
{
address addr = _create2(_code, keccak256(abi.encodePacked(_salt, _call)));
emit NewContract(addr);
if (_call.length > 0)
{
// solium-disable-next-line security/no-low-level-calls
(bool success, bytes memory reason) = addr.call(_call);
require(success, string(reason));
}
return addr;
}
}
|
solium-disable-next-line security/no-low-level-calls
|
function createContractAndCall(bytes memory _code, bytes32 _salt, bytes memory _call)
public returns(address)
{
address addr = _create2(_code, keccak256(abi.encodePacked(_salt, _call)));
emit NewContract(addr);
if (_call.length > 0)
{
(bool success, bytes memory reason) = addr.call(_call);
require(success, string(reason));
}
return addr;
}
| 1,836,372
|
pragma solidity 0.5.12;
//contrato simples de aluguel. Por convenção, o nome, após contract começa com letra maiúscula.
contract Aluguel
{
string public locatario;
string public locador;
uint256 private valor;
uint256 constant numeroMaximoLegalDeAlugueisparaMulta = 3;
// Constructor deve sempre ser público, mesmo que as variáveis parâmetros sejam privadas, pois é a primeira coisa que a VM
// do ethereum vai chamar.
// As variaveis de uma função NÂO ficam armazenadas na blockchain, somente aquelas declaradas fora, como as acima.
constructor ( string memory nomeLocador, string memory nomeLocatario, uint256 valorDoAluguel) public
{
locador = nomeLocador;
locatario = nomeLocatario;
valor = valorDoAluguel;
}
function valorAtualDoAluguel () public view returns (uint256)
{
return valor;
}
// Os parametros serão adicionados pelo usuario no Remix, no campo de deployed contracts, ou numa pagina frontend
// desenvolvida para isso
function simulaMulta ( uint256 mesesRestantes, uint256 totalMesesContrato) public view returns ( uint256 valorMulta)
{
valorMulta = valor*numeroMaximoLegalDeAlugueisparaMulta;
valorMulta = valorMulta/totalMesesContrato;
valorMulta = valorMulta*mesesRestantes;
return valorMulta;
}
function reajustaAluguel (uint256 percentualReajuste) public
{
// Essa condicional IF limita o percentual de reajuste a 20 %, igualando qualquer valor acima disso
// a 20. Dessa forma, tranfere-se para o SC um acordo de teto de reajuste entre as partes, por exemplo.
if (percentualReajuste > 20)
{
percentualReajuste = 20;
}
uint256 valorDoAcrescimo = 0;
valorDoAcrescimo = ((valor*percentualReajuste)/100);
valor = valor + valorDoAcrescimo;
}
// Adição Aula dia 8, para retificar um erro de valor p ex., quando, sem querer, se reajuste o Aluguel
// mais de uma vez. Essa funcao irá simplesmente corrigir o valor de uma vez, pois armazenar o valor
// original na BC custa Ether, e ficar realizando equações custa Gas.
function aditamentoValorAluguel (uint256 valorCerto) public
{
valor = valorCerto;
}
//
//
function aplicaMulta (uint256 mesesRestantes, uint256 percentual) public
{
// função require ira pedir algo para que a função descrita possa ser executada. É um requerimento. Nesse caso
// que o número restante de meses seja menor que trinta. Caso contrario nao deixará, e exibirá a mensagem.
require (mesesRestantes < 30, "Período de Contrato Inválido");
// looping for. Enquanto a condição for verdadeira, o comando será realizado. Quando ficar falsa, encerra o loop.
// Para os parametros, declara uma variável i com o seu valor inicial, a condição do loop, e a soma da variável + 1
// após a execução do comando.
for (uint256 i = 1; i < mesesRestantes; i++)
{
valor = valor + ((valor * percentual)/100);
}
}
}
|
Os parametros serão adicionados pelo usuario no Remix, no campo de deployed contracts, ou numa pagina frontend desenvolvida para isso
|
function simulaMulta ( uint256 mesesRestantes, uint256 totalMesesContrato) public view returns ( uint256 valorMulta)
{
valorMulta = valor*numeroMaximoLegalDeAlugueisparaMulta;
valorMulta = valorMulta/totalMesesContrato;
valorMulta = valorMulta*mesesRestantes;
return valorMulta;
}
| 12,701,074
|
/**
*Submitted for verification at Etherscan.io on 2021-03-16
*/
// SPDX-License-Identifier: MIT
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
function decimals() external view returns (uint8);
/**
* @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/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _governance;
event GovernanceTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_governance = msgSender;
emit GovernanceTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function governance() public view returns (address) {
return _governance;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyGovernance() {
require(_governance == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferGovernance(address newOwner) internal virtual onlyGovernance {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit GovernanceTransferred(_governance, newOwner);
_governance = newOwner;
}
}
// File: contracts/strategies/StabilizeStrategyUSTFlashArbV3.sol
pragma solidity ^0.6.6;
// This is a strategy that takes advantage of arb opportunities for ust
// Users deposit ust into the strategy and the strategy will sell into usdt when above usdt and usdt into ust when below
// Selling will occur via Uniswap or Curve and buying WETH via Uniswap
// Half the profit earned from the sell will be used to buy WETH and split it between the treasury, executor and staking pool
// Half will remain
// This strategy also uses flash loans to take advantage of opportunities in price inversions between exchanges
// Strategy takes into account 0.3% slippage estimate for large sells on Uniswap
// Strat will give executors option to skip flash loan to save gas, without flash loan, it only uses curve
interface StabilizeStakingPool {
function notifyRewardAmount(uint256) external;
}
interface UniswapRouter {
function swapExactETHForTokens(uint, address[] calldata, address, uint) external payable returns (uint[] memory);
function swapExactTokensForTokens(uint, uint, address[] calldata, address, uint) external returns (uint[] memory);
function getAmountsOut(uint, address[] calldata) external view returns (uint[] memory); // For a value in, it calculates value out
}
interface CurvePool {
function get_dy_underlying(int128, int128, uint256) external view returns (uint256); // Get quantity estimate
function exchange_underlying(int128, int128, uint256, uint256) external; // Exchange tokens
}
interface LendingPoolAddressesProvider {
function getLendingPool() external view returns (address);
}
interface LendingPool {
function flashLoan(address, address[] calldata, uint256[] calldata, uint256[] calldata, address, bytes calldata params, uint16) external;
}
interface AggregatorV3Interface {
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
contract StabilizeStrategyUSTFlashArbV3 is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Address for address;
address public treasuryAddress; // Address of the treasury
address public stakingAddress; // Address to the STBZ staking pool
address public zsTokenAddress; // The address of the controlling zs-Token
uint256 constant DIVISION_FACTOR = 100000;
uint256 public lastTradeTime = 0;
uint256 public lastActionBalance = 0; // Balance before last deposit or withdraw
uint256 public maxPoolSize = 3000000e18; // The maximum amount of ust tokens this strategy can hold, 3 mil by default
uint256 public percentTradeTrigger = 10000; // 10% change in value will trigger a trade
uint256 public maxSlippage = 300; // 0.3% max slippage is ok
uint256 public maxPercentSell = 80000; // 80% of the tokens are sold to the cheapest token if slippage is ok on Uni
uint256 public maxAmountSell = 500000; // The maximum amount of tokens that can be sold at once
uint256 public percentDepositor = 50000; // 1000 = 1%, depositors earn 50% of all gains
uint256 public percentExecutor = 10000; // 30000 = 30% of WETH goes to executor, 15% of total profit
uint256 public percentStakers = 50000; // 50% of non-depositors WETH goes to stakers, can be changed
uint256 public minTradeSplit = 20000; // If the balance is less than or equal to this, it trades the entire balance
uint256 public maxPercentStipend = 30000; // The maximum amount of WETH profit that can be allocated to the executor for gas in percent
uint256 public gasStipend = 1000000; // This is the gas units that are covered by executing a trade taken from the WETH profit
uint256[3] private flashParams; // Global parameters guiding the flash loan setup
uint256 constant minGain = 1e16; // Minimum amount of gain (0.01 coin) before buying WETH and splitting it
// Token information
// This strategy accepts frax and usdc
struct TokenInfo {
IERC20 token; // Reference of token
uint256 decimals; // Decimals of token
}
TokenInfo[] private tokenList; // An array of tokens accepted as deposits
// Strategy specific variables
address constant UNISWAP_ROUTER_ADDRESS = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); //Address of Uniswap
address constant CURVE_UST_POOL = address(0x890f4e345B1dAED0367A877a1612f86A1f86985f);
address constant WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle
address constant LENDING_POOL_ADDRESS_PROVIDER = address(0xB53C1a33016B2DC2fF3653530bfF1848a515c8c5); // Provider for Aave addresses
constructor(
address _treasury,
address _staking,
address _zsToken
) public {
treasuryAddress = _treasury;
stakingAddress = _staking;
zsTokenAddress = _zsToken;
setupWithdrawTokens();
}
// Initialization functions
function setupWithdrawTokens() internal {
// Start with UST
IERC20 _token = IERC20(address(0xa47c8bf37f92aBed4A126BDA807A7b7498661acD));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
// USDT
_token = IERC20(address(0xdAC17F958D2ee523a2206206994597C13D831ec7));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals()
})
);
}
// Modifier
modifier onlyZSToken() {
require(zsTokenAddress == _msgSender(), "Call not sent from the zs-Token");
_;
}
// Read functions
function rewardTokensCount() external view returns (uint256) {
return tokenList.length;
}
function rewardTokenAddress(uint256 _pos) external view returns (address) {
require(_pos < tokenList.length,"No token at that position");
return address(tokenList[_pos].token);
}
function balance() public view returns (uint256) {
return getNormalizedTotalBalance(address(this));
}
function getNormalizedTotalBalance(address _address) public view returns (uint256) {
uint256 _balance = 0;
for(uint256 i = 0; i < tokenList.length; i++){
uint256 _bal = tokenList[i].token.balanceOf(_address);
_bal = _bal.mul(1e18).div(10**tokenList[i].decimals);
_balance = _balance.add(_bal); // This has been normalized to 1e18 decimals
}
return _balance;
}
function withdrawTokenReserves() public view returns (address, uint256) {
// This function will return the address and amount of frax, then usdc
if(tokenList[0].token.balanceOf(address(this)) > 0){
return (address(tokenList[0].token), tokenList[0].token.balanceOf(address(this)));
}else if(tokenList[1].token.balanceOf(address(this)) > 0){
return (address(tokenList[1].token), tokenList[1].token.balanceOf(address(this)));
}else{
return (address(0), 0); // No balance
}
}
// Write functions
function enter() external onlyZSToken {
deposit(false);
}
function exit() external onlyZSToken {
// The ZS token vault is removing all tokens from this strategy
withdraw(_msgSender(),1,1, false);
}
function deposit(bool nonContract) public onlyZSToken {
// Only the ZS token can call the function
// No trading is performed on deposit
if(nonContract == true){ }
lastActionBalance = balance();
require(lastActionBalance <= maxPoolSize,"This strategy has reached its maximum balance");
}
function simulateExchange(address _inputToken, address _outputToken, uint256 _amount, bool _uniswap) internal view returns (uint256) {
if(_uniswap == true){
// Possible Uniswap routes, UST / USDT, USDT / ETH
UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS);
address[] memory path;
if(_inputToken == address(tokenList[0].token) && _outputToken == WETH_ADDRESS){
// Selling UST for WETH, must go through USDT
path = new address[](3);
path[0] = _inputToken;
path[1] = address(tokenList[1].token);
path[2] = _outputToken;
}else{
path = new address[](2);
path[0] = _inputToken;
path[1] = _outputToken;
}
uint256[] memory estimates = router.getAmountsOut(_amount, path);
_amount = estimates[estimates.length - 1]; // This is the amount of WETH returned
return _amount;
}else{
// We are swapping via curve
CurvePool pool = CurvePool(CURVE_UST_POOL);
int128 inCurve = 0;
int128 outCurve = 0;
if(_inputToken == address(tokenList[1].token)){inCurve = 3;}
if(_outputToken == address(tokenList[1].token)){outCurve = 3;}
return pool.get_dy_underlying(inCurve, outCurve, _amount);
}
}
function exchange(address _inputToken, address _outputToken, uint256 _amount, bool _uniswap) internal {
if(_uniswap == true){
// Possible Uniswap routes, UST / USDT, USDT / ETH
UniswapRouter router = UniswapRouter(UNISWAP_ROUTER_ADDRESS);
address[] memory path;
if(_inputToken == address(tokenList[0].token) && _outputToken == WETH_ADDRESS){
// Selling UST for WETH, must go through USDT
path = new address[](3);
path[0] = _inputToken;
path[1] = address(tokenList[1].token);
path[2] = _outputToken;
}else{
path = new address[](2);
path[0] = _inputToken;
path[1] = _outputToken;
}
IERC20(_inputToken).safeApprove(UNISWAP_ROUTER_ADDRESS, 0);
IERC20(_inputToken).safeApprove(UNISWAP_ROUTER_ADDRESS, _amount);
router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token
return;
}else{
// We are swapping via curve
CurvePool pool = CurvePool(CURVE_UST_POOL);
int128 inCurve = 0;
int128 outCurve = 0;
if(_inputToken == address(tokenList[1].token)){inCurve = 3;}
if(_outputToken == address(tokenList[1].token)){outCurve = 3;}
IERC20(_inputToken).safeApprove(CURVE_UST_POOL, 0);
IERC20(_inputToken).safeApprove(CURVE_UST_POOL, _amount);
pool.exchange_underlying(inCurve, outCurve, _amount, 1);
}
}
function getCheaperToken(bool doFlash) internal view returns (uint256, uint256, bool) {
// This will give us the ID of the cheapest token for both Uniswap and Curve
// We will estimate the return for trading 1 UST
// The higher the return, the lower the price of the other token
// It will also suggest which exchange we should use, Uniswap or Curve
uint256 targetID_1 = 0; // Our target ID is UST first
uint256 targetID_2 = 0;
bool useUni = false;
uint256 ustAmount = uint256(1).mul(10**tokenList[0].decimals);
// Now compare it to USDT on Uniswap
uint256 estimate = 0;
if(doFlash == true){
estimate = simulateExchange(address(tokenList[0].token),address(tokenList[1].token),ustAmount,true);
estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[1].decimals);
if(estimate > ustAmount){
// This token is worth less than the UST on Uniswap
targetID_1 = 1;
}
}
// Now on Curve
uint256 estimate2 = simulateExchange(address(tokenList[0].token),address(tokenList[1].token),ustAmount,false);
estimate2 = estimate2.mul(10**tokenList[0].decimals).div(10**tokenList[1].decimals);
if(estimate2 > ustAmount){
// This token is worth less than UST on curve
targetID_2 = 1;
}
if(doFlash == false){
return (targetID_2, targetID_2, false); // It will trade via curve if no flash loan taken
}else{
// Now determine which exchange offers the better rate between the two
if(targetID_1 == targetID_2){
if(targetID_1 == 1){
// USDT is weaker token on both exchanges
if(estimate2 >= estimate){
// Get more USDT from Curve
useUni = false;
}else{
useUni = true;
}
}else{
// UST is weaker token on both exchanges
if(estimate2 > estimate){
// Get more UST from Uni
useUni = true;
}else{
useUni = false;
}
}
}else{
if(targetID_1 == 0){
// When we flash loan to increase our USDT, sell it on Uni as it is more valuable on there
useUni = true;
}else{
// When we flash loan to increase our USDT, sell it on Curve as it is more valuable there
useUni = false;
}
}
return (targetID_1, targetID_2, useUni);
}
}
function estimateSellAtMaxSlippage(uint256 originID, uint256 targetID, uint256 _balance) internal view returns (uint256) {
// This will estimate the amount that can be sold at the maximum slippage
// We discover the price then compare it to the actual return
// The estimate is based on a linear curve so not 100% representative of Uniswap but close enough
// It will use a 0.1% sell to discover the price first
uint256 minSellPercent = maxPercentSell.div(1000);
uint256 _amount = _balance.mul(minSellPercent).div(DIVISION_FACTOR);
if(_amount == 0){ return 0; } // Nothing to sell, can't calculate
uint256 _maxReturn = simulateExchange(address(tokenList[originID].token), address(tokenList[targetID].token), _amount, true);
_maxReturn = _maxReturn.mul(1000); // Without slippage, this would be our maximum return
// Now calculate the slippage at the max percent
_amount = _balance.mul(maxPercentSell).div(DIVISION_FACTOR);
uint256 _return = simulateExchange(address(tokenList[originID].token), address(tokenList[targetID].token), _amount, true);
if(_return >= _maxReturn){
// This shouldn't be possible
return _amount; // Sell the entire amount
}
// Calculate slippage
uint256 percentSlip = uint256(_maxReturn.mul(DIVISION_FACTOR)).sub(_return.mul(DIVISION_FACTOR)).div(_maxReturn);
if(percentSlip <= maxSlippage){
return _amount; // This is less than our maximum slippage, sell it all
}
return _amount.mul(maxSlippage).div(percentSlip); // This will be the sell amount at max slip
}
function estimateFlashLoanResult(uint256 point1, uint256 point2, uint256 _amount) internal view returns (uint256) {
// This will estimate the return of our flash loan minus the fee
uint256 fee = _amount.mul(90).div(DIVISION_FACTOR); // This is the Aave fee (0.09%)
uint256 gain = 0;
if(point2 > point1){
// USL price is lower than USDT on Uniswap, while higher on Curve
// Use the borrowed USDT to buy USL on Uniswap
gain = simulateExchange(address(tokenList[1].token), address(tokenList[0].token), _amount, true); // Receive USL
gain = simulateExchange(address(tokenList[0].token), address(tokenList[1].token), gain, false); // Receive USDT
}else{
// USL price higher than USDT on Uniswap while lower on Curve
gain = simulateExchange(address(tokenList[1].token), address(tokenList[0].token), _amount, false); // Receive USL
gain = simulateExchange(address(tokenList[0].token), address(tokenList[1].token), gain, true); // Receive USDT
}
if(gain > _amount.add(fee)){
// Positive return on the flash
gain = gain.sub(fee).sub(_amount); // Get the pure gain after returning the funds with a fee
return gain;
}else{
return 0; // Do not take out a flash loan as not enough gain
}
}
function performFlashLoan(uint256 point1, uint256 point2, uint256 _amount) internal returns (uint256) {
// Will call Aave
uint256 flashGain = tokenList[1].token.balanceOf(address(this));
flashParams[0] = 1; // Authorize flash loan receiving
flashParams[1] = point1;
flashParams[2] = point2;
// Call the flash loan
LendingPool lender = LendingPool(LendingPoolAddressesProvider(LENDING_POOL_ADDRESS_PROVIDER).getLendingPool()); // Load the lending pool
address[] memory assets = new address[](1);
assets[0] = address(tokenList[1].token);
uint256[] memory amounts = new uint256[](1);
amounts[0] = _amount; // The amount we want to borrow
uint256[] memory modes = new uint256[](1);
modes[0] = 0; // Revert if fail to return funds
bytes memory params = "";
lender.flashLoan(address(this), assets, amounts, modes, address(this), params, 0);
flashParams[0] = 0; // Deactivate flash loan receiving
uint256 newBal = tokenList[1].token.balanceOf(address(this));
require(newBal > flashGain, "Flash loan failed to increase balance");
flashGain = newBal.sub(flashGain);
uint256 payout = flashGain.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR);
if(payout > 0){
// Convert part to WETH
exchange(address(tokenList[1].token), WETH_ADDRESS, payout, true);
}
return flashGain;
}
function executeOperation(
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata premiums,
address initiator,
bytes calldata params
)
external
returns (bool)
{
require(flashParams[0] == 1, "No flash loan authorized on this contract");
address lendingPool = LendingPoolAddressesProvider(LENDING_POOL_ADDRESS_PROVIDER).getLendingPool();
require(_msgSender() == lendingPool, "Not called from Aave");
require(initiator == address(this), "Not Authorized"); // Prevent other contracts from calling this function
if(params.length == 0){} // Removes the warning
flashParams[0] = 0; // Prevent a replay;
{
// Create inner scope to prevent stack too deep error
uint256 point1 = flashParams[1];
uint256 point2 = flashParams[2];
uint256 _bal;
// Swap the amounts to earn more
if(point2 > point1){
// USL price is lower than USDT on Uniswap, while higher on Curve
// Use the borrowed USDT to buy USL on Uniswap
_bal = tokenList[0].token.balanceOf(address(this));
exchange(address(tokenList[1].token), address(tokenList[0].token), amounts[0], true); // Receive USL
_bal = tokenList[0].token.balanceOf(address(this)).sub(_bal);
exchange(address(tokenList[0].token), address(tokenList[1].token), _bal, false); // Receive USDT
}else{
// USL price higher than USDT on Uniswap while lower on Curve
_bal = tokenList[0].token.balanceOf(address(this));
exchange(address(tokenList[1].token), address(tokenList[0].token), amounts[0], false); // Receive USL
_bal = tokenList[0].token.balanceOf(address(this)).sub(_bal);
exchange(address(tokenList[0].token), address(tokenList[1].token), _bal, true); // Receive USDT
}
}
// Authorize Aave to pull funds from this contract
// Approve the LendingPool contract allowance to *pull* the owed amount
for(uint256 i = 0; i < assets.length; i++) {
uint256 amountOwing = amounts[i].add(premiums[i]);
IERC20(assets[i]).safeApprove(lendingPool, 0);
IERC20(assets[i]).safeApprove(lendingPool, amountOwing);
}
return true;
}
function getFastGasPrice() internal view returns (uint256) {
AggregatorV3Interface gasOracle = AggregatorV3Interface(GAS_ORACLE_ADDRESS);
( , int intGasPrice, , , ) = gasOracle.latestRoundData(); // We only want the answer
return uint256(intGasPrice);
}
function checkAndSwapTokens(address _executor, bool doFlash) internal {
lastTradeTime = now;
// Now find our target token to sell into
(uint256 targetID_1, uint256 targetID_2, bool useUniswap) = getCheaperToken(doFlash); // Normally both these values should point to the same ID
uint256 targetID;
if(targetID_1 == targetID_2){
targetID = targetID_1;
}else{
// The fun part (flash laon)
// Since prices are inverse between the exchanges
// We will call Aave to borrow USDT, sell it for UST, sell UST on another exchange for more USDT than we original borrowed
// First determine borrow size at the max slippage
uint256 maxBorrow = uint256(1000000).mul(10**tokenList[1].decimals); // Predict based on $1million
maxBorrow = estimateSellAtMaxSlippage(1, 0, maxBorrow);
// Now estimate the return of the flash loan
if(estimateFlashLoanResult(targetID_1, targetID_2, maxBorrow) > 2){
// Flash loan will be profitable, borrow the funds
performFlashLoan(targetID_1, targetID_2, maxBorrow); // This will return USDT earned and exchange it for WETH
}
targetID = 0; // Sell whatever gains are possible for more UST
}
uint256 gain = 0;
if(doFlash == false){
uint256 length = tokenList.length;
// Now sell all the other tokens into this token
uint256 _totalBalance = balance(); // Get the token balance at this contract, should increase
bool _expectIncrease = false;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 sellBalance = 0;
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals); // Determine the maximum amount of tokens to sell at once
if(tokenList[i].token.balanceOf(address(this)) <= _minTradeTarget){
// If balance is too small,sell all tokens at once
sellBalance = tokenList[i].token.balanceOf(address(this));
}else{
if(useUniswap == true){
sellBalance = estimateSellAtMaxSlippage(i, targetID, tokenList[i].token.balanceOf(address(this))); // This will select a balance with a max slippage
}else{
// Curve supports larger sells
sellBalance = tokenList[i].token.balanceOf(address(this)).mul(maxPercentSell).div(DIVISION_FACTOR);
}
}
if(sellBalance > _maxTradeTarget){
// If greater than the maximum trade allowed, match it
sellBalance = _maxTradeTarget;
}
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
if(sellBalance > 0){
uint256 estimate = simulateExchange(address(tokenList[i].token), address(tokenList[targetID].token), sellBalance, useUniswap);
if(estimate > minReceiveBalance){
_expectIncrease = true;
exchange(address(tokenList[i].token), address(tokenList[targetID].token), sellBalance, useUniswap);
}
}
}
}
uint256 _newBalance = balance();
if(_expectIncrease == true){
// There may be rare scenarios where we don't gain any by calling this function
require(_newBalance > _totalBalance, "Failed to gain in balance from selling tokens");
}
gain = _newBalance.sub(_totalBalance);
}
IERC20 weth = IERC20(WETH_ADDRESS);
uint256 _wethBalance = weth.balanceOf(address(this));
if(gain >= minGain || _wethBalance > 0){
// Minimum gain required to buy WETH is about 0.01 tokens
if(gain >= minGain){
// Buy WETH from Uniswap with tokens
uint256 sellBalance = gain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
uint256 holdBalance = sellBalance.mul(percentDepositor).div(DIVISION_FACTOR);
sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount
if(sellBalance <= tokenList[targetID].token.balanceOf(address(this))){
// Sell some of our gained token for WETH
exchange(address(tokenList[targetID].token), WETH_ADDRESS, sellBalance, true);
_wethBalance = weth.balanceOf(address(this));
}
}
if(_wethBalance > 0){
// Split the rest between the stakers and such
// This is pure profit, figure out allocation
// Split the amount sent to the treasury, stakers and executor if one exists
if(_executor != address(0)){
// Executors will get a gas reimbursement in WETH and a percent of the remaining
uint256 maxGasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
uint256 gasFee = tx.gasprice.mul(gasStipend); // This is gas fee requested
if(gasFee > maxGasFee){
gasFee = maxGasFee; // Gas fee cannot be greater than the maximum
}
uint256 executorAmount = gasFee;
if(gasFee >= _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR)){
executorAmount = _wethBalance.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get the entire amount up to point
}else{
// Add the executor percent on top of gas fee
executorAmount = _wethBalance.sub(gasFee).mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee);
}
if(executorAmount > 0){
weth.safeTransfer(_executor, executorAmount);
_wethBalance = weth.balanceOf(address(this)); // Recalculate WETH in contract
}
}
if(_wethBalance > 0){
uint256 stakersAmount = _wethBalance.mul(percentStakers).div(DIVISION_FACTOR);
uint256 treasuryAmount = _wethBalance.sub(stakersAmount);
if(treasuryAmount > 0){
weth.safeTransfer(treasuryAddress, treasuryAmount);
}
if(stakersAmount > 0){
if(stakingAddress != address(0)){
weth.safeTransfer(stakingAddress, stakersAmount);
StabilizeStakingPool(stakingAddress).notifyRewardAmount(stakersAmount);
}else{
// No staking pool selected, just send to the treasury
weth.safeTransfer(treasuryAddress, stakersAmount);
}
}
}
}
}
}
function expectedProfit(bool inWETHForExecutor, bool doFlash) external view returns (uint256) {
// This view will return the amount of gain a forced swap will make on next call
// Now find our target token to sell into
(uint256 targetID_1, uint256 targetID_2, bool useUniswap) = getCheaperToken(doFlash); // Normally both these values should point to the same ID
uint256 targetID;
uint256 flashGain = 0;
if(targetID_1 == targetID_2){
targetID = targetID_1;
}else{
// The fun part (flash loan)
// Since prices are inverse between the exchanges
// We will call Aave to borrow USDT, sell it for UST, sell UST on another exchange for more USDT than we original borrowed
// First determine borrow size at the max slippage
uint256 maxBorrow = uint256(1000000).mul(10**tokenList[1].decimals); // Predict based on $1million
maxBorrow = estimateSellAtMaxSlippage(1, 0, maxBorrow);
// Now estimate the return of the flash loan
flashGain = estimateFlashLoanResult(targetID_1, targetID_2, maxBorrow);
if(flashGain > 0){
if(inWETHForExecutor == true){
flashGain = simulateExchange(address(tokenList[1].token), WETH_ADDRESS, flashGain.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR), true);
}else{
// Normalize it
flashGain = flashGain.mul(1e18).div(10**tokenList[1].decimals);
}
}
targetID = 0;
}
// Now simulate sell all the other tokens into this token
uint256 _normalizedGain = 0;
if(doFlash == false){
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
uint256 sellBalance = 0;
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals); // Determine the maximum amount of tokens to sell at once
if(tokenList[i].token.balanceOf(address(this)) <= _minTradeTarget){
// If balance is too small,sell all tokens at once
sellBalance = tokenList[i].token.balanceOf(address(this));
}else{
if(useUniswap == true){
sellBalance = estimateSellAtMaxSlippage(i, targetID, tokenList[i].token.balanceOf(address(this))); // This will select a balance with a max slippage
}else{
// Curve supports larger sells
sellBalance = tokenList[i].token.balanceOf(address(this)).mul(maxPercentSell).div(DIVISION_FACTOR);
}
}
if(sellBalance > _maxTradeTarget){
// If greater than the maximum trade allowed, match it
sellBalance = _maxTradeTarget;
}
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
if(sellBalance > 0){
uint256 estimate = simulateExchange(address(tokenList[i].token), address(tokenList[targetID].token), sellBalance, useUniswap);
if(estimate > minReceiveBalance){
uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[targetID].decimals); // Normalized gain
_normalizedGain = _normalizedGain.add(_gain);
}
}
}
}
}
if(inWETHForExecutor == false){
return _normalizedGain.add(flashGain);
}else{
if(_normalizedGain.add(flashGain) == 0){
return 0;
}
// Calculate how much WETH the executor would make as profit
uint256 estimate = flashGain; // WETH earned from flashloan
if(_normalizedGain > 0){
uint256 sellBalance = _normalizedGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
uint256 holdBalance = sellBalance.mul(percentDepositor).div(DIVISION_FACTOR);
sellBalance = sellBalance.sub(holdBalance); // We will buy WETH with this amount
// Estimate output
estimate = estimate.add(simulateExchange(address(tokenList[targetID].token), WETH_ADDRESS, sellBalance, true));
}
// Now calculate the amount going to the executor
uint256 gasFee = getFastGasPrice().mul(gasStipend); // This is gas stipend in wei
if(gasFee >= estimate.mul(maxPercentStipend).div(DIVISION_FACTOR)){ // Max percent of total
return estimate.mul(maxPercentStipend).div(DIVISION_FACTOR); // The executor will get max percent of total
}else{
estimate = estimate.sub(gasFee); // Subtract fee from remaining balance
return estimate.mul(percentExecutor).div(DIVISION_FACTOR).add(gasFee); // Executor amount with fee added
}
}
}
function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) {
require(balance() > 0, "There are no tokens in this strategy");
if(nonContract == true){
if( _share > _total.mul(percentTradeTrigger).div(DIVISION_FACTOR)){
checkAndSwapTokens(_depositor, false);
}
}
uint256 withdrawAmount = 0;
uint256 _balance = balance();
if(_share < _total){
uint256 _myBalance = _balance.mul(_share).div(_total);
withdrawPerOrder(_depositor, _myBalance, false); // This will withdraw based on token price
withdrawAmount = _myBalance;
}else{
// We are all shares, transfer all
withdrawPerOrder(_depositor, _balance, true);
withdrawAmount = _balance;
}
lastActionBalance = balance();
return withdrawAmount;
}
// This will withdraw the tokens from the contract based on their order
function withdrawPerOrder(address _receiver, uint256 _withdrawAmount, bool _takeAll) internal {
uint256 length = tokenList.length;
if(_takeAll == true){
// Send the entire balance
for(uint256 i = 0; i < length; i++){
uint256 _bal = tokenList[i].token.balanceOf(address(this));
if(_bal > 0){
tokenList[i].token.safeTransfer(_receiver, _bal);
}
}
return;
}
for(uint256 i = 0; i < length; i++){
// Determine the balance left
uint256 _normalizedBalance = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
if(_normalizedBalance <= _withdrawAmount){
// Withdraw the entire balance of this token
if(_normalizedBalance > 0){
_withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
tokenList[i].token.safeTransfer(_receiver, tokenList[i].token.balanceOf(address(this)));
}
}else{
// Withdraw a partial amount of this token
if(_withdrawAmount > 0){
// Convert the withdraw amount to the token's decimal amount
uint256 _balance = _withdrawAmount.mul(10**tokenList[i].decimals).div(1e18);
_withdrawAmount = 0;
tokenList[i].token.safeTransfer(_receiver, _balance);
}
break; // Nothing more to withdraw
}
}
}
function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade, bool doFlash) external {
// Function designed to promote trading with incentive. Users get 20% of WETH from profitable trades
require(now.sub(lastTradeTime) > _minSecSinceLastTrade, "The last trade was too recent");
require(_msgSender() == tx.origin, "Contracts cannot interact with this function");
checkAndSwapTokens(_executor, doFlash);
lastActionBalance = balance();
}
// Governance functions
function governanceSwapTokens(bool doFlash) external onlyGovernance {
// This is function that force trade tokens at anytime. It can only be called by governance
checkAndSwapTokens(governance(), doFlash);
lastActionBalance = balance();
}
// Timelock variables
uint256 private _timelockStart; // The start of the timelock to change governance variables
uint256 private _timelockType; // The function that needs to be changed
uint256 constant TIMELOCK_DURATION = 86400; // Timelock is 24 hours
// Reusable timelock variables
address private _timelock_address;
uint256[7] private _timelock_data;
modifier timelockConditionsMet(uint256 _type) {
require(_timelockType == _type, "Timelock not acquired for this function");
_timelockType = 0; // Reset the type once the timelock is used
if(balance() > 0){ // Timelock only applies when balance exists
require(now >= _timelockStart + TIMELOCK_DURATION, "Timelock time not met");
}
_;
}
// Change the owner of the token contract
// --------------------
function startGovernanceChange(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 1;
_timelock_address = _address;
}
function finishGovernanceChange() external onlyGovernance timelockConditionsMet(1) {
transferGovernance(_timelock_address);
}
// --------------------
// Change the treasury address
// --------------------
function startChangeTreasury(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 2;
_timelock_address = _address;
}
function finishChangeTreasury() external onlyGovernance timelockConditionsMet(2) {
treasuryAddress = _timelock_address;
}
// --------------------
// Change the staking address
// --------------------
function startChangeStakingPool(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 3;
_timelock_address = _address;
}
function finishChangeStakingPool() external onlyGovernance timelockConditionsMet(3) {
stakingAddress = _timelock_address;
}
// --------------------
// Change the zsToken address
// --------------------
function startChangeZSToken(address _address) external onlyGovernance {
_timelockStart = now;
_timelockType = 4;
_timelock_address = _address;
}
function finishChangeZSToken() external onlyGovernance timelockConditionsMet(4) {
zsTokenAddress = _timelock_address;
}
// --------------------
// Change the trading conditions used by the strategy
// --------------------
function startChangeTradingConditions(uint256 _pTradeTrigger, uint256 _pSellPercent, uint256 _mSellAmount, uint256 _minSplit, uint256 _maxStipend, uint256 _pMaxStipend, uint256 _pSlip) external onlyGovernance {
// Changes a lot of trading parameters in one call
require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pMaxStipend <= 100000 && _pSlip <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 5;
_timelock_data[0] = _pTradeTrigger;
_timelock_data[1] = _pSellPercent;
_timelock_data[2] = _minSplit;
_timelock_data[3] = _maxStipend;
_timelock_data[4] = _pMaxStipend;
_timelock_data[5] = _pSlip;
_timelock_data[6] = _mSellAmount;
}
function finishChangeTradingConditions() external onlyGovernance timelockConditionsMet(5) {
percentTradeTrigger = _timelock_data[0];
maxPercentSell = _timelock_data[1];
minTradeSplit = _timelock_data[2];
gasStipend = _timelock_data[3];
maxPercentStipend = _timelock_data[4];
maxSlippage = _timelock_data[5];
maxAmountSell = _timelock_data[6];
}
// --------------------
// Change the strategy allocations between the parties
// --------------------
function startChangeStrategyAllocations(uint256 _pDepositors, uint256 _pExecutor, uint256 _pStakers, uint256 _maxPool) external onlyGovernance {
// Changes strategy allocations in one call
require(_pDepositors <= 100000 && _pExecutor <= 100000 && _pStakers <= 100000,"Percent cannot be greater than 100%");
_timelockStart = now;
_timelockType = 6;
_timelock_data[0] = _pDepositors;
_timelock_data[1] = _pExecutor;
_timelock_data[2] = _pStakers;
_timelock_data[3] = _maxPool;
}
function finishChangeStrategyAllocations() external onlyGovernance timelockConditionsMet(6) {
percentDepositor = _timelock_data[0];
percentExecutor = _timelock_data[1];
percentStakers = _timelock_data[2];
maxPoolSize = _timelock_data[3];
}
// --------------------
}
|
Function designed to promote trading with incentive. Users get 20% of WETH from profitable trades
|
function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade, bool doFlash) external {
require(now.sub(lastTradeTime) > _minSecSinceLastTrade, "The last trade was too recent");
require(_msgSender() == tx.origin, "Contracts cannot interact with this function");
checkAndSwapTokens(_executor, doFlash);
lastActionBalance = balance();
}
| 10,912,233
|
contract Scrypt {
/// Verifies a salsa step in the first half of the scrypt computation.
function verifyFirstHalf(uint[4] input, uint[4] output) constant returns (bool) {
var (a, b, c, d) = Salsa8.round(input[0], input[1], input[2], input[3]);
return (a == output[0] && b == output[1] && c == output[2] && d == output[3]);
}
/// Verifies a salsa step in the second half of the scrypt computation.
function verifySecondHalf(uint[4] input, uint[4] vinput, uint[4] output) constant returns (bool) {
input[0] ^= vinput[0];
input[1] ^= vinput[1];
input[2] ^= vinput[2];
input[3] ^= vinput[3];
return verifyFirstHalf(input, output);
}
event Convicted();
uint[] queries;
/// Challenger queries claimant for the inputs and outputs in step `_step`.
function query(uint _step) {
if (queries.length > commits.length) throw;
queries.push(_step);
}
uint[4][3][] commits;
/// Claimant responds to challenge, commiting to a value.
function respond(uint[4][3] _response) {
if (commits.length >= queries.length) throw;
uint step = queries[queries.length - 1];
if (step < 1024 && !verifyFirstHalf(_response[0], _response[1])) {
Convicted();
return;
} else if (step >= 1024 && !verifySecondHalf(_response[0], _response[1], _response[2])) {
Convicted();
return;
}
commits.push(_response);
}
/// Invalid claims in direct computational steps are checked before
/// storing the response. Another source of inconsistency could be
/// different values at wires.
function convictFirstHalfWire(uint q1, uint q2) {
var step1 = queries[q1];
var step2 = queries[q2];
if (step2 != step1 + 1 || step1 > 1024) throw;
if (commits[q1][1][0] != commits[q2][0][0] ||
commits[q1][1][1] != commits[q2][0][1] ||
commits[q1][1][2] != commits[q2][0][2] ||
commits[q1][1][3] != commits[q2][0][3]
)
Convicted();
}
//@TODO convictSecondHalfWire
//@TODO convictCrossWire: check that in step k with (input, vinput),
// we have vinput = input_step[input % 32]
}
library Salsa8 {
uint constant m0 = 0x100000000000000000000000000000000000000000000000000000000;
uint constant m1 = 0x1000000000000000000000000000000000000000000000000;
uint constant m2 = 0x10000000000000000000000000000000000000000;
uint constant m3 = 0x100000000000000000000000000000000;
uint constant m4 = 0x1000000000000000000000000;
uint constant m5 = 0x10000000000000000;
uint constant m6 = 0x100000000;
uint constant m7 = 0x1;
function quarter(uint32 y0, uint32 y1, uint32 y2, uint32 y3)
internal returns (uint32, uint32, uint32, uint32)
{
uint32 t;
t = y0 + y3;
y1 = y1 ^ ((t * 2**7) | (t / 2**(32-7)));
t = y1 + y0;
y2 = y2 ^ ((t * 2**9) | (t / 2**(32-9)));
t = y2 + y1;
y3 = y3 ^ ((t * 2**13) | (t / 2**(32-13)));
t = y3 + y2;
y0 = y0 ^ ((t * 2**18) | (t / 2**(32-18)));
return (y0, y1, y2, y3);
}
function get(uint data, uint word) internal returns (uint32 x)
{
return uint32(data / 2**(256 - word * 32 - 32));
}
function put(uint x, uint word) internal returns (uint) {
return x * 2**(256 - word * 32 - 32);
}
function rowround(uint first, uint second) internal returns (uint f, uint s)
{
var (a,b,c,d) = quarter(uint32(first / m0), uint32(first / m1), uint32(first / m2), uint32(first / m3));
f = (((((uint(a) * 2**32) | uint(b)) * 2 ** 32) | uint(c)) * 2**32) | uint(d);
(b,c,d,a) = quarter(uint32(first / m5), uint32(first / m6), uint32(first / m7), uint32(first / m4));
f = (((((((f * 2**32) | uint(a)) * 2**32) | uint(b)) * 2 ** 32) | uint(c)) * 2**32) | uint(d);
(c,d,a,b) = quarter(uint32(second / m2), uint32(second / m3), uint32(second / m0), uint32(second / m1));
s = (((((uint(a) * 2**32) | uint(b)) * 2 ** 32) | uint(c)) * 2**32) | uint(d);
(d,a,b,c) = quarter(uint32(second / m7), uint32(second / m4), uint32(second / m5), uint32(second / m6));
s = (((((((s * 2**32) | uint(a)) * 2**32) | uint(b)) * 2 ** 32) | uint(c)) * 2**32) | uint(d);
}
function columnround(uint first, uint second) internal returns (uint f, uint s)
{
var (a,b,c,d) = quarter(uint32(first / m0), uint32(first / m4), uint32(second / m0), uint32(second / m4));
f = (uint(a) * m0) | (uint(b) * m4);
s = (uint(c) * m0) | (uint(d) * m4);
(a,b,c,d) = quarter(uint32(first / m5), uint32(second / m1), uint32(second / m5), uint32(first / m1));
f |= (uint(a) * m5) | (uint(d) * m1);
s |= (uint(b) * m1) | (uint(c) * m5);
(a,b,c,d) = quarter(uint32(second / m2), uint32(second / m6), uint32(first / m2), uint32(first / m6));
f |= (uint(c) * m2) | (uint(d) * m6);
s |= (uint(a) * m2) | (uint(b) * m6);
(a,b,c,d) = quarter(uint32(second / m7), uint32(first / m3), uint32(first / m7), uint32(second / m3));
f |= (uint(b) * m3) | (uint(c) * m7);
s |= (uint(a) * m7) | (uint(d) * m3);
}
function salsa20_8(uint _first, uint _second) internal returns (uint rfirst, uint rsecond) {
uint first = _first;
uint second = _second;
for (uint i = 0; i < 8; i += 2)
{
(first, second) = columnround(first, second);
(first, second) = rowround(first, second);
}
for (i = 0; i < 8; i++)
{
rfirst |= put(get(_first, i) + get(first, i), i);
rsecond |= put(get(_second, i) + get(second, i), i);
}
}
function round(uint _a, uint _b, uint _c, uint _d) constant returns (uint, uint, uint, uint) {
(_a, _b) = salsa20_8(_a ^ _c, _b ^ _d);
(_c, _d) = salsa20_8(_a ^ _c, _b ^ _d);
return (_a, _b, _c, _d);
}
}
|
Verifies a salsa step in the first half of the scrypt computation.
|
function verifyFirstHalf(uint[4] input, uint[4] output) constant returns (bool) {
var (a, b, c, d) = Salsa8.round(input[0], input[1], input[2], input[3]);
return (a == output[0] && b == output[1] && c == output[2] && d == output[3]);
}
| 5,517,823
|
./partial_match/1/0x5f1F5b4BFAa78E4e1F8063b71E96656bAF965Db7/sources/KongEntropyDirectMint.sol
|
Interface for Register contract./
|
interface RegisterInterface {
function getKongAmount(bytes32 primaryPublicKeyHash) external view returns (uint);
function getTertiaryKeyHash(bytes32 primaryPublicKeyHash) external view returns (bytes32);
function mintKong(bytes32 primaryPublicKeyHash, address recipient) external;
}
| 15,523,967
|
./full_match/5/0x04996Bf06a0654C8299041086115fbB0B836683f/sources/project_/contracts/HuxleyComicsIssue4.sol
|
Updates value of 'canPublicMint' _value New value of 'canPublicMint'/
|
function setCanPublicMint(bool _value) external onlyOwner {
canPublicMint = _value;
}
| 1,946,795
|
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/ERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155Receiver.sol";
import "@openzeppelin/contracts/utils/Pausable.sol";
import "./interfaces/IVoucherKernel.sol";
import "./interfaces/IVoucherSets.sol";
import "./interfaces/ICashier.sol";
//preparing for ERC-1066, ERC-1444, EIP-838
/**
* @title Voucher sets implemented as ERC-1155
*/
contract VoucherSets is IVoucherSets, ERC1155, Ownable, Pausable {
address private voucherKernelAddress; //address of the VoucherKernel contract
address private cashierAddress; //address of the Cashier contract
string private contractUri;
event LogVoucherKernelSet(address _newVoucherKernel, address _triggeredBy);
event LogCashierSet(address _newCashier, address _triggeredBy);
event LogContractUriSet(string _contractUri, address _triggeredBy);
modifier onlyFromVoucherKernel() {
require(msg.sender == voucherKernelAddress, "UNAUTHORIZED_VK");
_;
}
modifier notZeroAddress(address _address) {
require(_address != address(0), "ZERO_ADDRESS");
_;
}
/**
* @notice Construct and initialze the contract.
* @param _uri metadata uri
* @param _cashierAddress address of the associated Cashier contract
* @param _voucherKernelAddress address of the associated Voucher Kernel contract
*/
constructor(string memory _uri, address _cashierAddress, address _voucherKernelAddress) ERC1155(_uri) notZeroAddress(_cashierAddress) notZeroAddress(_voucherKernelAddress) {
cashierAddress = _cashierAddress;
voucherKernelAddress = _voucherKernelAddress;
}
/**
* @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency.
* Only BR contract is in control of this function.
*/
function pause() external override onlyOwner {
_pause();
}
/**
* @notice Unpause the process of interaction with voucherID's (ERC-721).
* Only BR contract is in control of this function.
*/
function unpause() external override onlyOwner {
_unpause();
}
/**
* @notice Transfers amount of _tokenId from-to addresses with safety call.
* If _to is a smart contract, will call onERC1155Received
* @dev ERC-1155
* @param _from Source address
* @param _to Destination address
* @param _tokenId ID of the token
* @param _value Transfer amount
* @param _data Additional data forwarded to onERC1155Received if _to is a contract
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
uint256 _value,
bytes calldata _data
)
public
override (ERC1155, IERC1155)
{
require(balanceOf(_from, _tokenId) == _value, "IQ"); //invalid qty
super.safeTransferFrom(_from, _to, _tokenId, _value, _data);
ICashier(cashierAddress).onVoucherSetTransfer(
_from,
_to,
_tokenId,
_value
);
}
/**
@notice Transfers amount of _tokenId from-to addresses with safety call.
If _to is a smart contract, will call onERC1155BatchReceived
@dev ERC-1155
@param _from Source address
@param _to Destination address
@param _tokenIds array of token IDs
@param _values array of transfer amounts
@param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract
*/
function safeBatchTransferFrom(
address _from,
address _to,
uint256[] calldata _tokenIds,
uint256[] calldata _values,
bytes calldata _data
)
public
override (ERC1155, IERC1155)
{
//Thes checks need to be called first. Code is duplicated, but super.safeBatchTransferFrom
//must be called at the end because otherwise the balance check in the loop will always fail
require(_tokenIds.length == _values.length, "ERC1155: ids and amounts length mismatch");
require(_to != address(0), "ERC1155: transfer to the zero address");
require(
_from == _msgSender() || isApprovedForAll(_from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
//This is inefficient because it repeats the loop in ERC1155.safeBatchTransferFrom. However,
//there is no other good way to call the Boson Protocol cashier contract inside the loop.
//Doing a full override by copying the ERC1155 code doesn't work because the _balances mapping
//is private instead of internal and can't be accesssed from this child contract
for (uint256 i = 0; i < _tokenIds.length; ++i) {
uint256 tokenId = _tokenIds[i];
uint256 value = _values[i];
//A voucher set's quantity cannot be partionally transferred. It's all or nothing
require(balanceOf(_from, tokenId) == value, "IQ"); //invalid qty
ICashier(cashierAddress).onVoucherSetTransfer(
_from,
_to,
tokenId,
value
);
}
super.safeBatchTransferFrom(_from, _to, _tokenIds, _values, _data);
}
// // // // // // // //
// STANDARD - UTILS
// // // // // // // //
/**
* @notice Mint an amount of a desired token
* Currently no restrictions as to who is allowed to mint - so, it is public.
* @dev ERC-1155
* @param _to owner of the minted token
* @param _tokenId ID of the token to be minted
* @param _value Amount of the token to be minted
* @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract
*/
function mint(
address _to,
uint256 _tokenId,
uint256 _value,
bytes memory _data
) external override onlyFromVoucherKernel {
_mint(_to, _tokenId, _value, _data);
}
/**
* @notice Batch minting of tokens
* Currently no restrictions as to who is allowed to mint - so, it is public.
* @dev ERC-1155
* @param _to The address that will own the minted token
* @param _tokenIds IDs of the tokens to be minted
* @param _values Amounts of the tokens to be minted
* @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract
*/
function mintBatch(
address _to,
uint256[] memory _tokenIds,
uint256[] memory _values,
bytes memory _data
) external onlyFromVoucherKernel {
//require approved minter
_mintBatch(_to, _tokenIds, _values, _data);
}
/**
* @notice Burn an amount of tokens with the given ID
* @dev ERC-1155
* @param _account Account which owns the token
* @param _tokenId ID of the token
* @param _value Amount of the token
*/
function burn(
address _account,
uint256 _tokenId,
uint256 _value
) external override onlyFromVoucherKernel {
_burn(_account, _tokenId, _value);
}
/**
* @notice Batch burn an amounts of tokens
* @dev ERC-1155
* @param _account Account which owns the token
* @param _tokenIds IDs of the tokens
* @param _values Amounts of the tokens
*/
function burnBatch(
address _account,
uint256[] memory _tokenIds,
uint256[] memory _values
) external onlyFromVoucherKernel {
_burnBatch(_account, _tokenIds, _values);
}
// // // // // // // //
// METADATA EXTENSIONS
// // // // // // // //
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
* @param _newUri New uri to be used
*/
function setUri(string memory _newUri) external onlyOwner {
_setURI(_newUri);
}
/**
* @notice Setting a contractURI for OpenSea collections integration.
* @param _contractUri The contract URI to be used
*/
function setContractUri(string memory _contractUri) external onlyOwner {
require(bytes(_contractUri).length != 0, "INVALID_VALUE");
contractUri = _contractUri;
emit LogContractUriSet(_contractUri, msg.sender);
}
// // // // // // // //
// UTILS
// // // // // // // //
/**
* @notice Set the address of the VoucherKernel contract
* @param _voucherKernelAddress The address of the Voucher Kernel contract
*/
function setVoucherKernelAddress(address _voucherKernelAddress)
external
override
onlyOwner
notZeroAddress(_voucherKernelAddress)
whenPaused
{
voucherKernelAddress = _voucherKernelAddress;
emit LogVoucherKernelSet(_voucherKernelAddress, msg.sender);
}
/**
* @notice Set the address of the cashier contract
* @param _cashierAddress The Cashier contract
*/
function setCashierAddress(address _cashierAddress)
external
override
onlyOwner
notZeroAddress(_cashierAddress)
whenPaused
{
cashierAddress = _cashierAddress;
emit LogCashierSet(_cashierAddress, msg.sender);
}
/**
* @notice Get the address of Voucher Kernel contract
* @return Address of Voucher Kernel contract
*/
function getVoucherKernelAddress()
external
view
override
returns (address)
{
return voucherKernelAddress;
}
/**
* @notice Get the address of Cashier contract
* @return Address of Cashier address
*/
function getCashierAddress()
external
view
override
returns (address)
{
return cashierAddress;
}
/**
* @notice Get the contractURI for Opensea collections integration
* @return Contract URI
*/
function contractURI() public view returns (string memory) {
return contractUri;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC1155.sol";
import "./IERC1155MetadataURI.sol";
import "./IERC1155Receiver.sol";
import "../../utils/Context.sol";
import "../../introspection/ERC165.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
*
* @dev Implementation of the basic standard multi-token.
* See https://eips.ethereum.org/EIPS/eip-1155
* Originally based on code by Enjin: https://github.com/enjin/erc-1155
*
* _Available since v3.1._
*/
contract ERC1155 is Context, ERC165, IERC1155, IERC1155MetadataURI {
using SafeMath for uint256;
using Address for address;
// Mapping from token ID to account balances
mapping (uint256 => mapping(address => uint256)) private _balances;
// Mapping from account to operator approvals
mapping (address => mapping(address => bool)) private _operatorApprovals;
// Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json
string private _uri;
/*
* bytes4(keccak256('balanceOf(address,uint256)')) == 0x00fdd58e
* bytes4(keccak256('balanceOfBatch(address[],uint256[])')) == 0x4e1273f4
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('safeTransferFrom(address,address,uint256,uint256,bytes)')) == 0xf242432a
* bytes4(keccak256('safeBatchTransferFrom(address,address,uint256[],uint256[],bytes)')) == 0x2eb2c2d6
*
* => 0x00fdd58e ^ 0x4e1273f4 ^ 0xa22cb465 ^
* 0xe985e9c5 ^ 0xf242432a ^ 0x2eb2c2d6 == 0xd9b67a26
*/
bytes4 private constant _INTERFACE_ID_ERC1155 = 0xd9b67a26;
/*
* bytes4(keccak256('uri(uint256)')) == 0x0e89341c
*/
bytes4 private constant _INTERFACE_ID_ERC1155_METADATA_URI = 0x0e89341c;
/**
* @dev See {_setURI}.
*/
constructor (string memory uri_) {
_setURI(uri_);
// register the supported interfaces to conform to ERC1155 via ERC165
_registerInterface(_INTERFACE_ID_ERC1155);
// register the supported interfaces to conform to ERC1155MetadataURI via ERC165
_registerInterface(_INTERFACE_ID_ERC1155_METADATA_URI);
}
/**
* @dev See {IERC1155MetadataURI-uri}.
*
* This implementation returns the same URI for *all* token types. It relies
* on the token type ID substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* Clients calling this function must replace the `\{id\}` substring with the
* actual token type ID.
*/
function uri(uint256) external view virtual override returns (string memory) {
return _uri;
}
/**
* @dev See {IERC1155-balanceOf}.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) public view virtual override returns (uint256) {
require(account != address(0), "ERC1155: balance query for the zero address");
return _balances[id][account];
}
/**
* @dev See {IERC1155-balanceOfBatch}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(
address[] memory accounts,
uint256[] memory ids
)
public
view
virtual
override
returns (uint256[] memory)
{
require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch");
uint256[] memory batchBalances = new uint256[](accounts.length);
for (uint256 i = 0; i < accounts.length; ++i) {
batchBalances[i] = balanceOf(accounts[i], ids[i]);
}
return batchBalances;
}
/**
* @dev See {IERC1155-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(_msgSender() != operator, "ERC1155: setting approval status for self");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC1155-isApprovedForAll}.
*/
function isApprovedForAll(address account, address operator) public view virtual override returns (bool) {
return _operatorApprovals[account][operator];
}
/**
* @dev See {IERC1155-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
public
virtual
override
{
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][from] = _balances[id][from].sub(amount, "ERC1155: insufficient balance for transfer");
_balances[id][to] = _balances[id][to].add(amount);
emit TransferSingle(operator, from, to, id, amount);
_doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data);
}
/**
* @dev See {IERC1155-safeBatchTransferFrom}.
*/
function safeBatchTransferFrom(
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
public
virtual
override
{
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
require(to != address(0), "ERC1155: transfer to the zero address");
require(
from == _msgSender() || isApprovedForAll(from, _msgSender()),
"ERC1155: transfer caller is not owner nor approved"
);
address operator = _msgSender();
_beforeTokenTransfer(operator, from, to, ids, amounts, data);
for (uint256 i = 0; i < ids.length; ++i) {
uint256 id = ids[i];
uint256 amount = amounts[i];
_balances[id][from] = _balances[id][from].sub(
amount,
"ERC1155: insufficient balance for transfer"
);
_balances[id][to] = _balances[id][to].add(amount);
}
emit TransferBatch(operator, from, to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data);
}
/**
* @dev Sets a new URI for all token types, by relying on the token type ID
* substitution mechanism
* https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP].
*
* By this mechanism, any occurrence of the `\{id\}` substring in either the
* URI or any of the amounts in the JSON file at said URI will be replaced by
* clients with the token type ID.
*
* For example, the `https://token-cdn-domain/\{id\}.json` URI would be
* interpreted by clients as
* `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json`
* for token type ID 0x4cce0.
*
* See {uri}.
*
* Because these URIs cannot be meaningfully represented by the {URI} event,
* this function emits no events.
*/
function _setURI(string memory newuri) internal virtual {
_uri = newuri;
}
/**
* @dev Creates `amount` tokens of token type `id`, and assigns them to `account`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - If `account` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function _mint(address account, uint256 id, uint256 amount, bytes memory data) internal virtual {
require(account != address(0), "ERC1155: mint to the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), account, _asSingletonArray(id), _asSingletonArray(amount), data);
_balances[id][account] = _balances[id][account].add(amount);
emit TransferSingle(operator, address(0), account, id, amount);
_doSafeTransferAcceptanceCheck(operator, address(0), account, id, amount, data);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function _mintBatch(address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data) internal virtual {
require(to != address(0), "ERC1155: mint to the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, address(0), to, ids, amounts, data);
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][to] = amounts[i].add(_balances[ids[i]][to]);
}
emit TransferBatch(operator, address(0), to, ids, amounts);
_doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data);
}
/**
* @dev Destroys `amount` tokens of token type `id` from `account`
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens of token type `id`.
*/
function _burn(address account, uint256 id, uint256 amount) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), _asSingletonArray(id), _asSingletonArray(amount), "");
_balances[id][account] = _balances[id][account].sub(
amount,
"ERC1155: burn amount exceeds balance"
);
emit TransferSingle(operator, account, address(0), id, amount);
}
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
*/
function _burnBatch(address account, uint256[] memory ids, uint256[] memory amounts) internal virtual {
require(account != address(0), "ERC1155: burn from the zero address");
require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch");
address operator = _msgSender();
_beforeTokenTransfer(operator, account, address(0), ids, amounts, "");
for (uint i = 0; i < ids.length; i++) {
_balances[ids[i]][account] = _balances[ids[i]][account].sub(
amounts[i],
"ERC1155: burn amount exceeds balance"
);
}
emit TransferBatch(operator, account, address(0), ids, amounts);
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning, as well as batched variants.
*
* The same hook is called on both single and batched variants. For single
* transfers, the length of the `id` and `amount` arrays will be 1.
*
* Calling conditions (for each `id` and `amount` pair):
*
* - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* of token type `id` will be transferred to `to`.
* - When `from` is zero, `amount` tokens of token type `id` will be minted
* for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens of token type `id`
* will be burned.
* - `from` and `to` are never both zero.
* - `ids` and `amounts` have the same, non-zero length.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
internal
virtual
{ }
function _doSafeTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256 id,
uint256 amount,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155Received.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _doSafeBatchTransferAcceptanceCheck(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
)
private
{
if (to.isContract()) {
try IERC1155Receiver(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns (bytes4 response) {
if (response != IERC1155Receiver(to).onERC1155BatchReceived.selector) {
revert("ERC1155: ERC1155Receiver rejected tokens");
}
} catch Error(string memory reason) {
revert(reason);
} catch {
revert("ERC1155: transfer to non ERC1155Receiver implementer");
}
}
}
function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) {
uint256[] memory array = new uint256[](1);
array[0] = element;
return array;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../introspection/IERC165.sol";
/**
* _Available since v3.1._
*/
interface IERC1155Receiver is IERC165 {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
To accept the transfer, this must return
`bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))`
(i.e. 0xf23a6e61, or its own function selector).
@param operator The address which initiated the transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param id The ID of the token being transferred
@param value The amount of tokens being transferred
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` if transfer is allowed
*/
function onERC1155Received(
address operator,
address from,
uint256 id,
uint256 value,
bytes calldata data
)
external
returns(bytes4);
/**
@dev Handles the receipt of a multiple ERC1155 token types. This function
is called at the end of a `safeBatchTransferFrom` after the balances have
been updated. To accept the transfer(s), this must return
`bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))`
(i.e. 0xbc197c81, or its own function selector).
@param operator The address which initiated the batch transfer (i.e. msg.sender)
@param from The address which previously owned the token
@param ids An array containing ids of each token being transferred (order and length must match values array)
@param values An array containing amounts of each token being transferred (order and length must match ids array)
@param data Additional data with no specified format
@return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed
*/
function onERC1155BatchReceived(
address operator,
address from,
uint256[] calldata ids,
uint256[] calldata values,
bytes calldata data
)
external
returns(bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./Context.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () {
_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: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "./../UsingHelpers.sol";
interface IVoucherKernel {
/**
* @notice Pause the process of interaction with voucherID's (ERC-721), in case of emergency.
* Only Cashier contract is in control of this function.
*/
function pause() external;
/**
* @notice Unpause the process of interaction with voucherID's (ERC-721).
* Only Cashier contract is in control of this function.
*/
function unpause() external;
/**
* @notice Creating a new promise for goods or services.
* Can be reused, e.g. for making different batches of these (but not in prototype).
* @param _seller seller of the promise
* @param _validFrom Start of valid period
* @param _validTo End of valid period
* @param _price Price (payment amount)
* @param _depositSe Seller's deposit
* @param _depositBu Buyer's deposit
*/
function createTokenSupplyId(
address _seller,
uint256 _validFrom,
uint256 _validTo,
uint256 _price,
uint256 _depositSe,
uint256 _depositBu,
uint256 _quantity
) external returns (uint256);
/**
* @notice Creates a Payment method struct recording the details on how the seller requires to receive Price and Deposits for a certain Voucher Set.
* @param _tokenIdSupply _tokenIdSupply of the voucher set this is related to
* @param _paymentMethod might be ETHETH, ETHTKN, TKNETH or TKNTKN
* @param _tokenPrice token address which will hold the funds for the price of the voucher
* @param _tokenDeposits token address which will hold the funds for the deposits of the voucher
*/
function createPaymentMethod(
uint256 _tokenIdSupply,
PaymentMethod _paymentMethod,
address _tokenPrice,
address _tokenDeposits
) external;
/**
* @notice Mark voucher token that the payment was released
* @param _tokenIdVoucher ID of the voucher token
*/
function setPaymentReleased(uint256 _tokenIdVoucher) external;
/**
* @notice Mark voucher token that the deposits were released
* @param _tokenIdVoucher ID of the voucher token
*/
function setDepositsReleased(uint256 _tokenIdVoucher) external;
/**
* @notice Redemption of the vouchers promise
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher
*/
function redeem(uint256 _tokenIdVoucher, address _messageSender) external;
/**
* @notice Refunding a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher
*/
function refund(uint256 _tokenIdVoucher, address _messageSender) external;
/**
* @notice Issue a complain for a voucher
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher
*/
function complain(uint256 _tokenIdVoucher, address _messageSender) external;
/**
* @notice Cancel/Fault transaction by the Seller, admitting to a fault or backing out of the deal
* @param _tokenIdVoucher ID of the voucher
* @param _messageSender owner of the voucher set (seller)
*/
function cancelOrFault(uint256 _tokenIdVoucher, address _messageSender)
external;
/**
* @notice Cancel/Fault transaction by the Seller, cancelling the remaining uncommitted voucher set so that seller prevents buyers from committing to vouchers for items no longer in exchange.
* @param _tokenIdSupply ID of the voucher
* @param _issuer owner of the voucher
*/
function cancelOrFaultVoucherSet(uint256 _tokenIdSupply, address _issuer)
external
returns (uint256);
/**
* @notice Fill Voucher Order, iff funds paid, then extract & mint NFT to the voucher holder
* @param _tokenIdSupply ID of the supply token (ERC-1155)
* @param _issuer Address of the token's issuer
* @param _holder Address of the recipient of the voucher (ERC-721)
* @param _paymentMethod method being used for that particular order that needs to be fulfilled
*/
function fillOrder(
uint256 _tokenIdSupply,
address _issuer,
address _holder,
PaymentMethod _paymentMethod
) external;
/**
* @notice Mark voucher token as expired
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerExpiration(uint256 _tokenIdVoucher) external;
/**
* @notice Mark voucher token to the final status
* @param _tokenIdVoucher ID of the voucher token
*/
function triggerFinalizeVoucher(uint256 _tokenIdVoucher) external;
/**
* @notice Set the address of the new holder of a _tokenIdSupply on transfer
* @param _tokenIdSupply _tokenIdSupply which will be transferred
* @param _newSeller new holder of the supply
*/
function setSupplyHolderOnTransfer(
uint256 _tokenIdSupply,
address _newSeller
) external;
/**
* @notice Set the general cancelOrFault period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _cancelFaultPeriod the new value for cancelOrFault period (in number of seconds)
*/
function setCancelFaultPeriod(uint256 _cancelFaultPeriod) external;
/**
* @notice Set the address of the Boson Router contract
* @param _bosonRouterAddress The address of the BR contract
*/
function setBosonRouterAddress(address _bosonRouterAddress) external;
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress) external;
/**
* @notice Set the address of the Vouchers token contract, an ERC721 contract
* @param _voucherTokenAddress The address of the Vouchers token contract
*/
function setVoucherTokenAddress(address _voucherTokenAddress) external;
/**
* @notice Set the address of the Voucher Sets token contract, an ERC1155 contract
* @param _voucherSetTokenAddress The address of the Voucher Sets token contract
*/
function setVoucherSetTokenAddress(address _voucherSetTokenAddress)
external;
/**
* @notice Set the general complain period, should be used sparingly as it has significant consequences. Here done simply for demo purposes.
* @param _complainPeriod the new value for complain period (in number of seconds)
*/
function setComplainPeriod(uint256 _complainPeriod) external;
/**
* @notice Get the promise ID at specific index
* @param _idx Index in the array of promise keys
* @return Promise ID
*/
function getPromiseKey(uint256 _idx) external view returns (bytes32);
/**
* @notice Get the address of the token where the price for the supply is held
* @param _tokenIdSupply ID of the voucher token
* @return Address of the token
*/
function getVoucherPriceToken(uint256 _tokenIdSupply)
external
view
returns (address);
/**
* @notice Get the address of the token where the deposits for the supply are held
* @param _tokenIdSupply ID of the voucher token
* @return Address of the token
*/
function getVoucherDepositToken(uint256 _tokenIdSupply)
external
view
returns (address);
/**
* @notice Get Buyer costs required to make an order for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Buyer's deposit)
*/
function getBuyerOrderCosts(uint256 _tokenIdSupply)
external
view
returns (uint256, uint256);
/**
* @notice Get Seller deposit
* @param _tokenIdSupply ID of the supply token
* @return returns sellers deposit
*/
function getSellerDeposit(uint256 _tokenIdSupply)
external
view
returns (uint256);
/**
* @notice Get the promise ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the promise
*/
function getIdSupplyFromVoucher(uint256 _tokenIdVoucher)
external
pure
returns (uint256);
/**
* @notice Get the promise ID from a voucher token
* @param _tokenIdVoucher ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromVoucherId(uint256 _tokenIdVoucher)
external
view
returns (bytes32);
/**
* @notice Get all necessary funds for a supply token
* @param _tokenIdSupply ID of the supply token
* @return returns a tuple (Payment amount, Seller's deposit, Buyer's deposit)
*/
function getOrderCosts(uint256 _tokenIdSupply)
external
view
returns (
uint256,
uint256,
uint256
);
/**
* @notice Get the remaining quantity left in supply of tokens (e.g ERC-721 left in ERC-1155) of an account
* @param _tokenSupplyId Token supply ID
* @param _owner holder of the Token Supply
* @return remaining quantity
*/
function getRemQtyForSupply(uint256 _tokenSupplyId, address _owner)
external
view
returns (uint256);
/**
* @notice Get the payment method for a particular _tokenIdSupply
* @param _tokenIdSupply ID of the voucher supply token
* @return payment method
*/
function getVoucherPaymentMethod(uint256 _tokenIdSupply)
external
view
returns (PaymentMethod);
/**
* @notice Get the current status of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Status of the voucher (via enum)
*/
function getVoucherStatus(uint256 _tokenIdVoucher)
external
view
returns (
uint8,
bool,
bool,
uint256,
uint256
);
/**
* @notice Get the holder of a supply
* @param _tokenIdSupply _tokenIdSupply ID of the order (aka VoucherSet) which is mapped to the corresponding Promise.
* @return Address of the holder
*/
function getSupplyHolder(uint256 _tokenIdSupply)
external
view
returns (address);
/**
* @notice Get the holder of a voucher
* @param _tokenIdVoucher ID of the voucher token
* @return Address of the holder
*/
function getVoucherHolder(uint256 _tokenIdVoucher)
external
view
returns (address);
/**
* @notice Checks whether a voucher is in valid period for redemption (between start date and end date)
* @param _tokenIdVoucher ID of the voucher token
*/
function isInValidityPeriod(uint256 _tokenIdVoucher)
external
view
returns (bool);
/**
* @notice Checks whether a voucher is in valid state to be transferred. If either payments or deposits are released, voucher could not be transferred
* @param _tokenIdVoucher ID of the voucher token
*/
function isVoucherTransferable(uint256 _tokenIdVoucher)
external
view
returns (bool);
/**
* @notice Get address of the Boson Router contract to which this contract points
* @return Address of the Boson Router contract
*/
function getBosonRouterAddress() external view returns (address);
/**
* @notice Get address of the Cashier contract to which this contract points
* @return Address of the Cashier contract
*/
function getCashierAddress() external view returns (address);
/**
* @notice Get the token nonce for a seller
* @param _seller Address of the seller
* @return The seller's
*/
function getTokenNonce(address _seller) external view returns (uint256);
/**
* @notice Get the current type Id
* @return type Id
*/
function getTypeId() external view returns (uint256);
/**
* @notice Get the complain period
* @return complain period
*/
function getComplainPeriod() external view returns (uint256);
/**
* @notice Get the cancel or fault period
* @return cancel or fault period
*/
function getCancelFaultPeriod() external view returns (uint256);
/**
* @notice Get promise data not retrieved by other accessor functions
* @param _promiseKey ID of the promise
* @return promise data not returned by other accessor methods
*/
function getPromiseData(bytes32 _promiseKey)
external
view
returns (
bytes32,
uint256,
uint256,
uint256,
uint256
);
/**
* @notice Get the promise ID from a voucher set
* @param _tokenIdSupply ID of the voucher token
* @return ID of the promise
*/
function getPromiseIdFromSupplyId(uint256 _tokenIdSupply)
external
view
returns (bytes32);
/**
* @notice Get the address of the Vouchers token contract, an ERC721 contract
* @return Address of Vouchers contract
*/
function getVoucherTokenAddress() external view returns (address);
/**
* @notice Get the address of the VoucherSets token contract, an ERC155 contract
* @return Address of VoucherSets contract
*/
function getVoucherSetTokenAddress() external view returns (address);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155MetadataURI.sol";
interface IVoucherSets is IERC1155, IERC1155MetadataURI {
/**
* @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency.
* All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed.
* There is special function for withdrawing funds if contract is paused.
*/
function pause() external;
/**
* @notice Unpause the Cashier && the Voucher Kernel contracts.
* All functions related to creating new batch, requestVoucher or withdraw will be unpaused.
*/
function unpause() external;
/**
* @notice Mint an amount of a desired token
* Currently no restrictions as to who is allowed to mint - so, it is external.
* @dev ERC-1155
* @param _to owner of the minted token
* @param _tokenId ID of the token to be minted
* @param _value Amount of the token to be minted
* @param _data Additional data forwarded to onERC1155BatchReceived if _to is a contract
*/
function mint(
address _to,
uint256 _tokenId,
uint256 _value,
bytes calldata _data
) external;
/**
* @notice Burn an amount of tokens with the given ID
* @dev ERC-1155
* @param _account Account which owns the token
* @param _tokenId ID of the token
* @param _value Amount of the token
*/
function burn(
address _account,
uint256 _tokenId,
uint256 _value
) external;
/**
* @notice Set the address of the VoucherKernel contract
* @param _voucherKernelAddress The address of the Voucher Kernel contract
*/
function setVoucherKernelAddress(address _voucherKernelAddress) external;
/**
* @notice Set the address of the Cashier contract
* @param _cashierAddress The address of the Cashier contract
*/
function setCashierAddress(address _cashierAddress) external;
/**
* @notice Get the address of Voucher Kernel contract
* @return Address of Voucher Kernel contract
*/
function getVoucherKernelAddress() external view returns (address);
/**
* @notice Get the address of Cashier contract
* @return Address of Cashier address
*/
function getCashierAddress() external view returns (address);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
import "./../UsingHelpers.sol";
interface ICashier {
/**
* @notice Pause the Cashier && the Voucher Kernel contracts in case of emergency.
* All functions related to creating new batch, requestVoucher or withdraw will be paused, hence cannot be executed.
* There is special function for withdrawing funds if contract is paused.
*/
function pause() external;
/**
* @notice Unpause the Cashier && the Voucher Kernel contracts.
* All functions related to creating new batch, requestVoucher or withdraw will be unpaused.
*/
function unpause() external;
function canUnpause() external view returns (bool);
/**
* @notice Trigger withdrawals of what funds are releasable
* The caller of this function triggers transfers to all involved entities (pool, issuer, token holder), also paying for gas.
* @dev This function would be optimized a lot, here verbose for readability.
* @param _tokenIdVoucher ID of a voucher token (ERC-721) to try withdraw funds from
*/
function withdraw(uint256 _tokenIdVoucher) external;
/**
* @notice External function for withdrawing deposits. Caller must be the seller of the goods, otherwise reverts.
* @notice Seller triggers withdrawals of remaining deposits for a given supply, in case the voucher set is no longer in exchange.
* @param _tokenIdSupply an ID of a supply token (ERC-1155) which will be burned and deposits will be returned for
* @param _burnedQty burned quantity that the deposits should be withdrawn for
* @param _messageSender owner of the voucher set
*/
function withdrawDepositsSe(
uint256 _tokenIdSupply,
uint256 _burnedQty,
address payable _messageSender
) external;
/**
* @notice Get the amount in escrow of an address
* @param _account The address of an account to query
* @return The balance in escrow
*/
function getEscrowAmount(address _account) external view returns (uint256);
/**
* @notice Update the amount in escrow of an address with the new value, based on VoucherSet/Voucher interaction
* @param _account The address of an account to query
*/
function addEscrowAmount(address _account) external payable;
/**
* @notice Update the amount in escrowTokens of an address with the new value, based on VoucherSet/Voucher interaction
* @param _token The address of a token to query
* @param _account The address of an account to query
* @param _newAmount New amount to be set
*/
function addEscrowTokensAmount(
address _token,
address _account,
uint256 _newAmount
) external;
/**
* @notice Hook which will be triggered when a _tokenIdVoucher will be transferred. Escrow funds should be allocated to the new owner.
* @param _from prev owner of the _tokenIdVoucher
* @param _to next owner of the _tokenIdVoucher
* @param _tokenIdVoucher _tokenIdVoucher that has been transferred
*/
function onVoucherTransfer(
address _from,
address _to,
uint256 _tokenIdVoucher
) external;
/**
* @notice After the transfer happens the _tokenSupplyId should be updated in the promise. Escrow funds for the deposits (If in ETH) should be allocated to the new owner as well.
* @param _from prev owner of the _tokenSupplyId
* @param _to next owner of the _tokenSupplyId
* @param _tokenSupplyId _tokenSupplyId for transfer
* @param _value qty which has been transferred
*/
function onVoucherSetTransfer(
address _from,
address _to,
uint256 _tokenSupplyId,
uint256 _value
) external;
/**
* @notice Get the address of Voucher Kernel contract
* @return Address of Voucher Kernel contract
*/
function getVoucherKernelAddress() external view returns (address);
/**
* @notice Get the address of Boson Router contract
* @return Address of Boson Router contract
*/
function getBosonRouterAddress() external view returns (address);
/**
* @notice Get the address of the Vouchers contract, an ERC721 contract
* @return Address of Vouchers contract
*/
function getVoucherTokenAddress() external view returns (address);
/**
* @notice Get the address of the VoucherSets token contract, an ERC155 contract
* @return Address of VoucherSets contract
*/
function getVoucherSetTokenAddress() external view returns (address);
/**
* @notice Ensure whether or not contract has been set to disaster state
* @return disasterState
*/
function isDisasterStateSet() external view returns (bool);
/**
* @notice Get the amount in escrow of an address
* @param _token The address of a token to query
* @param _account The address of an account to query
* @return The balance in escrow
*/
function getEscrowTokensAmount(address _token, address _account)
external
view
returns (uint256);
/**
* @notice Set the address of the BR contract
* @param _bosonRouterAddress The address of the Cashier contract
*/
function setBosonRouterAddress(address _bosonRouterAddress) external;
/**
* @notice Set the address of the VoucherKernel contract
* @param _voucherKernelAddress The address of the VoucherKernel contract
*/
function setVoucherKernelAddress(address _voucherKernelAddress) external;
/**
* @notice Set the address of the Vouchers token contract, an ERC721 contract
* @param _voucherTokenAddress The address of the Vouchers token contract
*/
function setVoucherTokenAddress(address _voucherTokenAddress) external;
/**
* @notice Set the address of the Voucher Sets token contract, an ERC1155 contract
* @param _voucherSetTokenAddress The address of the Voucher Sets token contract
*/
function setVoucherSetTokenAddress(address _voucherSetTokenAddress)
external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155 is IERC165 {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC1155.sol";
/**
* @dev Interface of the optional ERC1155MetadataExtension interface, as defined
* in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP].
*
* _Available since v3.1._
*/
interface IERC1155MetadataURI is IERC1155 {
/**
* @dev Returns the URI for token type `id`.
*
* If the `\{id\}` substring is present in the URI, it must be replaced by
* clients with the actual token type ID.
*/
function uri(uint256 id) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165 is IERC165 {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
constructor () {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: LGPL-3.0-or-later
pragma solidity 0.7.6;
// Those are the payment methods we are using throughout the system.
// Depending on how to user choose to interact with it's funds we store the method, so we could distribute its tokens afterwise
enum PaymentMethod {
ETHETH,
ETHTKN,
TKNETH,
TKNTKN
}
enum VoucherState {FINAL, CANCEL_FAULT, COMPLAIN, EXPIRE, REFUND, REDEEM, COMMIT}
/* Status of the voucher in 8 bits:
[6:COMMITTED] [5:REDEEMED] [4:REFUNDED] [3:EXPIRED] [2:COMPLAINED] [1:CANCELORFAULT] [0:FINAL]
*/
uint8 constant ONE = 1;
struct VoucherDetails {
uint256 tokenIdSupply;
uint256 tokenIdVoucher;
address issuer;
address holder;
uint256 price;
uint256 depositSe;
uint256 depositBu;
uint256 price2pool;
uint256 deposit2pool;
uint256 price2issuer;
uint256 deposit2issuer;
uint256 price2holder;
uint256 deposit2holder;
PaymentMethod paymentMethod;
VoucherStatus currStatus;
}
struct VoucherStatus {
uint8 status;
bool isPaymentReleased;
bool isDepositsReleased;
uint256 complainPeriodStart;
uint256 cancelFaultPeriodStart;
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Committed state.
* @param _status current status of a voucher.
*/
function isStateCommitted(uint8 _status) pure returns (bool) {
return _status == determineStatus(0, VoucherState.COMMIT);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in RedemptionSigned state.
* @param _status current status of a voucher.
*/
function isStateRedemptionSigned(uint8 _status)
pure
returns (bool)
{
return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REDEEM);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Refunded state.
* @param _status current status of a voucher.
*/
function isStateRefunded(uint8 _status) pure returns (bool) {
return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.REFUND);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks whether a voucher is in Expired state.
* @param _status current status of a voucher.
*/
function isStateExpired(uint8 _status) pure returns (bool) {
return _status == determineStatus(determineStatus(0, VoucherState.COMMIT), VoucherState.EXPIRE);
}
/**
* @notice Based on its lifecycle, voucher can have many different statuses. Checks the current status a voucher is at.
* @param _status current status of a voucher.
* @param _idx status to compare.
*/
function isStatus(uint8 _status, VoucherState _idx) pure returns (bool) {
return (_status >> uint8(_idx)) & ONE == 1;
}
/**
* @notice Set voucher status.
* @param _status previous status.
* @param _changeIdx next status.
*/
function determineStatus(uint8 _status, VoucherState _changeIdx)
pure
returns (uint8)
{
return _status | (ONE << uint8(_changeIdx));
}
|
Batch minting of tokens Currently no restrictions as to who is allowed to mint - so, it is public. ERC-1155 _to The address that will own the minted token _tokenIds IDs of the tokens to be minted _values Amounts of the tokens to be minted _data Additional data forwarded to onERC1155BatchReceived if _to is a contract/require approved minter
|
function mintBatch(
address _to,
uint256[] memory _tokenIds,
uint256[] memory _values,
bytes memory _data
) external onlyFromVoucherKernel {
_mintBatch(_to, _tokenIds, _values, _data);
}
| 6,202,375
|
pragma solidity ^0.6.6;
abstract contract Context {
function _MSGSENDER800() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA819() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
interface IERC20 {
function TOTALSUPPLY18() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF19(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER188(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE990(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE569(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM677(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER36(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL777(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD452(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB908(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB908(a, b, "SafeMath: subtraction overflow");
}
function SUB908(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function MUL764(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV702(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV702(a, b, "SafeMath: division by zero");
}
function DIV702(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD170(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD170(a, b, "SafeMath: modulo by zero");
}
function MOD170(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT666(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// 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);
}
function SENDVALUE670(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
function FUNCTIONCALL237(address target, bytes memory data) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALL237(target, data, "Address: low-level call failed");
}
function FUNCTIONCALL237(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return _FUNCTIONCALLWITHVALUE645(target, data, 0, errorMessage);
}
function FUNCTIONCALLWITHVALUE846(address target, bytes memory data, uint256 value) internal returns (bytes memory) { //inject NONSTANDARD NAMING
return FUNCTIONCALLWITHVALUE846(target, data, value, "Address: low-level call with value failed");
}
function FUNCTIONCALLWITHVALUE846(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { //inject NONSTANDARD NAMING
require(address(this).balance >= value, "Address: insufficient balance for call");
return _FUNCTIONCALLWITHVALUE645(target, data, value, errorMessage);
}
function _FUNCTIONCALLWITHVALUE645(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { //inject NONSTANDARD NAMING
require(ISCONTRACT666(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
function NAME463() public view returns (string memory) { //inject NONSTANDARD NAMING
return _name;
}
function SYMBOL625() public view returns (string memory) { //inject NONSTANDARD NAMING
return _symbol;
}
function DECIMALS746() public view returns (uint8) { //inject NONSTANDARD NAMING
return _decimals;
}
function TOTALSUPPLY18() public view override returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF19(address account) public view override returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER188(address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER546(_MSGSENDER800(), recipient, amount);
return true;
}
function ALLOWANCE990(address owner, address spender) public view virtual override returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE569(address spender, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_APPROVE756(_MSGSENDER800(), spender, amount);
return true;
}
function TRANSFERFROM677(address sender, address recipient, uint256 amount) public virtual override returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER546(sender, recipient, amount);
_APPROVE756(sender, _MSGSENDER800(), _allowances[sender][_MSGSENDER800()].SUB908(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE156(address spender, uint256 addedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE756(_MSGSENDER800(), spender, _allowances[_MSGSENDER800()][spender].ADD452(addedValue));
return true;
}
function DECREASEALLOWANCE599(address spender, uint256 subtractedValue) public virtual returns (bool) { //inject NONSTANDARD NAMING
_APPROVE756(_MSGSENDER800(), spender, _allowances[_MSGSENDER800()][spender].SUB908(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER546(address sender, address recipient, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_BEFORETOKENTRANSFER598(sender, recipient, amount);
_balances[sender] = _balances[sender].SUB908(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD452(amount);
emit TRANSFER36(sender, recipient, amount);
}
function _MINT47(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_BEFORETOKENTRANSFER598(address(0), account, amount);
_totalSupply = _totalSupply.ADD452(amount);
_balances[account] = _balances[account].ADD452(amount);
emit TRANSFER36(address(0), account, amount);
}
function _BURN695(address account, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_BEFORETOKENTRANSFER598(account, address(0), amount);
_balances[account] = _balances[account].SUB908(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB908(amount);
emit TRANSFER36(account, address(0), amount);
}
function _APPROVE756(address owner, address spender, uint256 amount) internal virtual { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL777(owner, spender, amount);
}
function _SETUPDECIMALS343(uint8 decimals_) internal { //inject NONSTANDARD NAMING
_decimals = decimals_;
}
function _BEFORETOKENTRANSFER598(address from, address to, uint256 amount) internal virtual { } //inject NONSTANDARD NAMING
}
contract ERAF is ERC20 {
constructor ()
ERC20('ERAF Finance', 'ERAF')
public
{
_MINT47(0x5a77bD42971B3399d5f2eaE6505bb36EA6a359F3, 12000 * 10 ** uint(DECIMALS746()));
}
}
|
inject NONSTANDARD NAMING
|
function ADD452(uint256 a, uint256 b) internal pure returns (uint256) {
| 1,825,752
|
pragma solidity ^0.5.17;
import "./Staking/SafeMath96.sol";
import "../openzeppelin/SafeMath.sol";
import "../openzeppelin/SafeERC20.sol";
import "./IFeeSharingProxy.sol";
import "./Staking/IStaking.sol";
contract FeeSharingProxy is SafeMath96, IFeeSharingProxy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
//TODO FEE_WITHDRAWAL_INTERVAL, MAX_CHECKPOINTS
uint256 constant FEE_WITHDRAWAL_INTERVAL = 86400;
uint32 constant MAX_CHECKPOINTS = 100;
IProtocol public protocol;
IStaking public staking;
/// checkpoints by index per pool token address
mapping(address => mapping(uint256 => Checkpoint)) public tokenCheckpoints;
/// @notice The number of checkpoints for each pool token address
mapping(address => uint32) public numTokenCheckpoints;
/// user => token => processed checkpoint
mapping(address => mapping(address => uint32)) public processedCheckpoints;
//token => time
mapping(address => uint256) public lastFeeWithdrawalTime;
//token => amount
//amount of tokens that were transferred, but were not saved in checkpoints
mapping(address => uint96) public unprocessedAmount;
struct Checkpoint {
uint32 blockNumber;
uint32 timestamp;
uint96 totalWeightedStake;
uint96 numTokens;
}
/// @notice An event that emitted when fee get withdrawn
event FeeWithdrawn(address indexed sender, address indexed token, uint256 amount);
/// @notice An event that emitted when tokens transferred
event TokensTransferred(address indexed sender, address indexed token, uint256 amount);
/// @notice An event that emitted when checkpoint added
event CheckpointAdded(address indexed sender, address indexed token, uint256 amount);
/// @notice An event that emitted when user fee get withdrawn
event UserFeeWithdrawn(address indexed sender, address indexed receiver, address indexed token, uint256 amount);
constructor(IProtocol _protocol, IStaking _staking) public {
protocol = _protocol;
staking = _staking;
}
/**
* @notice withdraw fees for the given token: lendingFee + tradingFee + borrowingFee
* @param _token address of the token
* */
function withdrawFees(address _token) public {
require(_token != address(0), "FeeSharingProxy::withdrawFees: invalid address");
address loanPoolToken = protocol.underlyingToLoanPool(_token);
require(loanPoolToken != address(0), "FeeSharingProxy::withdrawFees: loan token not found");
uint256 amount = protocol.withdrawFees(_token, address(this));
require(amount > 0, "FeeSharingProxy::withdrawFees: no tokens to withdraw");
//TODO can be also used - function addLiquidity(IERC20Token _reserveToken, uint256 _amount, uint256 _minReturn)
IERC20(_token).approve(loanPoolToken, amount);
uint256 poolTokenAmount = ILoanToken(loanPoolToken).mint(address(this), amount);
//update unprocessed amount of tokens
uint96 amount96 = safe96(poolTokenAmount, "FeeSharingProxy::withdrawFees: pool token amount exceeds 96 bits");
unprocessedAmount[loanPoolToken] = add96(
unprocessedAmount[loanPoolToken],
amount96,
"FeeSharingProxy::withdrawFees: unprocessedAmount exceeds 96 bits"
);
_addCheckpoint(loanPoolToken);
emit FeeWithdrawn(msg.sender, loanPoolToken, poolTokenAmount);
}
/**
* @notice transfer tokens to this contract
* @dev we just update amount of tokens here and write checkpoint in a separate methods
* in order to prevent adding checkpoints too often
* @param _token address of the token
* @param _amount amount to be transferred
* */
function transferTokens(address _token, uint96 _amount) public {
require(_token != address(0), "FeeSharingProxy::transferTokens: invalid address");
require(_amount > 0, "FeeSharingProxy::transferTokens: invalid amount");
//transfer tokens from msg.sender
bool success = IERC20(_token).transferFrom(address(msg.sender), address(this), _amount);
require(success, "Staking::transferTokens: token transfer failed");
//update unprocessed amount of tokens
unprocessedAmount[_token] = add96(unprocessedAmount[_token], _amount, "FeeSharingProxy::transferTokens: amount exceeds 96 bits");
_addCheckpoint(_token);
emit TokensTransferred(msg.sender, _token, _amount);
}
/**
* @notice adds checkpoint with accumulated amount by function invocation
* @param _token address of the token
* */
function _addCheckpoint(address _token) internal {
if (block.timestamp - lastFeeWithdrawalTime[_token] >= FEE_WITHDRAWAL_INTERVAL) {
lastFeeWithdrawalTime[_token] = block.timestamp;
uint96 amount = unprocessedAmount[_token];
unprocessedAmount[_token] = 0;
//write a regular checkpoint
_writeTokenCheckpoint(_token, amount);
}
}
/**
* @notice withdraw accumulated fee the message sender
* @param _loanPoolToken address of the pool token
* @param _maxCheckpoints maximum number of checkpoints to be processed
* @param _receiver the receiver of tokens or msg.sender
* */
function withdraw(
address _loanPoolToken,
uint32 _maxCheckpoints,
address _receiver
) public {
//prevents processing all checkpoints because of block gas limit
require(_maxCheckpoints > 0, "FeeSharingProxy::withdraw: _maxCheckpoints should be positive");
address user = msg.sender;
if (_receiver == address(0)) {
_receiver = msg.sender;
}
uint256 amount;
uint32 end;
(amount, end) = _getAccumulatedFees(user, _loanPoolToken, _maxCheckpoints);
processedCheckpoints[user][_loanPoolToken] = end;
require(IERC20(_loanPoolToken).transfer(user, amount), "FeeSharingProxy::withdraw: withdrawal failed");
emit UserFeeWithdrawn(msg.sender, _receiver, _loanPoolToken, amount);
}
/**
* @notice returns accumulated fee for the message sender
* @param _user the address of the user or contract
* @param _loanPoolToken address of the pool token
* */
function getAccumulatedFees(address _user, address _loanPoolToken) public view returns (uint256) {
uint256 amount;
(amount, ) = _getAccumulatedFees(_user, _loanPoolToken, 0);
return amount;
}
function _getAccumulatedFees(
address _user,
address _loanPoolToken,
uint32 _maxCheckpoints
) internal view returns (uint256, uint32) {
uint32 start = processedCheckpoints[_user][_loanPoolToken];
uint32 end;
//additional bool param can't be used because of stack too deep error
if (_maxCheckpoints > 0) {
//withdraw -> _getAccumulatedFees
require(start < numTokenCheckpoints[_loanPoolToken], "FeeSharingProxy::withdrawFees: no tokens for a withdrawal");
end = _getEndOfRange(start, _loanPoolToken, _maxCheckpoints);
} else {
//getAccumulatedFees -> _getAccumulatedFees
//don't throw error for getter invocation outside of transaction
if (start >= numTokenCheckpoints[_loanPoolToken]) {
return (0, numTokenCheckpoints[_loanPoolToken]);
}
end = numTokenCheckpoints[_loanPoolToken];
}
uint256 amount = 0;
uint256 cachedLockDate = 0;
uint96 cachedWeightedStake = 0;
for (uint32 i = start; i < end; i++) {
Checkpoint storage checkpoint = tokenCheckpoints[_loanPoolToken][i];
uint256 lockDate = staking.timestampToLockDate(checkpoint.timestamp);
uint96 weightedStake;
if (lockDate == cachedLockDate) {
weightedStake = cachedWeightedStake;
} else {
//We need to use "checkpoint.blockNumber - 1" here to calculate weighted stake
//for the same block like we did for total voting power in _writeTokenCheckpoint
weightedStake = staking.getPriorWeightedStake(_user, checkpoint.blockNumber - 1, checkpoint.timestamp);
cachedWeightedStake = weightedStake;
cachedLockDate = lockDate;
}
uint256 share = uint256(checkpoint.numTokens).mul(weightedStake).div(uint256(checkpoint.totalWeightedStake));
amount = amount.add(share);
}
return (amount, end);
}
function _getEndOfRange(
uint32 start,
address _loanPoolToken,
uint32 _maxCheckpoints
) internal view returns (uint32) {
uint32 nCheckpoints = numTokenCheckpoints[_loanPoolToken];
uint32 end;
if (_maxCheckpoints == 0) {
//all checkpoints will be processed (only for getter outside of a transaction)
end = nCheckpoints;
} else {
if (_maxCheckpoints > MAX_CHECKPOINTS) {
_maxCheckpoints = MAX_CHECKPOINTS;
}
end = safe32(start + _maxCheckpoints, "FeeSharingProxy::withdraw: checkpoint index exceeds 32 bits");
if (end > nCheckpoints) {
end = nCheckpoints;
}
}
//Withdrawal should only be possible for blocks which were already mined.
uint32 lastBlockNumber = tokenCheckpoints[_loanPoolToken][end - 1].blockNumber;
if (block.number == lastBlockNumber) {
end--;
}
return end;
}
function _writeTokenCheckpoint(address _token, uint96 _numTokens) internal {
uint32 blockNumber = safe32(block.number, "FeeSharingProxy::_writeCheckpoint: block number exceeds 32 bits");
uint32 blockTimestamp = safe32(block.timestamp, "FeeSharingProxy::_writeCheckpoint: block timestamp exceeds 32 bits");
uint32 nCheckpoints = numTokenCheckpoints[_token];
uint96 totalWeightedStake = staking.getPriorTotalVotingPower(blockNumber - 1, block.timestamp);
if (nCheckpoints > 0 && tokenCheckpoints[_token][nCheckpoints - 1].blockNumber == blockNumber) {
tokenCheckpoints[_token][nCheckpoints - 1].totalWeightedStake = totalWeightedStake;
tokenCheckpoints[_token][nCheckpoints - 1].numTokens = _numTokens;
} else {
tokenCheckpoints[_token][nCheckpoints] = Checkpoint(blockNumber, blockTimestamp, totalWeightedStake, _numTokens);
numTokenCheckpoints[_token] = nCheckpoints + 1;
}
emit CheckpointAdded(msg.sender, _token, _numTokens);
}
}
interface IProtocol {
function withdrawFees(address token, address receiver) external returns (uint256);
function underlyingToLoanPool(address token) external returns (address);
}
interface ILoanToken {
function mint(address receiver, uint256 depositAmount) external returns (uint256 mintAmount);
}
|
adds checkpoint with accumulated amount by function invocation _token address of the token /write a regular checkpoint
|
function _addCheckpoint(address _token) internal {
if (block.timestamp - lastFeeWithdrawalTime[_token] >= FEE_WITHDRAWAL_INTERVAL) {
lastFeeWithdrawalTime[_token] = block.timestamp;
uint96 amount = unprocessedAmount[_token];
unprocessedAmount[_token] = 0;
_writeTokenCheckpoint(_token, amount);
}
}
| 7,285,470
|
./full_match/5/0x3c2F64de19CbA99Dd82B7FCDd56CD122EDB67117/sources/src/Cre8ing.sol
|
exit a CRE8OR from the warehouse tokenId token to exit from the warehouse
|
function leaveWarehouse(uint256 tokenId) internal {
_beforeCre8ingExit(tokenId);
uint256 start = cre8ingStarted[tokenId];
cre8ingTotal[tokenId] += block.timestamp - start;
cre8ingStarted[tokenId] = 0;
emit Uncre8ed(tokenId);
}
| 7,053,681
|
./full_match/11155111/0x699f6dB94d38cD523584c91593e033c29948f56e/sources/contracts/Buffer2.sol
|
Calculate IPFS CID from id and encoding
|
function cid() public view returns (string memory) {
bytes32 data = bytes32(id);
bytes memory alphabet = bytes("abcdefghijklmnopqrstuvwxyz234567");
bytes memory _cid = bytes(encoding ? "bafybei" : "bafkrei");
uint bits = 2;
uint buffer = 24121888;
uint bitsPerChar = 5;
uint mask = uint((1 << bitsPerChar) - 1);
for(uint i=0; i<data.length; ++i) {
bytes1 char = bytes1(bytes32(id << (8*i)));
buffer = (uint32(buffer) << 8) | uint(uint8(char));
bits += 8;
while (bits > bitsPerChar) {
bits -= bitsPerChar;
_cid = abi.encodePacked(_cid, alphabet[mask & (buffer >> bits)]);
}
}
if (bits > 0) {
_cid = abi.encodePacked(_cid, alphabet[mask & (buffer << (bitsPerChar-bits))]);
}
return string(_cid);
}
| 3,795,337
|
./full_match/1287/0xC7C8F57C273c59476f67c614192296dEBcFE9229/sources/project_/contracts/Voting/BaseVotingContract.sol
|
core logic for voting votingBallotId this is the id of the ballot for which user is voting voter Voter's address oldWeight Old weight of the voter newWeight New weight of the voter
|
function _changeVoteWeight(
uint256 votingBallotId,
address voter,
uint256 oldWeight,
uint256 newWeight
) private {
require(
alreadyVoted[votingBallotId][voter] == true,
"INVALID: INTERNAL: USER_HAS_NOT_VOTED"
);
bool vote = userVotes[votingBallotId][voter];
if (vote) {
votingMap[votingBallotId].yesWeight -= oldWeight;
votingMap[votingBallotId].yesWeight += newWeight;
votingMap[votingBallotId].noWeight -= oldWeight;
votingMap[votingBallotId].noWeight += newWeight;
}
}
| 7,096,798
|
/*
_____ _________________ _ _ _ ___ _
/ ___| ___| ___ \ ___ \ | | | | / / | | |
\ `--.| |__ | |_/ / |_/ / | | | |/ /| | | |
`--. \ __|| __/| __/| | | | \| | | |
/\__/ / |___| | | | | |_| | |\ \ |_| |
\____/\____/\_| \_| \___/\_| \_/\___/
seppuku.me
t.me/seppukume
twitter.com/SeppukuMe
Stake your Uniswap LP tokens to Earn Seppuku
*/
pragma solidity ^0.6.12;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.6.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.6.2;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/EnumerableSet.sol
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library 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));
}
}
// File: @openzeppelin/contracts/GSN/Context.sol
pragma solidity ^0.6.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.6.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
pragma solidity 0.6.12;
contract SEPPUKUToken is ERC20("Seppuku.me", "SEPPUKU"), Ownable {
/// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
}
function burn(uint256 _amount) public {
_burn(msg.sender, _amount);
}
}
// File: contracts/MasterChef.sol
pragma solidity 0.6.12;
// MasterChef is the master of SEPPUKU. He can make SEPPUKU and he is a fair guy.
//
// Note that it's ownable and the owner wields tremendous power. The ownership
// will be transferred to a governance smart contract once SEPPUKU is sufficiently
// distributed and the community can show to govern itself.
//
// Have fun reading it. Hopefully it's bug-free. God bless.
contract MasterChef is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. SEPPUKU to distribute per block.
uint256 lastRewardBlock; // Last block number that SEPPUKU distribution occurs.
uint256 accSEPPUKUPerShare; // Accumulated SEPPUKU per share, times 1e12. See below.
}
// The SEPPUKU TOKEN!
SEPPUKUToken public SEPPUKU;
// Dev address.
address public devaddr;
// Block number when bonus SEPPUKU period ends.
uint256 public bonusEndBlock;
// SEPPUKU tokens created per block.
uint256 public SEPPUKUPerBlock;
// Bonus muliplier for early SEPPUKU makers.
uint256 public constant BONUS_MULTIPLIER = 10;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when SUSSEPPUKUHI mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
SEPPUKUToken _SEPPUKU,
address _devaddr,
uint256 _SEPPUKUPerBlock,
uint256 _startBlock,
uint256 _bonusEndBlock
) public {
SEPPUKU = _SEPPUKU;
devaddr = _devaddr;
SEPPUKUPerBlock = _SEPPUKUPerBlock;
bonusEndBlock = _bonusEndBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
// Add a new lp to the pool. Can only be called by the owner.
// XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accSEPPUKUPerShare: 0
}));
}
// Update the given pool's SEPPUKU allocation point. Can only be called by the owner.
function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
if (_to <= bonusEndBlock) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
} else if (_from >= bonusEndBlock) {
return _to.sub(_from);
} else {
return bonusEndBlock.sub(_from).mul(BONUS_MULTIPLIER).add(
_to.sub(bonusEndBlock)
);
}
}
// View function to see pending SEPPUKU on frontend.
function pendingSEPPUKU(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accSEPPUKUPerShare = pool.accSEPPUKUPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 SEPPUKUReward = multiplier.mul(SEPPUKUPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accSEPPUKUPerShare = accSEPPUKUPerShare.add(SEPPUKUReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accSEPPUKUPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function mint(uint256 amount) public onlyOwner{
SEPPUKU.mint(devaddr, amount);
}
// Update reward variables of the given pool to be up-to-date.
function burn(uint256 amount) public onlyOwner{
SEPPUKU.burn(amount);
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 SEPPUKUReward = multiplier.mul(SEPPUKUPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
SEPPUKU.mint(devaddr, SEPPUKUReward.div(4));
SEPPUKU.mint(address(this), SEPPUKUReward);
pool.accSEPPUKUPerShare = pool.accSEPPUKUPerShare.add(SEPPUKUReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for SEPPUKU allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accSEPPUKUPerShare).div(1e12).sub(user.rewardDebt);
safeSEPPUKUTransfer(msg.sender, pending);
}
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
user.rewardDebt = user.amount.mul(pool.accSEPPUKUPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accSEPPUKUPerShare).div(1e12).sub(user.rewardDebt);
safeSEPPUKUTransfer(msg.sender, pending);
user.amount = user.amount.sub(_amount);
user.rewardDebt = user.amount.mul(pool.accSEPPUKUPerShare).div(1e12);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
emit Withdraw(msg.sender, _pid, _amount);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
pool.lpToken.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
}
// Safe SEPPUKU transfer function, just in case if rounding error causes pool to not have enough SEPPUKU.
function safeSEPPUKUTransfer(address _to, uint256 _amount) internal {
uint256 SEPPUKUBal = SEPPUKU.balanceOf(address(this));
if (_amount > SEPPUKUBal) {
SEPPUKU.transfer(_to, SEPPUKUBal);
} else {
SEPPUKU.transfer(_to, _amount);
}
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
}
|
Safe SEPPUKU transfer function, just in case if rounding error causes pool to not have enough SEPPUKU.
|
function safeSEPPUKUTransfer(address _to, uint256 _amount) internal {
uint256 SEPPUKUBal = SEPPUKU.balanceOf(address(this));
if (_amount > SEPPUKUBal) {
SEPPUKU.transfer(_to, SEPPUKUBal);
SEPPUKU.transfer(_to, _amount);
}
}
| 7,669,552
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.0;
// Base
import "./openzeppelin-presets/ERC1155PresetMinterPauserSupplyHolder.sol";
// Token interfaces
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/interfaces/IERC165.sol";
// Meta transactions
import "@openzeppelin/contracts/metatx/ERC2771Context.sol";
// Protocol control center.
import { ProtocolControl } from "./ProtocolControl.sol";
// Royalties
import "@openzeppelin/contracts/interfaces/IERC2981.sol";
import "@openzeppelin/contracts/utils/Multicall.sol";
contract NFTCollection is ERC1155PresetMinterPauserSupplyHolder, ERC2771Context, IERC2981, Multicall {
/// @dev The protocol control center.
ProtocolControl internal controlCenter;
/// @dev The token Id of the next token to be minted.
uint256 public nextTokenId;
/// @dev NFT sale royalties -- see EIP 2981
uint256 public royaltyBps;
/// @dev Collection level metadata.
string public _contractURI;
/// @dev Only TRANSFER_ROLE holders can have tokens transferred from or to them, during restricted transfers.
bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE");
/// @dev Whether transfers on tokens are restricted.
bool public transfersRestricted;
/// @dev Whether the ERC 1155 token is a wrapped ERC 20 / 721 token.
enum UnderlyingType {
None,
ERC20,
ERC721
}
/// @dev The state of a token.
struct TokenState {
address creator;
string uri;
UnderlyingType underlyingType;
}
/// @dev The state of the underlying ERC 721 token, if any.
struct ERC721Wrapped {
address source;
uint256 tokenId;
}
/// @dev The state of the underlying ERC 20 token, if any.
struct ERC20Wrapped {
address source;
uint256 shares;
uint256 underlyingTokenAmount;
}
event RestrictedTransferUpdated(bool transferable);
/// @dev Emitted when native ERC 1155 tokens are created.
event NativeTokens(address indexed creator, uint256[] tokenIds, string[] tokenURIs, uint256[] tokenSupplies);
/// @dev Emitted when ERC 721 wrapped as an ERC 1155 token is minted.
event ERC721WrappedToken(
address indexed creator,
address indexed sourceOfUnderlying,
uint256 tokenIdOfUnderlying,
uint256 tokenId,
string tokenURI
);
/// @dev Emitted when an underlying ERC 721 token is redeemed.
event ERC721Redeemed(
address indexed redeemer,
address indexed sourceOfUnderlying,
uint256 tokenIdOfUnderlying,
uint256 tokenId
);
/// @dev Emitted when ERC 20 wrapped as an ERC 1155 token is minted.
event ERC20WrappedToken(
address indexed creator,
address indexed sourceOfUnderlying,
uint256 totalAmountOfUnderlying,
uint256 shares,
uint256 tokenId,
string tokenURI
);
/// @dev Emitted when an underlying ERC 20 token is redeemed.
event ERC20Redeemed(
address indexed redeemer,
uint256 indexed tokenId,
address indexed sourceOfUnderlying,
uint256 tokenAmountReceived,
uint256 sharesRedeemed
);
/// @dev Emitted when the EIP 2981 royalty of the contract is updated.
event RoyaltyUpdated(uint256 royaltyBps);
/// @dev NFT tokenId => token state.
mapping(uint256 => TokenState) public tokenState;
/// @dev NFT tokenId => state of underlying ERC721 token.
mapping(uint256 => ERC721Wrapped) public erc721WrappedTokens;
/// @dev NFT tokenId => state of underlying ERC20 token.
mapping(uint256 => ERC20Wrapped) public erc20WrappedTokens;
/// @dev Checks whether the caller is a protocol admin.
modifier onlyProtocolAdmin() {
require(
controlCenter.hasRole(controlCenter.DEFAULT_ADMIN_ROLE(), _msgSender()),
"NFTCollection: only a protocol admin can call this function."
);
_;
}
modifier onlyModuleAdmin() {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "only module admin role");
_;
}
/// @dev Checks whether the caller has MINTER_ROLE.
modifier onlyMinterRole() {
require(
hasRole(MINTER_ROLE, _msgSender()),
"NFTCollection: Only accounts with MINTER_ROLE can call this function."
);
_;
}
constructor(
address payable _controlCenter,
address _trustedForwarder,
string memory _uri,
uint256 _royaltyBps
) ERC1155PresetMinterPauserSupplyHolder(_uri) ERC2771Context(_trustedForwarder) {
// Set the protocol control center
controlCenter = ProtocolControl(_controlCenter);
// Set contract URI
_contractURI = _uri;
// Grant TRANSFER_ROLE to deployer.
_setupRole(TRANSFER_ROLE, _msgSender());
setRoyaltyBps(_royaltyBps);
}
/**
* Public functions
*/
/// @notice Create native ERC 1155 NFTs.
function createNativeTokens(
address to,
string[] calldata _nftURIs,
uint256[] calldata _nftSupplies,
bytes memory data
) public whenNotPaused onlyMinterRole returns (uint256[] memory nftIds) {
require(_nftURIs.length == _nftSupplies.length, "NFTCollection: Must specify equal number of config values.");
require(_nftURIs.length > 0, "NFTCollection: Must create at least one NFT.");
// Get creator
address tokenCreator = _msgSender();
// Get tokenIds.
nftIds = new uint256[](_nftURIs.length);
// Store token state for each token.
uint256 id = nextTokenId;
for (uint256 i = 0; i < _nftURIs.length; i++) {
nftIds[i] = id;
tokenState[id] = TokenState({
creator: tokenCreator,
uri: _nftURIs[i],
underlyingType: UnderlyingType.None
});
id += 1;
}
// Update contract level tokenId.
nextTokenId = id;
// Mint NFTs to token creator.
_mintBatch(to, nftIds, _nftSupplies, data);
emit NativeTokens(tokenCreator, nftIds, _nftURIs, _nftSupplies);
}
/// @dev See {ERC1155Minter}.
function mint(
address to,
uint256 id,
uint256 amount,
bytes memory data
) public virtual override {
require(id < nextTokenId, "NFTCollection: cannot call this fn for creating new NFTs.");
require(
tokenState[id].underlyingType == UnderlyingType.None,
"NFTCollection: cannot freely mint more of ERC20 or ERC721."
);
super.mint(to, id, amount, data);
}
/// @dev See {ERC1155Minter}.
function mintBatch(
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) public virtual override {
bool validIds = true;
bool validTokenType = true;
for (uint256 i = 0; i < ids.length; ++i) {
if (ids[i] >= nextTokenId && validIds) {
validIds = false;
}
if (tokenState[ids[i]].underlyingType != UnderlyingType.None && validTokenType) {
validTokenType = false;
}
}
require(validIds, "NFTCollection: cannot call this fn for creating new NFTs.");
require(validTokenType, "NFTCollection: cannot freely mint more of ERC20 or ERC721.");
super.mintBatch(to, ids, amounts, data);
}
/**
* External functions
*/
/// @dev Wraps an ERC721 NFT as an ERC1155 NFT.
function wrapERC721(
address _nftContract,
uint256 _tokenId,
string calldata _nftURI
) external whenNotPaused onlyMinterRole {
require(
IERC721(_nftContract).ownerOf(_tokenId) == _msgSender(),
"NFTCollection: Only the owner of the NFT can wrap it."
);
require(
IERC721(_nftContract).getApproved(_tokenId) == address(this) ||
IERC721(_nftContract).isApprovedForAll(_msgSender(), address(this)),
"NFTCollection: Must approve the contract to transfer the NFT."
);
// Get token creator
address tokenCreator = _msgSender();
// Get tokenId
uint256 id = nextTokenId;
nextTokenId += 1;
// Transfer the NFT to this contract.
IERC721(_nftContract).safeTransferFrom(tokenCreator, address(this), _tokenId);
// Mint wrapped NFT to token creator.
_mint(tokenCreator, id, 1, "");
// Store wrapped NFT state.
tokenState[id] = TokenState({ creator: tokenCreator, uri: _nftURI, underlyingType: UnderlyingType.ERC721 });
// Map the native NFT tokenId to the underlying NFT
erc721WrappedTokens[id] = ERC721Wrapped({ source: _nftContract, tokenId: _tokenId });
emit ERC721WrappedToken(tokenCreator, _nftContract, _tokenId, id, _nftURI);
}
/// @dev Lets a wrapped nft owner redeem the underlying ERC721 NFT.
function redeemERC721(uint256 _nftId) external {
// Get redeemer
address redeemer = _msgSender();
require(balanceOf(redeemer, _nftId) > 0, "NFTCollection: Cannot redeem an NFT you do not own.");
// Burn the native NFT token
_burn(redeemer, _nftId, 1);
// Transfer the NFT to redeemer
IERC721(erc721WrappedTokens[_nftId].source).safeTransferFrom(
address(this),
redeemer,
erc721WrappedTokens[_nftId].tokenId
);
emit ERC721Redeemed(redeemer, erc721WrappedTokens[_nftId].source, erc721WrappedTokens[_nftId].tokenId, _nftId);
}
/// @dev Wraps ERC20 tokens as ERC1155 NFTs.
function wrapERC20(
address _tokenContract,
uint256 _tokenAmount,
uint256 _numOfNftsToMint,
string calldata _nftURI
) external whenNotPaused onlyMinterRole {
// Get creator
address tokenCreator = _msgSender();
require(
IERC20(_tokenContract).balanceOf(tokenCreator) >= _tokenAmount,
"NFTCollection: Must own the amount of tokens being wrapped."
);
require(
IERC20(_tokenContract).allowance(tokenCreator, address(this)) >= _tokenAmount,
"NFTCollection: Must approve this contract to transfer tokens."
);
require(
IERC20(_tokenContract).transferFrom(tokenCreator, address(this), _tokenAmount),
"NFTCollection: Failed to transfer ERC20 tokens."
);
// Get NFT tokenId
uint256 id = nextTokenId;
nextTokenId += 1;
// Mint NFTs to token creator
_mint(tokenCreator, id, _numOfNftsToMint, "");
tokenState[id] = TokenState({ creator: tokenCreator, uri: _nftURI, underlyingType: UnderlyingType.ERC20 });
erc20WrappedTokens[id] = ERC20Wrapped({
source: _tokenContract,
shares: _numOfNftsToMint,
underlyingTokenAmount: _tokenAmount
});
emit ERC20WrappedToken(tokenCreator, _tokenContract, _tokenAmount, _numOfNftsToMint, id, _nftURI);
}
/// @dev Lets the nft owner redeem their ERC20 tokens.
function redeemERC20(uint256 _nftId, uint256 _amount) external {
// Get redeemer
address redeemer = _msgSender();
require(balanceOf(redeemer, _nftId) >= _amount, "NFTCollection: Cannot redeem an NFT you do not own.");
// Burn the native NFT token
_burn(redeemer, _nftId, _amount);
// Get the ERC20 token amount to distribute
uint256 amountToDistribute = (erc20WrappedTokens[_nftId].underlyingTokenAmount * _amount) /
erc20WrappedTokens[_nftId].shares;
// Transfer the ERC20 tokens to redeemer
require(
IERC20(erc20WrappedTokens[_nftId].source).transfer(redeemer, amountToDistribute),
"NFTCollection: Failed to transfer ERC20 tokens."
);
emit ERC20Redeemed(redeemer, _nftId, erc20WrappedTokens[_nftId].source, amountToDistribute, _amount);
}
/**
* External: setter functions
*/
/// @dev Lets a protocol admin update the royalties paid on pack sales.
function setRoyaltyBps(uint256 _royaltyBps) public onlyModuleAdmin {
require(
_royaltyBps < controlCenter.MAX_BPS(),
"NFTCollection: Invalid bps provided; must be less than 10,000."
);
royaltyBps = _royaltyBps;
emit RoyaltyUpdated(_royaltyBps);
}
/// @dev Sets contract URI for the storefront-level metadata of the contract.
function setContractURI(string calldata _URI) external onlyProtocolAdmin {
_contractURI = _URI;
}
/// @dev Lets a protocol admin restrict token transfers.
function setRestrictedTransfer(bool _restrictedTransfer) external onlyModuleAdmin {
transfersRestricted = _restrictedTransfer;
emit RestrictedTransferUpdated(_restrictedTransfer);
}
/**
* Internal functions.
*/
/// @dev Runs on every transfer.
function _beforeTokenTransfer(
address operator,
address from,
address to,
uint256[] memory ids,
uint256[] memory amounts,
bytes memory data
) internal override {
super._beforeTokenTransfer(operator, from, to, ids, amounts, data);
if (transfersRestricted && from != address(0) && to != address(0)) {
require(
hasRole(TRANSFER_ROLE, from) || hasRole(TRANSFER_ROLE, to),
"NFTCollection: Transfers are restricted to or from TRANSFER_ROLE holders"
);
}
}
/// @dev See EIP-2771
function _msgSender() internal view virtual override(Context, ERC2771Context) returns (address sender) {
return ERC2771Context._msgSender();
}
/// @dev See EIP-2771
function _msgData() internal view virtual override(Context, ERC2771Context) returns (bytes calldata) {
return ERC2771Context._msgData();
}
/**
* Rest: view functions
*/
/// @dev See ERC 165
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC1155PresetMinterPauserSupplyHolder, IERC165)
returns (bool)
{
return super.supportsInterface(interfaceId) || interfaceId == type(IERC2981).interfaceId;
}
/// @dev See EIP 2918
function royaltyInfo(uint256, uint256 salePrice)
external
view
virtual
override
returns (address receiver, uint256 royaltyAmount)
{
receiver = controlCenter.getRoyaltyTreasury(address(this));
royaltyAmount = (salePrice * royaltyBps) / controlCenter.MAX_BPS();
}
/// @dev See EIP 1155
function uri(uint256 _nftId) public view override returns (string memory) {
return tokenState[_nftId].uri;
}
/// @dev Alternative function to return a token's URI
function tokenURI(uint256 _nftId) public view returns (string memory) {
return tokenState[_nftId].uri;
}
/// @dev Returns the URI for the storefront-level metadata of the contract.
function contractURI() public view returns (string memory) {
return _contractURI;
}
/// @dev Returns the creator of an NFT
function creator(uint256 _nftId) external view returns (address) {
return tokenState[_nftId].creator;
}
}
|
Lets a protocol admin update the royalties paid on pack sales.
|
function setRoyaltyBps(uint256 _royaltyBps) public onlyModuleAdmin {
require(
_royaltyBps < controlCenter.MAX_BPS(),
"NFTCollection: Invalid bps provided; must be less than 10,000."
);
royaltyBps = _royaltyBps;
emit RoyaltyUpdated(_royaltyBps);
}
| 6,389,281
|
// File: contracts/ComptrollerInterface.sol
pragma solidity 0.5.17;
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function exitMarket(address cToken) external returns (uint);
/*** Policy Hooks ***/
function mintAllowed(address cToken, address minter, uint mintAmount) external returns (uint);
function mintVerify(address cToken, address minter, uint mintAmount, uint mintTokens) external;
function redeemAllowed(address cToken, address redeemer, uint redeemTokens) external returns (uint);
function redeemVerify(address cToken, address redeemer, uint redeemAmount, uint redeemTokens) external;
function borrowAllowed(address cToken, address borrower, uint borrowAmount) external returns (uint);
function borrowVerify(address cToken, address borrower, uint borrowAmount) external;
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint repayAmount) external returns (uint);
function repayBorrowVerify(
address cToken,
address payer,
address borrower,
uint repayAmount,
uint borrowerIndex) external;
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint);
function liquidateBorrowVerify(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint repayAmount,
uint seizeTokens) external;
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint);
function seizeVerify(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external;
function transferAllowed(address cToken, address src, address dst, uint transferTokens) external returns (uint);
function transferVerify(address cToken, address src, address dst, uint transferTokens) external;
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint repayAmount) external view returns (uint, uint);
}
// File: contracts/InterestRateModel.sol
pragma solidity 0.5.17;
/**
* @title InterestRateModel Interface
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(uint cash, uint borrows, uint reserves) external view returns (uint);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amnount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(uint cash, uint borrows, uint reserves, uint reserveFactorMantissa) external view returns (uint);
}
// File: contracts/GTokenInterfaces.sol
pragma solidity 0.5.17;
contract GTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-gToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping (address => uint) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping (address => mapping (address => uint)) internal transferAllowances;
/**
* @notice Container for borrow balance information
* @member principal Total balance (with accrued interest), after applying the most recent balance-changing action
* @member interestIndex Global borrowIndex as of the most recent balance-changing action
*/
struct BorrowSnapshot {
uint principal;
uint interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
}
contract GTokenInterface is GTokenStorage {
/**
* @notice Indicator that this is a GToken contract (for inspection)
*/
bool public constant isCToken = true;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint cashPrior, uint interestAccumulated, uint borrowIndex, uint totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint mintAmount, uint mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint redeemAmount, uint redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint borrowAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint repayAmount, uint accountBorrows, uint totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(address liquidator, address borrower, uint repayAmount, address cTokenCollateral, uint seizeTokens);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when comptroller is changed
*/
event NewComptroller(ComptrollerInterface oldComptroller, ComptrollerInterface newComptroller);
/**
* @notice Event emitted when interestRateModel is changed
*/
event NewMarketInterestRateModel(InterestRateModel oldInterestRateModel, InterestRateModel newInterestRateModel);
/**
* @notice Event emitted when the reserve factor is changed
*/
event NewReserveFactor(uint oldReserveFactorMantissa, uint newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint addAmount, uint newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint reduceAmount, uint newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint amount);
/**
* @notice Failure event
*/
event Failure(uint error, uint info, uint detail);
/*** User Interface ***/
function transfer(address dst, uint amount) external returns (bool);
function transferFrom(address src, address dst, uint amount) external returns (bool);
function approve(address spender, uint amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint);
function borrowRatePerBlock() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
function totalBorrowsCurrent() external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function borrowBalanceStored(address account) public view returns (uint);
function exchangeRateCurrent() public returns (uint);
function exchangeRateStored() public view returns (uint);
function getCash() external view returns (uint);
function accrueInterest() public returns (uint);
function seize(address liquidator, address borrower, uint seizeTokens) external returns (uint);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint);
function _acceptAdmin() external returns (uint);
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint);
function _setReserveFactor(uint newReserveFactorMantissa) external returns (uint);
function _reduceReserves(uint reduceAmount) external returns (uint);
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint);
}
contract CErc20Interface {
/*** User Interface ***/
function mint(uint mintAmount) external returns (uint);
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint);
function liquidateBorrow(address borrower, uint repayAmount, GTokenInterface cTokenCollateral) external returns (uint);
/*** Admin Functions ***/
function _addReserves(uint addAmount) external returns (uint);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(address implementation_, bool allowResign, bytes memory becomeImplementationData) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
// File: contracts/ErrorReporter.sol
pragma solidity 0.5.17;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR, // 0
UNAUTHORIZED, // 1
COMPTROLLER_MISMATCH, // 2
INSUFFICIENT_SHORTFALL, // 3
INSUFFICIENT_LIQUIDITY, // 4
INVALID_CLOSE_FACTOR, // 5
INVALID_COLLATERAL_FACTOR, // 6
INVALID_LIQUIDATION_INCENTIVE, // 7
MARKET_NOT_ENTERED, // 8 no longer possible
MARKET_NOT_LISTED, // 9
MARKET_ALREADY_LISTED, // 10
MATH_ERROR, // 11
NONZERO_BORROW_BALANCE, // 12
PRICE_ERROR, // 13
REJECTION, // 14
SNAPSHOT_ERROR, // 15
TOO_MANY_ASSETS, // 16
TOO_MUCH_REPAY // 17
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK, // 0
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK, // 1
EXIT_MARKET_BALANCE_OWED, // 2
EXIT_MARKET_REJECTION, // 3
SET_CLOSE_FACTOR_OWNER_CHECK, // 4
SET_CLOSE_FACTOR_VALIDATION, // 5
SET_COLLATERAL_FACTOR_OWNER_CHECK, // 6
SET_COLLATERAL_FACTOR_NO_EXISTS, // 7
SET_COLLATERAL_FACTOR_VALIDATION, // 8
SET_COLLATERAL_FACTOR_WITHOUT_PRICE, // 9
SET_IMPLEMENTATION_OWNER_CHECK, // 10
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK, // 11
SET_LIQUIDATION_INCENTIVE_VALIDATION, // 12
SET_MAX_ASSETS_OWNER_CHECK, // 13
SET_PENDING_ADMIN_OWNER_CHECK, // 14
SET_PENDING_IMPLEMENTATION_OWNER_CHECK, // 15
SET_PRICE_ORACLE_OWNER_CHECK, // 16
SUPPORT_MARKET_EXISTS, // 17
SUPPORT_MARKET_OWNER_CHECK, // 18
SET_PAUSE_GUARDIAN_OWNER_CHECK // 19
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR, // 0
UNAUTHORIZED, // 1
BAD_INPUT, // 2
COMPTROLLER_REJECTION, // 3
COMPTROLLER_CALCULATION_ERROR, // 4
INTEREST_RATE_MODEL_ERROR, // 5
INVALID_ACCOUNT_PAIR, // 6
INVALID_CLOSE_AMOUNT_REQUESTED, // 7
INVALID_COLLATERAL_FACTOR, // 8
MATH_ERROR, // 9
MARKET_NOT_FRESH, // 10
MARKET_NOT_LISTED, // 11
TOKEN_INSUFFICIENT_ALLOWANCE, // 12
TOKEN_INSUFFICIENT_BALANCE, // 13
TOKEN_INSUFFICIENT_CASH, // 14
TOKEN_TRANSFER_IN_FAILED, // 15
TOKEN_TRANSFER_OUT_FAILED // 16
}
/*
* Note: FailureInfo (but not Error) is kept in alphabetical order
* This is because FailureInfo grows significantly faster, and
* the order of Error has some meaning, while the order of FailureInfo
* is entirely arbitrary.
*/
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK, // 0
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, // 1
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED, // 2
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, // 3
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, // 4
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, // 5
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, // 6
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, // 7
BORROW_ACCRUE_INTEREST_FAILED, // 8
BORROW_CASH_NOT_AVAILABLE, // 9
BORROW_FRESHNESS_CHECK, // 10
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, // 11
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, // 12
BORROW_MARKET_NOT_LISTED, // 13
BORROW_COMPTROLLER_REJECTION, // 14
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED, // 15
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED, // 16
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK, // 17
LIQUIDATE_COMPTROLLER_REJECTION, // 18
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED, // 19
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX, // 20
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO, // 21
LIQUIDATE_FRESHNESS_CHECK, // 22
LIQUIDATE_LIQUIDATOR_IS_BORROWER, // 23
LIQUIDATE_REPAY_BORROW_FRESH_FAILED, // 24
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, // 25
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, // 26
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, // 27
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER, // 28
LIQUIDATE_SEIZE_TOO_MUCH, // 29
MINT_ACCRUE_INTEREST_FAILED, // 30
MINT_COMPTROLLER_REJECTION, // 31
MINT_EXCHANGE_CALCULATION_FAILED, // 32
MINT_EXCHANGE_RATE_READ_FAILED, // 33
MINT_FRESHNESS_CHECK, // 34
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, // 35
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, // 36
MINT_TRANSFER_IN_FAILED, // 37
MINT_TRANSFER_IN_NOT_POSSIBLE, // 38
REDEEM_ACCRUE_INTEREST_FAILED, // 39
REDEEM_COMPTROLLER_REJECTION, // 40
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, // 41
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, // 42
REDEEM_EXCHANGE_RATE_READ_FAILED, // 42
REDEEM_FRESHNESS_CHECK, // 43
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, // 44
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, // 45
REDEEM_TRANSFER_OUT_NOT_POSSIBLE, // 46
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED, // 47
REDUCE_RESERVES_ADMIN_CHECK, // 48
REDUCE_RESERVES_CASH_NOT_AVAILABLE, // 49
REDUCE_RESERVES_FRESH_CHECK, // 50
REDUCE_RESERVES_VALIDATION, // 51
REPAY_BEHALF_ACCRUE_INTEREST_FAILED, // 52
REPAY_BORROW_ACCRUE_INTEREST_FAILED, // 53
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, //54
REPAY_BORROW_COMPTROLLER_REJECTION, // 55
REPAY_BORROW_FRESHNESS_CHECK, // 56
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, //57
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, // 58
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE, // 59
SET_COLLATERAL_FACTOR_OWNER_CHECK, // 60
SET_COLLATERAL_FACTOR_VALIDATION, // 61
SET_COMPTROLLER_OWNER_CHECK, // 62
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED, //63
SET_INTEREST_RATE_MODEL_FRESH_CHECK, // 64
SET_INTEREST_RATE_MODEL_OWNER_CHECK, // 65
SET_MAX_ASSETS_OWNER_CHECK, // 66
SET_ORACLE_MARKET_NOT_LISTED, // 67
SET_PENDING_ADMIN_OWNER_CHECK, // 68
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED, // 69
SET_RESERVE_FACTOR_ADMIN_CHECK, // 70
SET_RESERVE_FACTOR_FRESH_CHECK, // 71
SET_RESERVE_FACTOR_BOUNDS_CHECK, // 72
TRANSFER_COMPTROLLER_REJECTION, // 73
TRANSFER_NOT_ALLOWED, // 74
TRANSFER_NOT_ENOUGH, // 75
TRANSFER_TOO_MUCH, // 76
ADD_RESERVES_ACCRUE_INTEREST_FAILED, // 77
ADD_RESERVES_FRESH_CHECK, // 78
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE // 79
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint error, uint info, uint detail);
/**
* @dev use this when reporting a known error from the money market or a non-upgradeable collaborator
*/
function fail(Error err, FailureInfo info) internal returns (uint) {
emit Failure(uint(err), uint(info), 0);
return uint(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(Error err, FailureInfo info, uint opaqueError) internal returns (uint) {
emit Failure(uint(err), uint(info), opaqueError);
return uint(err);
}
}
// File: contracts/CarefulMath.sol
pragma solidity 0.5.17;
/**
* @title Careful Math
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {
NO_ERROR,
DIVISION_BY_ZERO,
INTEGER_OVERFLOW,
INTEGER_UNDERFLOW
}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint c = a * b;
if (c / a != b) {
return (MathError.INTEGER_OVERFLOW, 0);
} else {
return (MathError.NO_ERROR, c);
}
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function divUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b == 0) {
return (MathError.DIVISION_BY_ZERO, 0);
}
return (MathError.NO_ERROR, a / b);
}
/**
* @dev Subtracts two numbers, returns an error on overflow (i.e. if subtrahend is greater than minuend).
*/
function subUInt(uint a, uint b) internal pure returns (MathError, uint) {
if (b <= a) {
return (MathError.NO_ERROR, a - b);
} else {
return (MathError.INTEGER_UNDERFLOW, 0);
}
}
/**
* @dev Adds two numbers, returns an error on overflow.
*/
function addUInt(uint a, uint b) internal pure returns (MathError, uint) {
uint c = a + b;
if (c >= a) {
return (MathError.NO_ERROR, c);
} else {
return (MathError.INTEGER_OVERFLOW, 0);
}
}
/**
* @dev add a and b and then subtract c
*/
function addThenSubUInt(uint a, uint b, uint c) internal pure returns (MathError, uint) {
(MathError err0, uint sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
// File: contracts/Exponential.sol
pragma solidity 0.5.17;
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint num, uint denom) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint rational) = divUInt(scaledNumerator, denom);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: rational}));
}
/**
* @dev Adds two exponentials, returning a new exponential.
*/
function addExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = addUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Subtracts two exponentials, returning a new exponential.
*/
function subExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError error, uint result) = subUInt(a.mantissa, b.mantissa);
return (error, Exp({mantissa: result}));
}
/**
* @dev Multiply an Exp by a scalar, returning a new Exp.
*/
function mulScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint scaledMantissa) = mulUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: scaledMantissa}));
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mulScalarTruncate(Exp memory a, uint scalar) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(product));
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mulScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (MathError, uint) {
(MathError err, Exp memory product) = mulScalar(a, scalar);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return addUInt(truncate(product), addend);
}
/**
* @dev Divide an Exp by a scalar, returning a new Exp.
*/
function divScalar(Exp memory a, uint scalar) pure internal returns (MathError, Exp memory) {
(MathError err0, uint descaledMantissa) = divUInt(a.mantissa, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return (MathError.NO_ERROR, Exp({mantissa: descaledMantissa}));
}
/**
* @dev Divide a scalar by an Exp, returning a new Exp.
*/
function divScalarByExp(uint scalar, Exp memory divisor) pure internal returns (MathError, Exp memory) {
/*
We are doing this as:
getExp(mulUInt(expScale, scalar), divisor.mantissa)
How it works:
Exp = a / b;
Scalar = s;
`s / (a / b)` = `b * s / a` and since for an Exp `a = mantissa, b = expScale`
*/
(MathError err0, uint numerator) = mulUInt(expScale, scalar);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
return getExp(numerator, divisor.mantissa);
}
/**
* @dev Divide a scalar by an Exp, then truncate to return an unsigned integer.
*/
function divScalarByExpTruncate(uint scalar, Exp memory divisor) pure internal returns (MathError, uint) {
(MathError err, Exp memory fraction) = divScalarByExp(scalar, divisor);
if (err != MathError.NO_ERROR) {
return (err, 0);
}
return (MathError.NO_ERROR, truncate(fraction));
}
/**
* @dev Multiplies two exponentials, returning a new exponential.
*/
function mulExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
(MathError err0, uint doubleScaledProduct) = mulUInt(a.mantissa, b.mantissa);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
// We add half the scale before dividing so that we get rounding instead of truncation.
// See "Listing 6" and text above it at https://accu.org/index.php/journals/1717
// Without this change, a result like 6.6...e-19 will be truncated to 0 instead of being rounded to 1e-18.
(MathError err1, uint doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint product) = divUInt(doubleScaledProductWithHalfScale, expScale);
// The only error `div` can return is MathError.DIVISION_BY_ZERO but we control `expScale` and it is not zero.
assert(err2 == MathError.NO_ERROR);
return (MathError.NO_ERROR, Exp({mantissa: product}));
}
/**
* @dev Multiplies two exponentials given their mantissas, returning a new exponential.
*/
function mulExp(uint a, uint b) pure internal returns (MathError, Exp memory) {
return mulExp(Exp({mantissa: a}), Exp({mantissa: b}));
}
/**
* @dev Multiplies three exponentials, returning a new exponential.
*/
function mulExp3(Exp memory a, Exp memory b, Exp memory c) pure internal returns (MathError, Exp memory) {
(MathError err, Exp memory ab) = mulExp(a, b);
if (err != MathError.NO_ERROR) {
return (err, ab);
}
return mulExp(ab, c);
}
/**
* @dev Divides two exponentials, returning a new exponential.
* (a/scale) / (b/scale) = (a/scale) * (scale/b) = a/b,
* which we can scale as an Exp by calling getExp(a.mantissa, b.mantissa)
*/
function divExp(Exp memory a, Exp memory b) pure internal returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// File: contracts/EIP20Interface.sol
pragma solidity 0.5.17;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// File: contracts/EIP20NonStandardInterface.sol
pragma solidity 0.5.17;
/**
* @title EIP20NonStandardInterface
* @dev Version of ERC20 with no return values for `transfer` and `transferFrom`
* See https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
interface EIP20NonStandardInterface {
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transfer` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transfer(address dst, uint256 amount) external;
///
/// !!!!!!!!!!!!!!
/// !!! NOTICE !!! `transferFrom` does not return a value, in violation of the ERC-20 specification
/// !!!!!!!!!!!!!!
///
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
*/
function transferFrom(address src, address dst, uint256 amount) external;
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// File: contracts/GToken.sol
pragma solidity 0.5.17;
/**
* @title GToken Contract
* @notice Abstract base for CTokens
*/
contract GToken is GTokenInterface, Exponential, TokenErrorReporter {
bytes32 internal constant projectHash = keccak256(abi.encodePacked("ZILD"));
/**
* @notice Underlying asset for this GToken
*/
address public underlying;
/**
* @notice , ETH is native coin
*/
bool public underlyingIsNativeCoin;
// borrow fee amount * borrowFee / 10000;
uint public borrowFee;
// redeem fee amount = redeem amount * redeemFee / 10000;
uint public redeemFee;
uint public constant TEN_THOUSAND = 10000;
// max fee borrow redeem fee : 1%
uint public constant MAX_BORROW_REDEEM_FEE = 100;
// borrow fee and redeemFee will send to feeTo
address payable public feeTo;
event NewBorrowFee(uint oldBorrowFee, uint newBorrowFee);
event NewRedeemFee(uint oldRedeemFee, uint newRedeemFee);
event NewFeeTo(address oldFeeTo, address newFeeTo);
/**
* @notice Initialize the money market
* @param underlying_ Underlying asset for this GToken, ZETH's underlying is address(0)
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
* @param borrowFee_ borrow fee
* @param redeemFee_ redeem fee
* @param feeTo_ fee address
*/
function initialize(address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_, uint borrowFee_, uint redeemFee_, address payable feeTo_) public {
require(msg.sender == admin, "only admin may initialize the market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market may only be initialized once");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be greater than zero.");
// Set the comptroller
uint err = _setComptroller(comptroller_);
require(err == uint(Error.NO_ERROR), "setting comptroller failed");
// Initialize block number and borrow index (block number mocks depend on comptroller being set)
accrualBlockNumber = getBlockNumber();
borrowIndex = mantissaOne;
// Set the interest rate model (depends on block number / borrow index)
err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint(Error.NO_ERROR), "setting interest rate model failed");
_setBorrowFee(borrowFee_);
_setRedeemFee(redeemFee_);
_setFeeTo(feeTo_);
name = name_;
symbol = symbol_;
decimals = decimals_;
underlying = underlying_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
}
/**
* @notice .
* @dev Admin function: change borrowFee.
* @param newBorrowFee newBorrowFee
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setBorrowFee(uint newBorrowFee) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
require(newBorrowFee <= MAX_BORROW_REDEEM_FEE, "newBorrowFee is greater than MAX_BORROW_REDEEM_FEE");
emit NewBorrowFee(borrowFee, newBorrowFee);
borrowFee = newBorrowFee;
return uint(Error.NO_ERROR);
}
/**
* @notice .
* @dev Admin function: change redeemFee.
* @param newRedeemFee newRedeemFee
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setRedeemFee(uint newRedeemFee) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
require(newRedeemFee <= MAX_BORROW_REDEEM_FEE, "newRedeemFee is greater than MAX_BORROW_REDEEM_FEE");
emit NewBorrowFee(redeemFee, newRedeemFee);
redeemFee = newRedeemFee;
return uint(Error.NO_ERROR);
}
/**
* @notice .
* @dev Admin function: change feeTo.
* @param newFeeTo newFeeTo
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setFeeTo(address payable newFeeTo) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
require(newFeeTo != address(0), "newFeeTo is zero address");
emit NewFeeTo(feeTo, newFeeTo);
feeTo = newFeeTo;
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `tokens` tokens from `src` to `dst` by `spender`
* @dev Called by both `transfer` and `transferFrom` internally
* @param spender The address of the account performing the transfer
* @param src The address of the source account
* @param dst The address of the destination account
* @param tokens The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferTokens(address spender, address src, address dst, uint tokens) internal returns (uint) {
/* Fail if transfer not allowed */
uint allowed = comptroller.transferAllowed(address(this), src, dst, tokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.TRANSFER_COMPTROLLER_REJECTION, allowed);
}
/* Do not allow self-transfers */
if (src == dst) {
return fail(Error.BAD_INPUT, FailureInfo.TRANSFER_NOT_ALLOWED);
}
/* Get the allowance, infinite for the account owner */
uint startingAllowance = 0;
if (spender == src) {
startingAllowance = uint(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint allowanceNew;
uint srcTokensNew;
uint dstTokensNew;
(mathErr, allowanceNew) = subUInt(startingAllowance, tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ALLOWED);
}
(mathErr, srcTokensNew) = subUInt(accountTokens[src], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_NOT_ENOUGH);
}
(mathErr, dstTokensNew) = addUInt(accountTokens[dst], tokens);
if (mathErr != MathError.NO_ERROR) {
return fail(Error.MATH_ERROR, FailureInfo.TRANSFER_TOO_MUCH);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
accountTokens[src] = srcTokensNew;
accountTokens[dst] = dstTokensNew;
/* Eat some of the allowance (if necessary) */
if (startingAllowance != uint(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
comptroller.transferVerify(address(this), src, dst, tokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, msg.sender, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external nonReentrant returns (bool) {
return transferTokens(msg.sender, src, dst, amount) == uint(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool) {
address src = msg.sender;
transferAllowances[src][spender] = amount;
emit Approval(src, spender, amount);
return true;
}
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256) {
return transferAllowances[owner][spender];
}
/**
* @notice Get the token balance of the `owner`
* @param owner The address of the account to query
* @return The number of tokens owned by `owner`
*/
function balanceOf(address owner) external view returns (uint256) {
return accountTokens[owner];
}
/**
* @notice Get the underlying balance of the `owner`
* @dev This also accrues interest in a transaction
* @param owner The address of the account to query
* @return The amount of underlying owned by `owner`
*/
function balanceOfUnderlying(address owner) external returns (uint) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "balance could not be calculated");
return balance;
}
/**
* @notice Get a snapshot of the account's balances, and the cached exchange rate
* @dev This is used by comptroller to more efficiently perform liquidity checks.
* @param account Address of the account to snapshot
* @return (possible error, token balance, borrow balance, exchange rate mantissa)
*/
function getAccountSnapshot(address account) external view returns (uint, uint, uint, uint) {
uint cTokenBalance = accountTokens[account];
uint borrowBalance;
uint exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0, 0, 0);
}
return (uint(Error.NO_ERROR), cTokenBalance, borrowBalance, exchangeRateMantissa);
}
/**
* @dev Function to simply retrieve block number
* This exists mainly for inheriting test contracts to stub this result.
*/
function getBlockNumber() internal view returns (uint) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this gToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint) {
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this gToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint) {
return interestRateModel.getSupplyRate(getCashPrior(), totalBorrows, totalReserves, reserveFactorMantissa);
}
/**
* @notice Returns the current total borrows plus accrued interest
* @return The total borrows with interest
*/
function totalBorrowsCurrent() external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return totalBorrows;
}
/**
* @notice Accrue interest to updated borrowIndex and then calculate account's borrow balance using the updated borrowIndex
* @param account The address whose balance should be calculated after updating borrowIndex
* @return The calculated balance
*/
function borrowBalanceCurrent(address account) external nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return borrowBalanceStored(account);
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return The calculated balance
*/
function borrowBalanceStored(address account) public view returns (uint) {
(MathError err, uint result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "borrowBalanceStored: borrowBalanceStoredInternal failed");
return result;
}
/**
* @notice Return the borrow balance of account based on stored data
* @param account The address whose balance should be calculated
* @return (error code, the calculated balance or 0 if error code is non-zero)
*/
function borrowBalanceStoredInternal(address account) internal view returns (MathError, uint) {
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint principalTimesIndex;
uint result;
/* Get borrowBalance and borrowIndex */
BorrowSnapshot storage borrowSnapshot = accountBorrows[account];
/* If borrowBalance = 0 then borrowIndex is likely also 0.
* Rather than failing the calculation with a division by 0, we immediately return 0 in this case.
*/
if (borrowSnapshot.principal == 0) {
return (MathError.NO_ERROR, 0);
}
/* Calculate new borrow balance using the interest index:
* recentBorrowBalance = borrower.borrowBalance * market.borrowIndex / borrower.borrowIndex
*/
(mathErr, principalTimesIndex) = mulUInt(borrowSnapshot.principal, borrowIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, result) = divUInt(principalTimesIndex, borrowSnapshot.interestIndex);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, result);
}
/**
* @notice Accrue interest then return the up-to-date exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateCurrent() public nonReentrant returns (uint) {
require(accrueInterest() == uint(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the GToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint) {
(MathError err, uint result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStored: exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the GToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint) {
uint _totalSupply = totalSupply;
if (_totalSupply == 0) {
/*
* If there are no tokens minted:
* exchangeRate = initialExchangeRate
*/
return (MathError.NO_ERROR, initialExchangeRateMantissa);
} else {
/*
* Otherwise:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*/
uint totalCash = getCashPrior();
uint cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this gToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint) {
return getCashPrior();
}
/**
* @notice Applies accrued interest to total borrows and reserves
* @dev This calculates interest accrued from the last checkpointed block
* up to the current block and writes new checkpoint to storage.
*/
function accrueInterest() public returns (uint) {
/* Remember the initial block number */
uint currentBlockNumber = getBlockNumber();
uint accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint cashPrior = getCashPrior();
uint borrowsPrior = totalBorrows;
uint reservesPrior = totalReserves;
uint borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate is absurdly high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint blockDelta) = subUInt(currentBlockNumber, accrualBlockNumberPrior);
require(mathErr == MathError.NO_ERROR, "could not calculate block delta");
/*
* Calculate the interest accumulated into borrows and reserves and the new index:
* simpleInterestFactor = borrowRate * blockDelta
* interestAccumulated = simpleInterestFactor * totalBorrows
* totalBorrowsNew = interestAccumulated + totalBorrows
* totalReservesNew = interestAccumulated * reserveFactor + totalReserves
* borrowIndexNew = simpleInterestFactor * borrowIndex + borrowIndex
*/
Exp memory simpleInterestFactor;
uint interestAccumulated;
uint totalBorrowsNew;
uint totalReservesNew;
uint borrowIndexNew;
(mathErr, simpleInterestFactor) = mulScalar(Exp({mantissa: borrowRateMantissa}), blockDelta);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, totalReservesNew) = mulScalarTruncateAddUInt(Exp({mantissa: reserveFactorMantissa}), interestAccumulated, reservesPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED, uint(mathErr));
}
(mathErr, borrowIndexNew) = mulScalarTruncateAddUInt(simpleInterestFactor, borrowIndexPrior, borrowIndexPrior);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accrualBlockNumber = currentBlockNumber;
borrowIndex = borrowIndexNew;
totalBorrows = totalBorrowsNew;
totalReserves = totalReservesNew;
/* We emit an AccrueInterest event */
emit AccrueInterest(cashPrior, interestAccumulated, borrowIndexNew, totalBorrowsNew);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintInternal(uint mintAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.MINT_ACCRUE_INTEREST_FAILED), 0);
}
// mintFresh emits the actual Mint event if successful and logs on errors, so we don't need to
return mintFresh(msg.sender, mintAmount);
}
struct MintLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint mintTokens;
uint totalSupplyNew;
uint accountTokensNew;
uint actualMintAmount;
}
/**
* @notice User supplies assets into the market and receives cTokens in exchange
* @dev Assumes interest has already been accrued up to the current block
* @param minter The address of the account which is supplying the assets
* @param mintAmount The amount of the underlying asset to supply
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual mint amount.
*/
function mintFresh(address minter, uint mintAmount) internal returns (uint, uint) {
/* Fail if mint not allowed */
uint allowed = comptroller.mintAllowed(address(this), minter, mintAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.MINT_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.MINT_FRESHNESS_CHECK), 0);
}
MintLocalVars memory vars;
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.MINT_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the gToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(vars.actualMintAmount, Exp({mantissa: vars.exchangeRateMantissa}));
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
/* We call the defense hook */
comptroller.mintVerify(address(this), minter, vars.actualMintAmount, vars.mintTokens);
return (uint(Error.NO_ERROR), vars.actualMintAmount);
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemInternal(uint redeemTokens) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, redeemTokens, 0);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to receive from redeeming cTokens
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlyingInternal(uint redeemAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted redeem failed
return fail(Error(error), FailureInfo.REDEEM_ACCRUE_INTEREST_FAILED);
}
// redeemFresh emits redeem-specific logs on errors, so we don't need to
return redeemFresh(msg.sender, 0, redeemAmount);
}
struct RedeemLocalVars {
Error err;
MathError mathErr;
uint exchangeRateMantissa;
uint redeemTokens;
uint redeemAmount;
uint totalSupplyNew;
uint accountTokensNew;
}
/**
* @notice User redeems cTokens in exchange for the underlying asset
* @dev Assumes interest has already been accrued up to the current block
* @param redeemer The address of the account which is redeeming the tokens
* @param redeemTokensIn The number of cTokens to redeem into underlying (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @param redeemAmountIn The number of underlying tokens to receive from redeeming cTokens (only one of redeemTokensIn or redeemAmountIn may be non-zero)
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemFresh(address payable redeemer, uint redeemTokensIn, uint redeemAmountIn) internal returns (uint) {
require(redeemTokensIn == 0 || redeemAmountIn == 0, "one of redeemTokensIn or redeemAmountIn must be zero");
RedeemLocalVars memory vars;
/* exchangeRate = invoke Exchange Rate Stored() */
(vars.mathErr, vars.exchangeRateMantissa) = exchangeRateStoredInternal();
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_RATE_READ_FAILED, uint(vars.mathErr));
}
/* If redeemTokensIn > 0: */
if (redeemTokensIn > 0) {
/*
* We calculate the exchange rate and the amount of underlying to be redeemed:
* redeemTokens = redeemTokensIn
* redeemAmount = redeemTokensIn x exchangeRateCurrent
*/
vars.redeemTokens = redeemTokensIn;
(vars.mathErr, vars.redeemAmount) = mulScalarTruncate(Exp({mantissa: vars.exchangeRateMantissa}), redeemTokensIn);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED, uint(vars.mathErr));
}
} else {
/*
* We get the current exchange rate and calculate the amount to be redeemed:
* redeemTokens = redeemAmountIn / exchangeRate
* redeemAmount = redeemAmountIn
*/
(vars.mathErr, vars.redeemTokens) = divScalarByExpTruncate(redeemAmountIn, Exp({mantissa: vars.exchangeRateMantissa}));
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED, uint(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint allowed = comptroller.redeemAllowed(address(this), redeemer, vars.redeemTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REDEEM_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDEEM_FRESHNESS_CHECK);
}
/*
* We calculate the new total supply and redeemer balance, checking for underflow:
* totalSupplyNew = totalSupply - redeemTokens
* accountTokensNew = accountTokens[redeemer] - redeemTokens
*/
(vars.mathErr, vars.totalSupplyNew) = subUInt(totalSupply, vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountTokensNew) = subUInt(accountTokens[redeemer], vars.redeemTokens);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* On success, the gToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
uint fee = 0;
uint redeemAmountMinusFee = 0;
(vars.mathErr, fee) = mulUInt(vars.redeemAmount, redeemFee);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, fee) = divUInt(fee, TEN_THOUSAND);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, redeemAmountMinusFee) = subUInt(vars.redeemAmount, fee);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
// doTransferOut(redeemer, vars.redeemAmount);
// vars.redeemAmount = redeemAmountMinusFee + fee
doTransferOut(redeemer, redeemAmountMinusFee);
doTransferOut(feeTo, fee);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* We call the defense hook */
comptroller.redeemVerify(address(this), redeemer, vars.redeemAmount, vars.redeemTokens);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowInternal(uint borrowAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return fail(Error(error), FailureInfo.BORROW_ACCRUE_INTEREST_FAILED);
}
// borrowFresh emits borrow-specific logs on errors, so we don't need to
return borrowFresh(msg.sender, borrowAmount);
}
struct BorrowLocalVars {
MathError mathErr;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
}
/**
* @notice Users borrow assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrowFresh(address payable borrower, uint borrowAmount) internal returns (uint) {
/* Fail if borrow not allowed */
uint allowed = comptroller.borrowAllowed(address(this), borrower, borrowAmount);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.BORROW_COMPTROLLER_REJECTION, allowed);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.BORROW_FRESHNESS_CHECK);
}
/* Fail gracefully if protocol has insufficient underlying cash */
if (getCashPrior() < borrowAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.BORROW_CASH_NOT_AVAILABLE);
}
BorrowLocalVars memory vars;
/*
* We calculate the new borrower and total borrow balances, failing on overflow:
* accountBorrowsNew = accountBorrows + borrowAmount
* totalBorrowsNew = totalBorrows + borrowAmount
*/
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.accountBorrowsNew) = addUInt(vars.accountBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, vars.totalBorrowsNew) = addUInt(totalBorrows, borrowAmount);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* On success, the gToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
uint fee = 0;
uint borrowAmountMinusFee = 0;
(vars.mathErr, fee) = mulUInt(borrowAmount, borrowFee);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, fee) = divUInt(fee, TEN_THOUSAND);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
(vars.mathErr, borrowAmountMinusFee) = subUInt(borrowAmount, fee);
if (vars.mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED, uint(vars.mathErr));
}
doTransferOut(borrower, borrowAmountMinusFee);
doTransferOut(feeTo, fee);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.borrowVerify(address(this), borrower, borrowAmount);
return uint(Error.NO_ERROR);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowInternal(uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BORROW_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, msg.sender, repayAmount);
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowBehalfInternal(address borrower, uint repayAmount) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted borrow failed
return (fail(Error(error), FailureInfo.REPAY_BEHALF_ACCRUE_INTEREST_FAILED), 0);
}
// repayBorrowFresh emits repay-borrow-specific logs on errors, so we don't need to
return repayBorrowFresh(msg.sender, borrower, repayAmount);
}
struct RepayBorrowLocalVars {
Error err;
MathError mathErr;
uint repayAmount;
uint borrowerIndex;
uint accountBorrows;
uint accountBorrowsNew;
uint totalBorrowsNew;
uint actualRepayAmount;
}
/**
* @notice Borrows are repaid by another user (possibly the borrower).
* @param payer the account paying off the borrow
* @param borrower the account with the debt being payed off
* @param repayAmount the amount of undelrying tokens being returned
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function repayBorrowFresh(address payer, address borrower, uint repayAmount) internal returns (uint, uint) {
/* Fail if repayBorrow not allowed */
uint allowed = comptroller.repayBorrowAllowed(address(this), payer, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.REPAY_BORROW_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.REPAY_BORROW_FRESHNESS_CHECK), 0);
}
RepayBorrowLocalVars memory vars;
/* We remember the original borrowerIndex for verification purposes */
vars.borrowerIndex = accountBorrows[borrower].interestIndex;
/* We fetch the amount the borrower owes, with accumulated interest */
(vars.mathErr, vars.accountBorrows) = borrowBalanceStoredInternal(borrower);
if (vars.mathErr != MathError.NO_ERROR) {
return (failOpaque(Error.MATH_ERROR, FailureInfo.REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED, uint(vars.mathErr)), 0);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* On success, the gToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
/* We call the defense hook */
comptroller.repayBorrowVerify(address(this), payer, borrower, vars.actualRepayAmount, vars.borrowerIndex);
return (uint(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this gToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(address borrower, uint repayAmount, GTokenInterface cTokenCollateral) internal nonReentrant returns (uint, uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED), 0);
}
error = cTokenCollateral.accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this gToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(address liquidator, address borrower, uint repayAmount, GTokenInterface cTokenCollateral) internal returns (uint, uint) {
/* Fail if liquidate not allowed */
uint allowed = comptroller.liquidateBorrowAllowed(address(this), address(cTokenCollateral), liquidator, borrower, repayAmount);
if (allowed != 0) {
return (failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_COMPTROLLER_REJECTION, allowed), 0);
}
/* Verify market's block number equals current block number */
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_FRESHNESS_CHECK), 0);
}
/* Verify cTokenCollateral market's block number equals current block number */
if (cTokenCollateral.accrualBlockNumber() != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.LIQUIDATE_COLLATERAL_FRESHNESS_CHECK), 0);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return (fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_LIQUIDATOR_IS_BORROWER), 0);
}
/* Fail if repayAmount = 0 */
if (repayAmount == 0) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_ZERO), 0);
}
/* Fail if repayAmount = -1 */
if (repayAmount == uint(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint repayBorrowError, uint actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint(Error.NO_ERROR)) {
return (fail(Error(repayBorrowError), FailureInfo.LIQUIDATE_REPAY_BORROW_FRESH_FAILED), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We calculate the number of collateral tokens that will be seized */
(uint amountSeizeError, uint seizeTokens) = comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint(Error.NO_ERROR), "LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED");
/* Revert if borrower collateral token balance < seizeTokens */
require(cTokenCollateral.balanceOf(borrower) >= seizeTokens, "LIQUIDATE_SEIZE_TOO_MUCH");
// If this is also the collateral, run seizeInternal to avoid re-entrancy, otherwise make an external call
uint seizeError;
if (address(cTokenCollateral) == address(this)) {
seizeError = seizeInternal(address(this), liquidator, borrower, seizeTokens);
} else {
seizeError = cTokenCollateral.seize(liquidator, borrower, seizeTokens);
}
/* Revert if seize tokens fails (since we cannot be sure of side effects) */
require(seizeError == uint(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
/* We call the defense hook */
comptroller.liquidateBorrowVerify(address(this), address(cTokenCollateral), liquidator, borrower, actualRepayAmount, seizeTokens);
return (uint(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another gToken during the process of liquidation.
* Its absolutely critical to use msg.sender as the borrowed gToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(address liquidator, address borrower, uint seizeTokens) external nonReentrant returns (uint) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another GToken.
* Its absolutely critical to use msg.sender as the seizer gToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed gToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) {
/* Fail if seize not allowed */
uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens);
if (allowed != 0) {
return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed);
}
/* Fail if borrower = liquidator */
if (borrower == liquidator) {
return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER);
}
MathError mathErr;
uint borrowerTokensNew;
uint liquidatorTokensNew;
/*
* We calculate the new borrower and liquidator token balances, failing on underflow/overflow:
* borrowerTokensNew = accountTokens[borrower] - seizeTokens
* liquidatorTokensNew = accountTokens[liquidator] + seizeTokens
*/
(mathErr, borrowerTokensNew) = subUInt(accountTokens[borrower], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/* We write the previously calculated values into storage */
accountTokens[borrower] = borrowerTokensNew;
accountTokens[liquidator] = liquidatorTokensNew;
/* Emit a Transfer event */
emit Transfer(borrower, liquidator, seizeTokens);
/* We call the defense hook */
comptroller.seizeVerify(address(this), seizerToken, liquidator, borrower, seizeTokens);
return uint(Error.NO_ERROR);
}
/*** Admin Functions ***/
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() external returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets a new comptroller for the market
* @dev Admin function to set a new comptroller
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setComptroller(ComptrollerInterface newComptroller) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COMPTROLLER_OWNER_CHECK);
}
ComptrollerInterface oldComptroller = comptroller;
// Ensure invoke comptroller.isComptroller() returns true
require(newComptroller.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
comptroller = newComptroller;
// Emit NewComptroller(oldComptroller, newComptroller)
emit NewComptroller(oldComptroller, newComptroller);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and sets a new reserve factor for the protocol using _setReserveFactorFresh
* @dev Admin function to accrue interest and set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactor(uint newReserveFactorMantissa) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reserve factor change failed.
return fail(Error(error), FailureInfo.SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED);
}
// _setReserveFactorFresh emits reserve-factor-specific logs on errors, so we don't need to.
return _setReserveFactorFresh(newReserveFactorMantissa);
}
/**
* @notice Sets a new reserve factor for the protocol (*requires fresh interest accrual)
* @dev Admin function to set a new reserve factor
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setReserveFactorFresh(uint newReserveFactorMantissa) internal returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_RESERVE_FACTOR_ADMIN_CHECK);
}
// Verify market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_RESERVE_FACTOR_FRESH_CHECK);
}
// Check newReserveFactor ≤ maxReserveFactor
if (newReserveFactorMantissa > reserveFactorMaxMantissa) {
return fail(Error.BAD_INPUT, FailureInfo.SET_RESERVE_FACTOR_BOUNDS_CHECK);
}
uint oldReserveFactorMantissa = reserveFactorMantissa;
reserveFactorMantissa = newReserveFactorMantissa;
emit NewReserveFactor(oldReserveFactorMantissa, newReserveFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Accrues interest and reduces reserves by transferring from msg.sender
* @param addAmount Amount of addition to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReservesInternal(uint addAmount) internal nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.ADD_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _addReservesFresh emits reserve-addition-specific logs on errors, so we don't need to.
(error, ) = _addReservesFresh(addAmount);
return error;
}
/**
* @notice Add reserves by transferring from caller
* @dev Requires fresh interest accrual
* @param addAmount Amount of addition to reserves
* @return (uint, uint) An error code (0=success, otherwise a failure (see ErrorReporter.sol for details)) and the actual amount added, net token fees
*/
function _addReservesFresh(uint addAmount) internal returns (uint, uint) {
// totalReserves + actualAddAmount
uint totalReservesNew;
uint actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The gToken must handle variations between ERC-20 and ETH underlying.
* On success, the gToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves unexpected overflow");
// Store reserves[n+1] = reserves[n] + actualAddAmount
totalReserves = totalReservesNew;
/* Emit NewReserves(admin, actualAddAmount, reserves[n+1]) */
emit ReservesAdded(msg.sender, actualAddAmount, totalReservesNew);
/* Return (NO_ERROR, actualAddAmount) */
return (uint(Error.NO_ERROR), actualAddAmount);
}
/**
* @notice Accrues interest and reduces reserves by transferring to admin
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReserves(uint reduceAmount) external nonReentrant returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted reduce reserves failed.
return fail(Error(error), FailureInfo.REDUCE_RESERVES_ACCRUE_INTEREST_FAILED);
}
// _reduceReservesFresh emits reserve-reduction-specific logs on errors, so we don't need to.
return _reduceReservesFresh(reduceAmount);
}
/**
* @notice Reduces reserves by transferring to admin
* @dev Requires fresh interest accrual
* @param reduceAmount Amount of reduction to reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _reduceReservesFresh(uint reduceAmount) internal returns (uint) {
// totalReserves - reduceAmount
uint totalReservesNew;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.REDUCE_RESERVES_ADMIN_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.REDUCE_RESERVES_FRESH_CHECK);
}
// Fail gracefully if protocol has insufficient underlying cash
if (getCashPrior() < reduceAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDUCE_RESERVES_CASH_NOT_AVAILABLE);
}
// Check reduceAmount ≤ reserves[n] (totalReserves)
if (reduceAmount > totalReserves) {
return fail(Error.BAD_INPUT, FailureInfo.REDUCE_RESERVES_VALIDATION);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
totalReservesNew = totalReserves - reduceAmount;
// We checked reduceAmount <= totalReserves above, so this should never revert.
require(totalReservesNew <= totalReserves, "reduce reserves unexpected underflow");
// Store reserves[n+1] = reserves[n] - reduceAmount
totalReserves = totalReservesNew;
// doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
doTransferOut(admin, reduceAmount);
emit ReservesReduced(admin, reduceAmount, totalReservesNew);
return uint(Error.NO_ERROR);
}
/**
* @notice accrues interest and updates the interest rate model using _setInterestRateModelFresh
* @dev Admin function to accrue interest and update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModel(InterestRateModel newInterestRateModel) public returns (uint) {
uint error = accrueInterest();
if (error != uint(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but on top of that we want to log the fact that an attempted change of interest rate model failed
return fail(Error(error), FailureInfo.SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED);
}
// _setInterestRateModelFresh emits interest-rate-model-update-specific logs on errors, so we don't need to.
return _setInterestRateModelFresh(newInterestRateModel);
}
/**
* @notice updates the interest rate model (*requires fresh interest accrual)
* @dev Admin function to update the interest rate model
* @param newInterestRateModel the new interest rate model to use
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setInterestRateModelFresh(InterestRateModel newInterestRateModel) internal returns (uint) {
// Used to store old model for use in the event that is emitted on success
InterestRateModel oldInterestRateModel;
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return fail(Error.MARKET_NOT_FRESH, FailureInfo.SET_INTEREST_RATE_MODEL_FRESH_CHECK);
}
// Track the market's current interest rate model
oldInterestRateModel = interestRateModel;
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
interestRateModel = newInterestRateModel;
// Emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel)
emit NewMarketInterestRateModel(oldInterestRateModel, newInterestRateModel);
return uint(Error.NO_ERROR);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying owned by this contract
*/
function getCashPrior() internal view returns (uint);
/**
* @dev Performs a transfer in, reverting upon failure. Returns the amount actually transferred to the protocol, in case of a fee.
* This may revert due to insufficient balance or insufficient allowance.
*/
function doTransferIn(address from, uint amount) internal returns (uint);
/**
* @dev Performs a transfer out, ideally returning an explanatory error code upon failure tather than reverting.
* If caller has not called checked protocol's balance, may revert due to insufficient cash held in the contract.
* If caller has checked protocol's balance, and verified it is >= amount, this should not revert in normal conditions.
*/
function doTransferOut(address payable to, uint amount) internal;
/*** Reentrancy Guard ***/
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
*/
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
}
// File: contracts/PriceOracle.sol
pragma solidity 0.5.17;
contract PriceOracle {
/// @notice Indicator that this is a PriceOracle contract (for inspection)
bool public constant isPriceOracle = true;
/**
* @notice Get the underlying price of a gToken asset
* @param gToken The gToken to get the underlying price of
* @return The underlying asset price mantissa (scaled by 1e18).
* Zero means the price is unavailable.
*/
function getUnderlyingPrice(GToken gToken) external view returns (uint);
/**
* Get underlying market price for web app
*/
function getMarketPrice(string calldata symbol) external view returns (uint);
/**
* Get underlying oracle price for web app
*/
function price(string calldata symbol) external view returns (uint);
}
// File: contracts/ComptrollerStorage.sol
pragma solidity 0.5.17;
contract UnitrollerAdminStorage {
/**
* @notice Administrator for this contract
*/
address public admin;
/**
* @notice Pending administrator for this contract
*/
address public pendingAdmin;
/**
* @notice Active brains of Supervisor
*/
address public comptrollerImplementation;
/**
* @notice Pending brains of Supervisor
*/
address public pendingComptrollerImplementation;
}
contract ComptrollerV1Storage is UnitrollerAdminStorage {
/**
* @notice Oracle which gives the price of any given asset
*/
PriceOracle public oracle;
/**
* @notice Multiplier used to calculate the maximum repayAmount when liquidating a borrow
*/
uint public closeFactorMantissa;
/**
* @notice Multiplier representing the discount on collateral that a liquidator receives
*/
uint public liquidationIncentiveMantissa;
/**
* @notice Max number of assets a single account can participate in (borrow or use as collateral)
*/
uint public maxAssets;
/**
* @notice Per-account mapping of "assets you are in", capped by maxAssets
*/
mapping(address => GToken[]) public accountAssets;
}
contract ComptrollerV2Storage is ComptrollerV1Storage {
struct Market {
/// @notice Whether or not this market is listed
bool isListed;
/**
* @notice Multiplier representing the most one can borrow against their collateral in this market.
* For instance, 0.9 to allow borrowing 90% of collateral value.
* Must be between 0 and 1, and stored as a mantissa.
*/
uint collateralFactorMantissa;
/// @notice Per-market mapping of "accounts in this asset"
mapping(address => bool) accountMembership;
/// @notice Whether or not this market receives COMP
bool isComped;
}
/**
* @notice Official mapping of cTokens -> Market metadata
* @dev Used e.g. to determine if a market is supported
*/
mapping(address => Market) public markets;
/**
* @notice The Pause Guardian can pause certain actions as a safety mechanism.
* Actions which allow users to remove their own assets cannot be paused.
* Liquidation / seizing / transfer can only be paused globally, not by market.
*/
address public pauseGuardian;
bool public _mintGuardianPaused;
bool public _borrowGuardianPaused;
bool public transferGuardianPaused;
bool public seizeGuardianPaused;
mapping(address => bool) public mintGuardianPaused;
mapping(address => bool) public borrowGuardianPaused;
}
contract ComptrollerV3Storage is ComptrollerV2Storage {
/// @notice A list of all markets
GToken[] public allMarkets;
}
// File: contracts/Comptroller.sol
pragma solidity 0.5.17;
/**
* @title Comptroller Contract
*/
contract Comptroller is ComptrollerV3Storage, ComptrollerInterface, ComptrollerErrorReporter, Exponential {
/// @notice Emitted when an admin supports a market
event MarketListed(GToken gToken);
/// @notice Emitted when an account enters a market
event MarketEntered(GToken gToken, address account);
/// @notice Emitted when an account exits a market
event MarketExited(GToken gToken, address account);
/// @notice Emitted when close factor is changed by admin
event NewCloseFactor(uint oldCloseFactorMantissa, uint newCloseFactorMantissa);
/// @notice Emitted when a collateral factor is changed by admin
event NewCollateralFactor(GToken gToken, uint oldCollateralFactorMantissa, uint newCollateralFactorMantissa);
/// @notice Emitted when liquidation incentive is changed by admin
event NewLiquidationIncentive(uint oldLiquidationIncentiveMantissa, uint newLiquidationIncentiveMantissa);
/// @notice Emitted when maxAssets is changed by admin
event NewMaxAssets(uint oldMaxAssets, uint newMaxAssets);
/// @notice Emitted when price oracle is changed
event NewPriceOracle(PriceOracle oldPriceOracle, PriceOracle newPriceOracle);
/// @notice Emitted when pause guardian is changed
event NewPauseGuardian(address oldPauseGuardian, address newPauseGuardian);
/// @notice Emitted when an action is paused globally
event ActionGlobalPaused(string action, bool pauseState);
/// @notice Emitted when an action is paused on a market
event ActionMarketPaused(GToken gToken, string action, bool pauseState);
/// @notice Emitted when market comped status is changed
event MarketComped(GToken gToken, bool isComped);
/// @notice Emitted when pendingAdmin is changed
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/// @notice Emitted when pendingAdmin is accepted, which means admin is updated
event NewAdmin(address oldAdmin, address newAdmin);
// closeFactorMantissa must be strictly greater than this value
uint internal constant closeFactorMinMantissa = 0.05e18; // 0.05
// closeFactorMantissa must not exceed this value
uint internal constant closeFactorMaxMantissa = 0.9e18; // 0.9
// No collateralFactorMantissa may exceed this value
uint internal constant collateralFactorMaxMantissa = 0.9e18; // 0.9
// liquidationIncentiveMantissa must be no less than this value
uint internal constant liquidationIncentiveMinMantissa = 1.0e18; // 1.0
// liquidationIncentiveMantissa must be no greater than this value
uint internal constant liquidationIncentiveMaxMantissa = 1.5e18; // 1.5
constructor() public {
admin = msg.sender;
}
/**
* @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @dev Admin function to begin change of admin. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer.
* @param newPendingAdmin New pending admin.
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPendingAdmin(address newPendingAdmin) public returns (uint) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
// Save current value, if any, for inclusion in log
address oldPendingAdmin = pendingAdmin;
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
// Emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin)
emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin);
return uint(Error.NO_ERROR);
}
/**
* @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin
* @dev Admin function for pending admin to accept role and update admin
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _acceptAdmin() public returns (uint) {
// Check caller is pendingAdmin and pendingAdmin ≠ address(0)
if (msg.sender != pendingAdmin || msg.sender == address(0)) {
return fail(Error.UNAUTHORIZED, FailureInfo.ACCEPT_ADMIN_PENDING_ADMIN_CHECK);
}
// Save current values for inclusion in log
address oldAdmin = admin;
address oldPendingAdmin = pendingAdmin;
// Store admin with value pendingAdmin
admin = pendingAdmin;
// Clear the pending value
pendingAdmin = address(0);
emit NewAdmin(oldAdmin, admin);
emit NewPendingAdmin(oldPendingAdmin, pendingAdmin);
return uint(Error.NO_ERROR);
}
/*** Assets You Are In ***/
/**
* @notice Returns the assets an account has entered
* @param account The address of the account to pull assets for
* @return A dynamic list with the assets the account has entered
*/
function getAssetsIn(address account) external view returns (GToken[] memory) {
GToken[] memory assetsIn = accountAssets[account];
return assetsIn;
}
/**
* @notice Returns whether the given account is entered in the given asset
* @param account The address of the account to check
* @param gToken The gToken to check
* @return True if the account is in the asset, otherwise false.
*/
function checkMembership(address account, GToken gToken) external view returns (bool) {
return markets[address(gToken)].accountMembership[account];
}
/**
* @notice Add assets to be included in account liquidity calculation
* @param gTokens The list of addresses of the gToken markets to be enabled
* @return Success indicator for whether each corresponding market was entered
*/
function enterMarkets(address[] memory gTokens) public returns (uint[] memory) {
uint len = gTokens.length;
uint[] memory results = new uint[](len);
for (uint i = 0; i < len; i++) {
GToken gToken = GToken(gTokens[i]);
results[i] = uint(addToMarketInternal(gToken, msg.sender));
}
return results;
}
/**
* @notice Add the market to the borrower's "assets in" for liquidity calculations
* @param gToken The market to enter
* @param borrower The address of the account to modify
* @return Success indicator for whether the market was entered
*/
function addToMarketInternal(GToken gToken, address borrower) internal returns (Error) {
Market storage marketToJoin = markets[address(gToken)];
if (!marketToJoin.isListed) {
// market is not listed, cannot join
return Error.MARKET_NOT_LISTED;
}
if (marketToJoin.accountMembership[borrower] == true) {
// already joined
return Error.NO_ERROR;
}
if (accountAssets[borrower].length >= maxAssets) {
// no space, cannot join
return Error.TOO_MANY_ASSETS;
}
// survived the gauntlet, add to list
// NOTE: we store these somewhat redundantly as a significant optimization
// this avoids having to iterate through the list for the most common use cases
// that is, only when we need to perform liquidity checks
// and not whenever we want to check if an account is in a particular market
marketToJoin.accountMembership[borrower] = true;
accountAssets[borrower].push(gToken);
emit MarketEntered(gToken, borrower);
return Error.NO_ERROR;
}
/**
* @notice Removes asset from sender's account liquidity calculation
* @dev Sender must not have an outstanding borrow balance in the asset,
* or be providing necessary collateral for an outstanding borrow.
* @param gTokenAddress The address of the asset to be removed
* @return Whether or not the account successfully exited the market
*/
function exitMarket(address gTokenAddress) external returns (uint) {
GToken gToken = GToken(gTokenAddress);
/* Get sender tokensHeld and amountOwed underlying from the gToken */
(uint oErr, uint tokensHeld, uint amountOwed, ) = gToken.getAccountSnapshot(msg.sender);
require(oErr == 0, "exitMarket: getAccountSnapshot failed"); // semi-opaque error code
/* Fail if the sender has a borrow balance */
if (amountOwed != 0) {
return fail(Error.NONZERO_BORROW_BALANCE, FailureInfo.EXIT_MARKET_BALANCE_OWED);
}
/* Fail if the sender is not permitted to redeem all of their tokens */
uint allowed = redeemAllowedInternal(gTokenAddress, msg.sender, tokensHeld);
if (allowed != 0) {
return failOpaque(Error.REJECTION, FailureInfo.EXIT_MARKET_REJECTION, allowed);
}
Market storage marketToExit = markets[address(gToken)];
/* Return true if the sender is not already ‘in’ the market */
if (!marketToExit.accountMembership[msg.sender]) {
return uint(Error.NO_ERROR);
}
/* Set gToken account membership to false */
delete marketToExit.accountMembership[msg.sender];
/* Delete gToken from the account’s list of assets */
// load into memory for faster iteration
GToken[] memory userAssetList = accountAssets[msg.sender];
uint len = userAssetList.length;
uint assetIndex = len;
for (uint i = 0; i < len; i++) {
if (userAssetList[i] == gToken) {
assetIndex = i;
break;
}
}
// We *must* have found the asset in the list or our redundant data structure is broken
assert(assetIndex < len);
// copy last item in list to location of item to be removed, reduce length by 1
GToken[] storage storedList = accountAssets[msg.sender];
storedList[assetIndex] = storedList[storedList.length - 1];
storedList.length--;
emit MarketExited(gToken, msg.sender);
return uint(Error.NO_ERROR);
}
/*** Policy Hooks ***/
/**
* @notice Checks if the account should be allowed to mint tokens in the given market
* @param gToken The market to verify the mint against
* @param minter The account which would get the minted tokens
* @param mintAmount The amount of underlying being supplied to the market in exchange for tokens
* @return 0 if the mint is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function mintAllowed(address gToken, address minter, uint mintAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!mintGuardianPaused[gToken], "mint is paused");
// Shh - currently unused
minter;
mintAmount;
if (!markets[gToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates mint and reverts on rejection. May emit logs.
* @param gToken Asset being minted
* @param minter The address minting the tokens
* @param actualMintAmount The amount of the underlying asset being minted
* @param mintTokens The number of tokens being minted
*/
function mintVerify(address gToken, address minter, uint actualMintAmount, uint mintTokens) external {
// Shh - currently unused
gToken;
minter;
actualMintAmount;
mintTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to redeem tokens in the given market
* @param gToken The market to verify the redeem against
* @param redeemer The account which would redeem the tokens
* @param redeemTokens The number of gTokens to exchange for the underlying asset in the market
* @return 0 if the redeem is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function redeemAllowed(address gToken, address redeemer, uint redeemTokens) external returns (uint) {
uint allowed = redeemAllowedInternal(gToken, redeemer, redeemTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
return uint(Error.NO_ERROR);
}
function redeemAllowedInternal(address gToken, address redeemer, uint redeemTokens) internal view returns (uint) {
if (!markets[gToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* If the redeemer is not 'in' the market, then we can bypass the liquidity check */
if (!markets[gToken].accountMembership[redeemer]) {
return uint(Error.NO_ERROR);
}
/* Otherwise, perform a hypothetical liquidity check to guard against shortfall */
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(redeemer, GToken(gToken), redeemTokens, 0);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates redeem and reverts on rejection. May emit logs.
* @param gToken Asset being redeemed
* @param redeemer The address redeeming the tokens
* @param redeemAmount The amount of the underlying asset being redeemed
* @param redeemTokens The number of tokens being redeemed
*/
function redeemVerify(address gToken, address redeemer, uint redeemAmount, uint redeemTokens) external {
// Shh - currently unused
gToken;
redeemer;
// Require tokens is zero or amount is also zero
if (redeemTokens == 0 && redeemAmount > 0) {
revert("redeemTokens zero");
}
}
/**
* @notice Checks if the account should be allowed to borrow the underlying asset of the given market
* @param gToken The market to verify the borrow against
* @param borrower The account which would borrow the asset
* @param borrowAmount The amount of underlying the account would borrow
* @return 0 if the borrow is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function borrowAllowed(address gToken, address borrower, uint borrowAmount) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!borrowGuardianPaused[gToken], "borrow is paused");
if (!markets[gToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (!markets[gToken].accountMembership[borrower]) {
// only gTokens may call borrowAllowed if borrower not in market
require(msg.sender == gToken, "sender must be gToken");
// attempt to add borrower to the market
Error err = addToMarketInternal(GToken(msg.sender), borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
// it should be impossible to break the important invariant
assert(markets[gToken].accountMembership[borrower]);
}
if (oracle.getUnderlyingPrice(GToken(gToken)) == 0) {
return uint(Error.PRICE_ERROR);
}
(Error err, , uint shortfall) = getHypotheticalAccountLiquidityInternal(borrower, GToken(gToken), 0, borrowAmount);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall > 0) {
return uint(Error.INSUFFICIENT_LIQUIDITY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates borrow and reverts on rejection. May emit logs.
* @param gToken Asset whose underlying is being borrowed
* @param borrower The address borrowing the underlying
* @param borrowAmount The amount of the underlying asset requested to borrow
*/
function borrowVerify(address gToken, address borrower, uint borrowAmount) external {
// Shh - currently unused
gToken;
borrower;
borrowAmount;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to repay a borrow in the given market
* @param gToken The market to verify the repay against
* @param payer The account which would repay the asset
* @param borrower The account which would borrowed the asset
* @param repayAmount The amount of the underlying asset the account would repay
* @return 0 if the repay is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function repayBorrowAllowed(
address gToken,
address payer,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
payer;
borrower;
repayAmount;
if (!markets[gToken].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates repayBorrow and reverts on rejection. May emit logs.
* @param gToken Asset being repaid
* @param payer The address repaying the borrow
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function repayBorrowVerify(
address gToken,
address payer,
address borrower,
uint actualRepayAmount,
uint borrowerIndex) external {
// Shh - currently unused
gToken;
payer;
borrower;
actualRepayAmount;
borrowerIndex;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the liquidation should be allowed to occur
* @param gTokenBorrowed Asset which was borrowed by the borrower
* @param gTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param repayAmount The amount of underlying being repaid
*/
function liquidateBorrowAllowed(
address gTokenBorrowed,
address gTokenCollateral,
address liquidator,
address borrower,
uint repayAmount) external returns (uint) {
// Shh - currently unused
liquidator;
if (!markets[gTokenBorrowed].isListed || !markets[gTokenCollateral].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
/* The borrower must have shortfall in order to be liquidatable */
(Error err, , uint shortfall) = getAccountLiquidityInternal(borrower);
if (err != Error.NO_ERROR) {
return uint(err);
}
if (shortfall == 0) {
return uint(Error.INSUFFICIENT_SHORTFALL);
}
/* The liquidator may not repay more than what is allowed by the closeFactor */
uint borrowBalance = GToken(gTokenBorrowed).borrowBalanceStored(borrower);
(MathError mathErr, uint maxClose) = mulScalarTruncate(Exp({mantissa: closeFactorMantissa}), borrowBalance);
if (mathErr != MathError.NO_ERROR) {
return uint(Error.MATH_ERROR);
}
if (repayAmount > maxClose) {
return uint(Error.TOO_MUCH_REPAY);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates liquidateBorrow and reverts on rejection. May emit logs.
* @param gTokenBorrowed Asset which was borrowed by the borrower
* @param gTokenCollateral Asset which was used as collateral and will be seized
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param actualRepayAmount The amount of underlying being repaid
*/
function liquidateBorrowVerify(
address gTokenBorrowed,
address gTokenCollateral,
address liquidator,
address borrower,
uint actualRepayAmount,
uint seizeTokens) external {
// Shh - currently unused
gTokenBorrowed;
gTokenCollateral;
liquidator;
borrower;
actualRepayAmount;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the seizing of assets should be allowed to occur
* @param gTokenCollateral Asset which was used as collateral and will be seized
* @param gTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeAllowed(
address gTokenCollateral,
address gTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!seizeGuardianPaused, "seize is paused");
// Shh - currently unused
seizeTokens;
if (!markets[gTokenCollateral].isListed || !markets[gTokenBorrowed].isListed) {
return uint(Error.MARKET_NOT_LISTED);
}
if (GToken(gTokenCollateral).comptroller() != GToken(gTokenBorrowed).comptroller()) {
return uint(Error.COMPTROLLER_MISMATCH);
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates seize and reverts on rejection. May emit logs.
* @param gTokenCollateral Asset which was used as collateral and will be seized
* @param gTokenBorrowed Asset which was borrowed by the borrower
* @param liquidator The address repaying the borrow and seizing the collateral
* @param borrower The address of the borrower
* @param seizeTokens The number of collateral tokens to seize
*/
function seizeVerify(
address gTokenCollateral,
address gTokenBorrowed,
address liquidator,
address borrower,
uint seizeTokens) external {
// Shh - currently unused
gTokenCollateral;
gTokenBorrowed;
liquidator;
borrower;
seizeTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/**
* @notice Checks if the account should be allowed to transfer tokens in the given market
* @param gToken The market to verify the transfer against
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of gTokens to transfer
* @return 0 if the transfer is allowed, otherwise a semi-opaque error code (See ErrorReporter.sol)
*/
function transferAllowed(address gToken, address src, address dst, uint transferTokens) external returns (uint) {
// Pausing is a very serious situation - we revert to sound the alarms
require(!transferGuardianPaused, "transfer is paused");
// Currently the only consideration is whether or not
// the src is allowed to redeem this many tokens
uint allowed = redeemAllowedInternal(gToken, src, transferTokens);
if (allowed != uint(Error.NO_ERROR)) {
return allowed;
}
return uint(Error.NO_ERROR);
}
/**
* @notice Validates transfer and reverts on rejection. May emit logs.
* @param gToken Asset being transferred
* @param src The account which sources the tokens
* @param dst The account which receives the tokens
* @param transferTokens The number of gTokens to transfer
*/
function transferVerify(address gToken, address src, address dst, uint transferTokens) external {
// Shh - currently unused
gToken;
src;
dst;
transferTokens;
// Shh - we don't ever want this hook to be marked pure
if (false) {
maxAssets = maxAssets;
}
}
/*** Liquidity/Liquidation Calculations ***/
/**
* @dev Local vars for avoiding stack-depth limits in calculating account liquidity.
* Note that `gTokenBalance` is the number of gTokens the account owns in the market,
* whereas `borrowBalance` is the amount of underlying that the account has borrowed.
*/
struct AccountLiquidityLocalVars {
uint sumCollateral;
uint sumBorrowPlusEffects;
uint gTokenBalance;
uint borrowBalance;
uint exchangeRateMantissa;
uint oraclePriceMantissa;
Exp collateralFactor;
Exp exchangeRate;
Exp oraclePrice;
Exp tokensToDenom;
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code (semi-opaque),
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidity(address account) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, GToken(0), 0, 0);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine the current account liquidity wrt collateral requirements
* @return (possible error code,
account liquidity in excess of collateral requirements,
* account shortfall below collateral requirements)
*/
function getAccountLiquidityInternal(address account) internal view returns (Error, uint, uint) {
return getHypotheticalAccountLiquidityInternal(account, GToken(0), 0, 0);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param gTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @return (possible error code (semi-opaque),
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidity(
address account,
address gTokenModify,
uint redeemTokens,
uint borrowAmount) public view returns (uint, uint, uint) {
(Error err, uint liquidity, uint shortfall) = getHypotheticalAccountLiquidityInternal(account, GToken(gTokenModify), redeemTokens, borrowAmount);
return (uint(err), liquidity, shortfall);
}
/**
* @notice Determine what the account liquidity would be if the given amounts were redeemed/borrowed
* @param gTokenModify The market to hypothetically redeem/borrow in
* @param account The account to determine liquidity for
* @param redeemTokens The number of tokens to hypothetically redeem
* @param borrowAmount The amount of underlying to hypothetically borrow
* @dev Note that we calculate the exchangeRateStored for each collateral gToken using stored data,
* without calculating accumulated interest.
* @return (possible error code,
hypothetical account liquidity in excess of collateral requirements,
* hypothetical account shortfall below collateral requirements)
*/
function getHypotheticalAccountLiquidityInternal(
address account,
GToken gTokenModify,
uint redeemTokens,
uint borrowAmount) internal view returns (Error, uint, uint) {
AccountLiquidityLocalVars memory vars; // Holds all our calculation results
uint oErr;
MathError mErr;
// For each asset the account is in
GToken[] memory assets = accountAssets[account];
for (uint i = 0; i < assets.length; i++) {
GToken asset = assets[i];
// Read the balances and exchange rate from the gToken
(oErr, vars.gTokenBalance, vars.borrowBalance, vars.exchangeRateMantissa) = asset.getAccountSnapshot(account);
if (oErr != 0) { // semi-opaque error code, we assume NO_ERROR == 0 is invariant between upgrades
return (Error.SNAPSHOT_ERROR, 0, 0);
}
vars.collateralFactor = Exp({mantissa: markets[address(asset)].collateralFactorMantissa});
vars.exchangeRate = Exp({mantissa: vars.exchangeRateMantissa});
// Get the normalized price of the asset
vars.oraclePriceMantissa = oracle.getUnderlyingPrice(asset);
if (vars.oraclePriceMantissa == 0) {
return (Error.PRICE_ERROR, 0, 0);
}
vars.oraclePrice = Exp({mantissa: vars.oraclePriceMantissa});
// Pre-compute a conversion factor from tokens -> ether (normalized price value)
(mErr, vars.tokensToDenom) = mulExp3(vars.collateralFactor, vars.exchangeRate, vars.oraclePrice);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumCollateral += tokensToDenom * gTokenBalance
(mErr, vars.sumCollateral) = mulScalarTruncateAddUInt(vars.tokensToDenom, vars.gTokenBalance, vars.sumCollateral);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// sumBorrowPlusEffects += oraclePrice * borrowBalance
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, vars.borrowBalance, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// Calculate effects of interacting with gTokenModify
if (asset == gTokenModify) {
// redeem effect
// sumBorrowPlusEffects += tokensToDenom * redeemTokens
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.tokensToDenom, redeemTokens, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
// borrow effect
// sumBorrowPlusEffects += oraclePrice * borrowAmount
(mErr, vars.sumBorrowPlusEffects) = mulScalarTruncateAddUInt(vars.oraclePrice, borrowAmount, vars.sumBorrowPlusEffects);
if (mErr != MathError.NO_ERROR) {
return (Error.MATH_ERROR, 0, 0);
}
}
}
// These are safe, as the underflow condition is checked first
if (vars.sumCollateral > vars.sumBorrowPlusEffects) {
return (Error.NO_ERROR, vars.sumCollateral - vars.sumBorrowPlusEffects, 0);
} else {
return (Error.NO_ERROR, 0, vars.sumBorrowPlusEffects - vars.sumCollateral);
}
}
/**
* @notice Calculate number of tokens of collateral asset to seize given an underlying amount
* @dev Used in liquidation (called in gToken.liquidateBorrowFresh)
* @param gTokenBorrowed The address of the borrowed gToken
* @param gTokenCollateral The address of the collateral gToken
* @param actualRepayAmount The amount of gTokenBorrowed underlying to convert into gTokenCollateral tokens
* @return (errorCode, number of gTokenCollateral tokens to be seized in a liquidation)
*/
function liquidateCalculateSeizeTokens(address gTokenBorrowed, address gTokenCollateral, uint actualRepayAmount) external view returns (uint, uint) {
/* Read oracle prices for borrowed and collateral markets */
uint priceBorrowedMantissa = oracle.getUnderlyingPrice(GToken(gTokenBorrowed));
uint priceCollateralMantissa = oracle.getUnderlyingPrice(GToken(gTokenCollateral));
if (priceBorrowedMantissa == 0 || priceCollateralMantissa == 0) {
return (uint(Error.PRICE_ERROR), 0);
}
/*
* Get the exchange rate and calculate the number of collateral tokens to seize:
* seizeAmount = actualRepayAmount * liquidationIncentive * priceBorrowed / priceCollateral
* seizeTokens = seizeAmount / exchangeRate
* = actualRepayAmount * (liquidationIncentive * priceBorrowed) / (priceCollateral * exchangeRate)
*/
uint exchangeRateMantissa = GToken(gTokenCollateral).exchangeRateStored(); // Note: reverts on error
uint seizeTokens;
Exp memory numerator;
Exp memory denominator;
Exp memory ratio;
MathError mathErr;
(mathErr, numerator) = mulExp(liquidationIncentiveMantissa, priceBorrowedMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, denominator) = mulExp(priceCollateralMantissa, exchangeRateMantissa);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, ratio) = divExp(numerator, denominator);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
(mathErr, seizeTokens) = mulScalarTruncate(ratio, actualRepayAmount);
if (mathErr != MathError.NO_ERROR) {
return (uint(Error.MATH_ERROR), 0);
}
return (uint(Error.NO_ERROR), seizeTokens);
}
/*** Admin Functions ***/
/**
* @notice Sets a new price oracle for the comptroller
* @dev Admin function to set a new price oracle
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _setPriceOracle(PriceOracle newOracle) public returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PRICE_ORACLE_OWNER_CHECK);
}
// Track the old oracle for the comptroller
PriceOracle oldOracle = oracle;
// Set comptroller's oracle to newOracle
oracle = newOracle;
// Emit NewPriceOracle(oldOracle, newOracle)
emit NewPriceOracle(oldOracle, newOracle);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the closeFactor used when liquidating borrows
* @dev Admin function to set closeFactor
* @param newCloseFactorMantissa New close factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCloseFactor(uint newCloseFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_CLOSE_FACTOR_OWNER_CHECK);
}
Exp memory newCloseFactorExp = Exp({mantissa: newCloseFactorMantissa});
Exp memory lowLimit = Exp({mantissa: closeFactorMinMantissa});
if (lessThanOrEqualExp(newCloseFactorExp, lowLimit)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
Exp memory highLimit = Exp({mantissa: closeFactorMaxMantissa});
if (lessThanExp(highLimit, newCloseFactorExp)) {
return fail(Error.INVALID_CLOSE_FACTOR, FailureInfo.SET_CLOSE_FACTOR_VALIDATION);
}
uint oldCloseFactorMantissa = closeFactorMantissa;
closeFactorMantissa = newCloseFactorMantissa;
emit NewCloseFactor(oldCloseFactorMantissa, closeFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets the collateralFactor for a market
* @dev Admin function to set per-market collateralFactor
* @param gToken The market to set the factor on
* @param newCollateralFactorMantissa The new collateral factor, scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setCollateralFactor(GToken gToken, uint newCollateralFactorMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_COLLATERAL_FACTOR_OWNER_CHECK);
}
// Verify market is listed
Market storage market = markets[address(gToken)];
if (!market.isListed) {
return fail(Error.MARKET_NOT_LISTED, FailureInfo.SET_COLLATERAL_FACTOR_NO_EXISTS);
}
Exp memory newCollateralFactorExp = Exp({mantissa: newCollateralFactorMantissa});
// Check collateral factor <= 0.9
Exp memory highLimit = Exp({mantissa: collateralFactorMaxMantissa});
if (lessThanExp(highLimit, newCollateralFactorExp)) {
return fail(Error.INVALID_COLLATERAL_FACTOR, FailureInfo.SET_COLLATERAL_FACTOR_VALIDATION);
}
// If collateral factor != 0, fail if price == 0
if (newCollateralFactorMantissa != 0 && oracle.getUnderlyingPrice(gToken) == 0) {
return fail(Error.PRICE_ERROR, FailureInfo.SET_COLLATERAL_FACTOR_WITHOUT_PRICE);
}
// Set market's collateral factor to new collateral factor, remember old value
uint oldCollateralFactorMantissa = market.collateralFactorMantissa;
market.collateralFactorMantissa = newCollateralFactorMantissa;
// Emit event with asset, old collateral factor, and new collateral factor
emit NewCollateralFactor(gToken, oldCollateralFactorMantissa, newCollateralFactorMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets maxAssets which controls how many markets can be entered
* @dev Admin function to set maxAssets
* @param newMaxAssets New max assets
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setMaxAssets(uint newMaxAssets) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_MAX_ASSETS_OWNER_CHECK);
}
uint oldMaxAssets = maxAssets;
maxAssets = newMaxAssets;
emit NewMaxAssets(oldMaxAssets, newMaxAssets);
return uint(Error.NO_ERROR);
}
/**
* @notice Sets liquidationIncentive
* @dev Admin function to set liquidationIncentive
* @param newLiquidationIncentiveMantissa New liquidationIncentive scaled by 1e18
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setLiquidationIncentive(uint newLiquidationIncentiveMantissa) external returns (uint) {
// Check caller is admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_LIQUIDATION_INCENTIVE_OWNER_CHECK);
}
// Check de-scaled min <= newLiquidationIncentive <= max
Exp memory newLiquidationIncentive = Exp({mantissa: newLiquidationIncentiveMantissa});
Exp memory minLiquidationIncentive = Exp({mantissa: liquidationIncentiveMinMantissa});
if (lessThanExp(newLiquidationIncentive, minLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
Exp memory maxLiquidationIncentive = Exp({mantissa: liquidationIncentiveMaxMantissa});
if (lessThanExp(maxLiquidationIncentive, newLiquidationIncentive)) {
return fail(Error.INVALID_LIQUIDATION_INCENTIVE, FailureInfo.SET_LIQUIDATION_INCENTIVE_VALIDATION);
}
// Save current value for use in log
uint oldLiquidationIncentiveMantissa = liquidationIncentiveMantissa;
// Set liquidation incentive to new incentive
liquidationIncentiveMantissa = newLiquidationIncentiveMantissa;
// Emit event with old incentive, new incentive
emit NewLiquidationIncentive(oldLiquidationIncentiveMantissa, newLiquidationIncentiveMantissa);
return uint(Error.NO_ERROR);
}
/**
* @notice Add the market to the markets mapping and set it as listed
* @dev Admin function to set isListed and add support for the market
* @param gToken The address of the market (token) to list
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _supportMarket(GToken gToken) external returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SUPPORT_MARKET_OWNER_CHECK);
}
if (markets[address(gToken)].isListed) {
return fail(Error.MARKET_ALREADY_LISTED, FailureInfo.SUPPORT_MARKET_EXISTS);
}
gToken.isCToken(); // Sanity check to make sure its really a GToken
markets[address(gToken)] = Market({isListed: true, isComped: false, collateralFactorMantissa: 0});
_addMarketInternal(address(gToken));
emit MarketListed(gToken);
return uint(Error.NO_ERROR);
}
function _addMarketInternal(address gToken) internal {
for (uint i = 0; i < allMarkets.length; i ++) {
require(allMarkets[i] != GToken(gToken), "market already added");
}
allMarkets.push(GToken(gToken));
}
/**
* @notice Admin function to change the Pause Guardian
* @param newPauseGuardian The address of the new Pause Guardian
* @return uint 0=success, otherwise a failure. (See enum Error for details)
*/
function _setPauseGuardian(address newPauseGuardian) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PAUSE_GUARDIAN_OWNER_CHECK);
}
// Save current value for inclusion in log
address oldPauseGuardian = pauseGuardian;
// Store pauseGuardian with value newPauseGuardian
pauseGuardian = newPauseGuardian;
// Emit NewPauseGuardian(OldPauseGuardian, NewPauseGuardian)
emit NewPauseGuardian(oldPauseGuardian, pauseGuardian);
return uint(Error.NO_ERROR);
}
function _setMintPaused(GToken gToken, bool state) public returns (bool) {
require(markets[address(gToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
mintGuardianPaused[address(gToken)] = state;
emit ActionMarketPaused(gToken, "Mint", state);
return state;
}
function _setBorrowPaused(GToken gToken, bool state) public returns (bool) {
require(markets[address(gToken)].isListed, "cannot pause a market that is not listed");
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
borrowGuardianPaused[address(gToken)] = state;
emit ActionMarketPaused(gToken, "Borrow", state);
return state;
}
function _setTransferPaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
transferGuardianPaused = state;
emit ActionGlobalPaused("Transfer", state);
return state;
}
function _setSeizePaused(bool state) public returns (bool) {
require(msg.sender == pauseGuardian || msg.sender == admin, "only pause guardian and admin can pause");
require(msg.sender == admin || state == true, "only admin can unpause");
seizeGuardianPaused = state;
emit ActionGlobalPaused("Seize", state);
return state;
}
/*
function _become(Supervisor unitroller) public {
require(msg.sender == unitroller.admin(), "only unitroller admin can change brains");
require(unitroller._acceptImplementation() == 0, "change not authorized");
}
*/
/**
* @notice Checks caller is admin, or this contract is becoming the new implementation
*/
function adminOrInitializing() internal view returns (bool) {
return msg.sender == admin || msg.sender == comptrollerImplementation;
}
/**
* @notice Return all of the markets
* @dev The automatic getter may be used to access an individual market.
* @return The list of market addresses
*/
function getAllMarkets() public view returns (GToken[] memory) {
return allMarkets;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
}
|
. Admin function: change redeemFee. newRedeemFee newRedeemFee return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Check caller = admin
|
function _setRedeemFee(uint newRedeemFee) public returns (uint) {
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
require(newRedeemFee <= MAX_BORROW_REDEEM_FEE, "newRedeemFee is greater than MAX_BORROW_REDEEM_FEE");
emit NewBorrowFee(redeemFee, newRedeemFee);
redeemFee = newRedeemFee;
return uint(Error.NO_ERROR);
}
| 598,269
|
pragma solidity ^0.5.16;
import "./ERC20.sol";
// SushiBar is the mock contract for testing.
// Ref: https://etherscan.io/address/0x8798249c2E607446EfB7Ad49eC89dD1865Ff4272#code
contract SushiBar is StandardToken(0, "SushiBar", 18, "xSUSHI") {
using SafeMath for uint256;
ERC20 public sushi;
constructor(ERC20 _sushi) public {
sushi = _sushi;
}
function _mint(address _to, uint256 _amount) internal returns (bool) {
totalSupply = totalSupply.add(_amount);
balanceOf[_to] = balanceOf[_to].add(_amount);
return true;
}
function _burn(address _to, uint256 _amount) internal returns (bool) {
totalSupply = totalSupply.sub(_amount);
balanceOf[_to] = balanceOf[_to].sub(_amount);
return true;
}
// Enter the bar. Pay some SUSHIs. Earn some shares.
function enter(uint256 _amount) public {
uint256 totalSushi = sushi.balanceOf(address(this));
uint256 totalShares = totalSupply;
if (totalShares == 0 || totalSushi == 0) {
_mint(msg.sender, _amount);
} else {
uint256 what = _amount.mul(totalShares).div(totalSushi);
_mint(msg.sender, what);
}
sushi.transferFrom(msg.sender, address(this), _amount);
}
// Leave the bar. Claim back your SUSHIs.
function leave(uint256 _share) public {
uint256 totalShares = totalSupply;
uint256 what = _share.mul(sushi.balanceOf(address(this))).div(totalShares);
_burn(msg.sender, _share);
sushi.transfer(msg.sender, what);
}
}
|
Enter the bar. Pay some SUSHIs. Earn some shares.
|
function enter(uint256 _amount) public {
uint256 totalSushi = sushi.balanceOf(address(this));
uint256 totalShares = totalSupply;
if (totalShares == 0 || totalSushi == 0) {
_mint(msg.sender, _amount);
uint256 what = _amount.mul(totalShares).div(totalSushi);
_mint(msg.sender, what);
}
sushi.transferFrom(msg.sender, address(this), _amount);
}
| 1,052,055
|
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
/*
Copyright 2019 dYdX Trading Inc.
Copyright 2020, 2021 Empty Set Squad <emptysetsquad@protonmail.com>
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 Decimal
* @notice Library that defines a fixed-point number with 18 decimal places.
*
* audit-info: Extended from dYdX's Decimal library:
* https://github.com/dydxprotocol/solo/blob/master/contracts/protocol/lib/Decimal.sol
*/
library Decimal {
using SafeMath for uint256;
// ============ Constants ============
/**
* @notice Fixed-point base for Decimal.D256 values
*/
uint256 constant BASE = 10**18;
// ============ Structs ============
/**
* @notice Main struct to hold Decimal.D256 state
* @dev Represents the number value / BASE
*/
struct D256 {
/**
* @notice Underlying value of the Decimal.D256
*/
uint256 value;
}
// ============ Static Functions ============
/**
* @notice Returns a new Decimal.D256 struct initialized to represent 0.0
* @return Decimal.D256 representation of 0.0
*/
function zero()
internal
pure
returns (D256 memory)
{
return D256({ value: 0 });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent 1.0
* @return Decimal.D256 representation of 1.0
*/
function one()
internal
pure
returns (D256 memory)
{
return D256({ value: BASE });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent `a`
* @param a Integer to transform to Decimal.D256 type
* @return Decimal.D256 representation of integer`a`
*/
function from(
uint256 a
)
internal
pure
returns (D256 memory)
{
return D256({ value: a.mul(BASE) });
}
/**
* @notice Returns a new Decimal.D256 struct initialized to represent `a` / `b`
* @param a Numerator of ratio to transform to Decimal.D256 type
* @param b Denominator of ratio to transform to Decimal.D256 type
* @return Decimal.D256 representation of ratio `a` / `b`
*/
function ratio(
uint256 a,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(a, BASE, b) });
}
// ============ Self Functions ============
/**
* @notice Adds integer `b` to Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to add to `self`
* @return Resulting Decimal.D256
*/
function add(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.mul(BASE)) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE)) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @dev Reverts on underflow with reason `reason`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.mul(BASE), reason) });
}
/**
* @notice Subtracts integer `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Integer to subtract from `self`
* @return 0 on underflow, or the Resulting Decimal.D256
*/
function subOrZero(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
uint256 amount = b.mul(BASE);
return D256({ value: self.value > amount ? self.value.sub(amount) : 0 });
}
/**
* @notice Multiplies Decimal.D256 `self` by integer `b`
* @param self Original Decimal.D256 number
* @param b Integer to multiply `self` by
* @return Resulting Decimal.D256
*/
function mul(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.mul(b) });
}
/**
* @notice Divides Decimal.D256 `self` by integer `b`
* @param self Original Decimal.D256 number
* @param b Integer to divide `self` by
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b) });
}
/**
* @notice Divides Decimal.D256 `self` by integer `b`
* @dev Reverts on divide-by-zero with reason `reason`
* @param self Original Decimal.D256 number
* @param b Integer to divide `self` by
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
uint256 b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.div(b, reason) });
}
/**
* @notice Exponentiates Decimal.D256 `self` to the power of integer `b`
* @dev Not optimized - is only suitable to use with small exponents
* @param self Original Decimal.D256 number
* @param b Integer exponent
* @return Resulting Decimal.D256
*/
function pow(
D256 memory self,
uint256 b
)
internal
pure
returns (D256 memory)
{
if (b == 0) {
return from(1);
}
D256 memory temp = D256({ value: self.value });
for (uint256 i = 1; i < b; i++) {
temp = mul(temp, self);
}
return temp;
}
/**
* @notice Adds Decimal.D256 `b` to Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to add to `self`
* @return Resulting Decimal.D256
*/
function add(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.add(b.value) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @dev Reverts on underflow with reason `reason`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function sub(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value.sub(b.value, reason) });
}
/**
* @notice Subtracts Decimal.D256 `b` from Decimal.D256 `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to subtract from `self`
* @return 0 on underflow, or the Resulting Decimal.D256
*/
function subOrZero(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: self.value > b.value ? self.value.sub(b.value) : 0 });
}
/**
* @notice Multiplies Decimal.D256 `self` by Decimal.D256 `b`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to multiply `self` by
* @return Resulting Decimal.D256
*/
function mul(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, b.value, BASE) });
}
/**
* @notice Divides Decimal.D256 `self` by Decimal.D256 `b`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to divide `self` by
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
D256 memory b
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value) });
}
/**
* @notice Divides Decimal.D256 `self` by Decimal.D256 `b`
* @dev Reverts on divide-by-zero with reason `reason`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to divide `self` by
* @param reason Revert reason
* @return Resulting Decimal.D256
*/
function div(
D256 memory self,
D256 memory b,
string memory reason
)
internal
pure
returns (D256 memory)
{
return D256({ value: getPartial(self.value, BASE, b.value, reason) });
}
/**
* @notice Checks if `b` is equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is equal to `self`
*/
function equals(D256 memory self, D256 memory b) internal pure returns (bool) {
return self.value == b.value;
}
/**
* @notice Checks if `b` is greater than `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is greater than `self`
*/
function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 2;
}
/**
* @notice Checks if `b` is less than `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is less than `self`
*/
function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) == 0;
}
/**
* @notice Checks if `b` is greater than or equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is greater than or equal to `self`
*/
function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) > 0;
}
/**
* @notice Checks if `b` is less than or equal to `self`
* @param self Original Decimal.D256 number
* @param b Decimal.D256 to compare
* @return Whether `b` is less than or equal to `self`
*/
function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) {
return compareTo(self, b) < 2;
}
/**
* @notice Checks if `self` is equal to 0
* @param self Original Decimal.D256 number
* @return Whether `self` is equal to 0
*/
function isZero(D256 memory self) internal pure returns (bool) {
return self.value == 0;
}
/**
* @notice Truncates the decimal part of `self` and returns the integer value as a uint256
* @param self Original Decimal.D256 number
* @return Truncated Integer value as a uint256
*/
function asUint256(D256 memory self) internal pure returns (uint256) {
return self.value.div(BASE);
}
// ============ General Math ============
/**
* @notice Determines the minimum of `a` and `b`
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return Resulting minimum Decimal.D256
*/
function min(D256 memory a, D256 memory b) internal pure returns (Decimal.D256 memory) {
return lessThan(a, b) ? a : b;
}
/**
* @notice Determines the maximum of `a` and `b`
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return Resulting maximum Decimal.D256
*/
function max(D256 memory a, D256 memory b) internal pure returns (Decimal.D256 memory) {
return greaterThan(a, b) ? a : b;
}
// ============ Core Methods ============
/**
* @notice Multiplies `target` by ratio `numerator` / `denominator`
* @dev Internal only - helper
* @param target Original Integer number
* @param numerator Integer numerator of ratio
* @param denominator Integer denominator of ratio
* @return Resulting Decimal.D256 number
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator);
}
/**
* @notice Multiplies `target` by ratio `numerator` / `denominator`
* @dev Internal only - helper
* Reverts on divide-by-zero with reason `reason`
* @param target Original Integer number
* @param numerator Integer numerator of ratio
* @param denominator Integer denominator of ratio
* @param reason Revert reason
* @return Resulting Decimal.D256 number
*/
function getPartial(
uint256 target,
uint256 numerator,
uint256 denominator,
string memory reason
)
private
pure
returns (uint256)
{
return target.mul(numerator).div(denominator, reason);
}
/**
* @notice Compares Decimal.D256 `a` to Decimal.D256 `b`
* @dev Internal only - helper
* @param a First Decimal.D256 number to compare
* @param b Second Decimal.D256 number to compare
* @return 0 if a < b, 1 if a == b, 2 if a > b
*/
function compareTo(
D256 memory a,
D256 memory b
)
private
pure
returns (uint256)
{
if (a.value == b.value) {
return 1;
}
return a.value > b.value ? 2 : 0;
}
}
/*
Copyright 2020, 2021 Empty Set Squad <emptysetsquad@protonmail.com>
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 IManagedToken
* @notice Generic interface for ERC20 tokens that can be minted and burned by their owner
* @dev Used by Dollar and Stake in this protocol
*/
interface IManagedToken {
/**
* @notice Mints `amount` tokens to the {owner}
* @param amount Amount of token to mint
*/
function burn(uint256 amount) external;
/**
* @notice Burns `amount` tokens from the {owner}
* @param amount Amount of token to burn
*/
function mint(uint256 amount) external;
}
/**
* @title IGovToken
* @notice Generic interface for ERC20 tokens that have Compound-governance features
* @dev Used by Stake and other compatible reserve-held tokens
*/
interface IGovToken {
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external;
}
/**
* @title IReserve
* @notice Interface for the protocol reserve
*/
interface IReserve {
/**
* @notice The price that one ESD can currently be sold to the reserve for
* @dev Returned as a Decimal.D256
* Normalizes for decimals (e.g. 1.00 USDC == Decimal.one())
* @return Current ESD redemption price
*/
function redeemPrice() external view returns (Decimal.D256 memory);
}
interface IRegistry {
/**
* @notice USDC token contract
*/
function usdc() external view returns (address);
/**
* @notice Compound protocol cUSDC pool
*/
function cUsdc() external view returns (address);
/**
* @notice ESD stablecoin contract
*/
function dollar() external view returns (address);
/**
* @notice ESDS governance token contract
*/
function stake() external view returns (address);
/**
* @notice ESD reserve contract
*/
function reserve() external view returns (address);
/**
* @notice ESD governor contract
*/
function governor() external view returns (address);
/**
* @notice ESD timelock contract, owner for the protocol
*/
function timelock() external view returns (address);
/**
* @notice Migration contract to bride v1 assets with current system
*/
function migrator() external view returns (address);
/**
* @notice Registers a new address for USDC
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setUsdc(address newValue) external;
/**
* @notice Registers a new address for cUSDC
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setCUsdc(address newValue) external;
/**
* @notice Registers a new address for ESD
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setDollar(address newValue) external;
/**
* @notice Registers a new address for ESDS
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setStake(address newValue) external;
/**
* @notice Registers a new address for the reserve
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setReserve(address newValue) external;
/**
* @notice Registers a new address for the governor
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setGovernor(address newValue) external;
/**
* @notice Registers a new address for the timelock
* @dev Owner only - governance hook
* Does not automatically update the owner of all owned protocol contracts
* @param newValue New address to register
*/
function setTimelock(address newValue) external;
/**
* @notice Registers a new address for the v1 migration contract
* @dev Owner only - governance hook
* @param newValue New address to register
*/
function setMigrator(address newValue) external;
}
/*
Copyright 2021 Empty Set Squad <emptysetsquad@protonmail.com>
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 TimeUtils
* @notice Library that accompanies Decimal to convert unix time into Decimal.D256 values
*/
library TimeUtils {
/**
* @notice Number of seconds in a single day
*/
uint256 private constant SECONDS_IN_DAY = 86400;
/**
* @notice Converts an integer number of seconds to a Decimal.D256 amount of days
* @param s Number of seconds to convert
* @return Equivalent amount of days as a Decimal.D256
*/
function secondsToDays(uint256 s) internal pure returns (Decimal.D256 memory) {
return Decimal.ratio(s, SECONDS_IN_DAY);
}
}
/*
Copyright 2021 Empty Set Squad <emptysetsquad@protonmail.com>
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 Implementation
* @notice Common functions and accessors across upgradeable, ownable contracts
*/
contract Implementation {
/**
* @notice Emitted when {owner} is updated with `newOwner`
*/
event OwnerUpdate(address newOwner);
/**
* @notice Emitted when {registry} is updated with `newRegistry`
*/
event RegistryUpdate(address newRegistry);
/**
* @dev Storage slot with the address of the current implementation
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1
*/
bytes32 private constant IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Storage slot with the admin of the contract
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1
*/
bytes32 private constant ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant OWNER_SLOT = keccak256("emptyset.v2.implementation.owner");
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant REGISTRY_SLOT = keccak256("emptyset.v2.implementation.registry");
/**
* @notice Storage slot with the owner of the contract
*/
bytes32 private constant NOT_ENTERED_SLOT = keccak256("emptyset.v2.implementation.notEntered");
// UPGRADEABILITY
/**
* @notice Returns the current implementation
* @return Address of the current implementation
*/
function implementation() external view returns (address impl) {
bytes32 slot = IMPLEMENTATION_SLOT;
assembly {
impl := sload(slot)
}
}
/**
* @notice Returns the current proxy admin contract
* @return Address of the current proxy admin contract
*/
function admin() external view returns (address adm) {
bytes32 slot = ADMIN_SLOT;
assembly {
adm := sload(slot)
}
}
// REGISTRY
/**
* @notice Updates the registry contract
* @dev Owner only - governance hook
* If registry is already set, the new registry's timelock must match the current's
* @param newRegistry New registry contract
*/
function setRegistry(address newRegistry) external onlyOwner {
IRegistry registry = registry();
// New registry must have identical owner
require(newRegistry != address(0), "Implementation: zero address");
require(
(address(registry) == address(0) && Address.isContract(newRegistry)) ||
IRegistry(newRegistry).timelock() == registry.timelock(),
"Implementation: timelocks must match"
);
_setRegistry(newRegistry);
emit RegistryUpdate(newRegistry);
}
/**
* @notice Updates the registry contract
* @dev Internal only
* @param newRegistry New registry contract
*/
function _setRegistry(address newRegistry) internal {
bytes32 position = REGISTRY_SLOT;
assembly {
sstore(position, newRegistry)
}
}
/**
* @notice Returns the current registry contract
* @return Address of the current registry contract
*/
function registry() public view returns (IRegistry reg) {
bytes32 slot = REGISTRY_SLOT;
assembly {
reg := sload(slot)
}
}
// OWNER
/**
* @notice Takes ownership over a contract if none has been set yet
* @dev Needs to be called initialize ownership after deployment
* Ensure that this has been properly set before using the protocol
*/
function takeOwnership() external {
require(owner() == address(0), "Implementation: already initialized");
_setOwner(msg.sender);
emit OwnerUpdate(msg.sender);
}
/**
* @notice Updates the owner contract
* @dev Owner only - governance hook
* @param newOwner New owner contract
*/
function setOwner(address newOwner) external onlyOwner {
require(newOwner != address(this), "Implementation: this");
require(Address.isContract(newOwner), "Implementation: not contract");
_setOwner(newOwner);
emit OwnerUpdate(newOwner);
}
/**
* @notice Updates the owner contract
* @dev Internal only
* @param newOwner New owner contract
*/
function _setOwner(address newOwner) internal {
bytes32 position = OWNER_SLOT;
assembly {
sstore(position, newOwner)
}
}
/**
* @notice Owner contract with admin permission over this contract
* @return Owner contract
*/
function owner() public view returns (address o) {
bytes32 slot = OWNER_SLOT;
assembly {
o := sload(slot)
}
}
/**
* @dev Only allow when the caller is the owner address
*/
modifier onlyOwner {
require(msg.sender == owner(), "Implementation: not owner");
_;
}
// NON REENTRANT
/**
* @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(), "Implementation: reentrant call");
// Any calls to nonReentrant after this point will fail
_setNotEntered(false);
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_setNotEntered(true);
}
/**
* @notice The entered status of the current call
* @return entered status
*/
function notEntered() internal view returns (bool ne) {
bytes32 slot = NOT_ENTERED_SLOT;
assembly {
ne := sload(slot)
}
}
/**
* @notice Updates the entered status of the current call
* @dev Internal only
* @param newNotEntered New entered status
*/
function _setNotEntered(bool newNotEntered) internal {
bytes32 position = NOT_ENTERED_SLOT;
assembly {
sstore(position, newNotEntered)
}
}
// SETUP
/**
* @notice Hook to surface arbitrary logic to be called after deployment by owner
* @dev Governance hook
* Does not ensure that it is only called once because it is permissioned to governance only
*/
function setup() external onlyOwner {
// 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.
_setNotEntered(true);
_setup();
}
/**
* @notice Override to provide addition setup logic per implementation
*/
function _setup() internal { }
}
/*
Copyright 2021 Empty Set Squad <emptysetsquad@protonmail.com>
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 ReserveTypes
* @notice Contains all reserve state structs
*/
contract ReserveTypes {
/**
* @notice Stores state for a single order
*/
struct Order {
/**
* @notice price (takerAmount per makerAmount) for the order as a Decimal
*/
Decimal.D256 price;
/**
* @notice total available amount of the maker token
*/
uint256 amount;
}
/**
* @notice Stores state for the entire reserve
*/
struct State {
/**
* @notice Total debt
*/
uint256 totalDebt;
/**
* @notice Mapping of total debt per borrower
*/
mapping(address => uint256) debt;
/**
* @notice Mapping of all registered limit orders
*/
mapping(address => mapping(address => ReserveTypes.Order)) orders;
}
}
/**
* @title ReserveState
* @notice Reserve state
*/
contract ReserveState {
/**
* @notice Entirety of the reserve contract state
* @dev To upgrade state, append additional state variables at the end of this contract
*/
ReserveTypes.State internal _state;
}
/**
* @title ReserveAccessors
* @notice Reserve state accessor helpers
*/
contract ReserveAccessors is Implementation, ReserveState {
using SafeMath for uint256;
using Decimal for Decimal.D256;
// SWAPPER
/**
* @notice Full state of the `makerToken`-`takerToken` order
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @return Specified order
*/
function order(address makerToken, address takerToken) public view returns (ReserveTypes.Order memory) {
return _state.orders[makerToken][takerToken];
}
/**
* @notice Returns the total debt outstanding
* @return Total debt
*/
function totalDebt() public view returns (uint256) {
return _state.totalDebt;
}
/**
* @notice Returns the total debt outstanding for `borrower`
* @return Total debt for borrower
*/
function debt(address borrower) public view returns (uint256) {
return _state.debt[borrower];
}
/**
* @notice Sets the `price` and `amount` of the specified `makerToken`-`takerToken` order
* @dev Internal only
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param price Price as a ratio of takerAmount:makerAmount times 10^18
* @param amount Amount to decrement in ESD
*/
function _updateOrder(address makerToken, address takerToken, uint256 price, uint256 amount) internal {
_state.orders[makerToken][takerToken] = ReserveTypes.Order({price: Decimal.D256({value: price}), amount: amount});
}
/**
* @notice Decrements the available amount of the specified `makerToken`-`takerToken` order
* @dev Internal only
Reverts when insufficient amount with reason `reason`
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param amount Amount to decrement in ESD
* @param reason revert reason
*/
function _decrementOrderAmount(address makerToken, address takerToken, uint256 amount, string memory reason) internal {
_state.orders[makerToken][takerToken].amount = _state.orders[makerToken][takerToken].amount.sub(amount, reason);
}
/**
* @notice Decrements the debt for `borrower`
* @dev Internal only
* @param borrower Address that is drawing the debt
* @param amount Amount of debt to draw
*/
function _incrementDebt(address borrower, uint256 amount) internal {
_state.totalDebt = _state.totalDebt.add(amount);
_state.debt[borrower] = _state.debt[borrower].add(amount);
}
/**
* @notice Increments the debt for `borrower`
* @dev Internal only
Reverts when insufficient amount with reason `reason`
* @param borrower Address that is drawing the debt
* @param amount Amount of debt to draw
* @param reason revert reason
*/
function _decrementDebt(address borrower, uint256 amount, string memory reason) internal {
_state.totalDebt = _state.totalDebt.sub(amount, reason);
_state.debt[borrower] = _state.debt[borrower].sub(amount, reason);
}
}
/*
Copyright 2021 Empty Set Squad <emptysetsquad@protonmail.com>
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 ReserveVault
* @notice Logic to passively manage USDC reserve with low-risk strategies
* @dev Currently uses Compound to lend idle USDC in the reserve
*/
contract ReserveVault is ReserveAccessors {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using Decimal for Decimal.D256;
/**
* @notice Emitted when `amount` USDC is supplied to the vault
*/
event SupplyVault(uint256 amount);
/**
* @notice Emitted when `amount` USDC is redeemed from the vault
*/
event RedeemVault(uint256 amount);
/**
* @notice Total value of the assets managed by the vault
* @dev Denominated in USDC
* @return Total value of the vault
*/
function _balanceOfVault() internal view returns (uint256) {
ICErc20 cUsdc = ICErc20(registry().cUsdc());
Decimal.D256 memory exchangeRate = Decimal.D256({value: cUsdc.exchangeRateStored()});
return exchangeRate.mul(cUsdc.balanceOf(address(this))).asUint256();
}
/**
* @notice Supplies `amount` USDC to the external protocol for reward accrual
* @dev Supplies to the Compound USDC lending pool
* @param amount Amount of USDC to supply
*/
function _supplyVault(uint256 amount) internal {
address cUsdc = registry().cUsdc();
IERC20(registry().usdc()).safeApprove(cUsdc, amount);
require(ICErc20(cUsdc).mint(amount) == 0, "ReserveVault: supply failed");
emit SupplyVault(amount);
}
/**
* @notice Redeems `amount` USDC from the external protocol for reward accrual
* @dev Redeems from the Compound USDC lending pool
* @param amount Amount of USDC to redeem
*/
function _redeemVault(uint256 amount) internal {
require(ICErc20(registry().cUsdc()).redeemUnderlying(amount) == 0, "ReserveVault: redeem failed");
emit RedeemVault(amount);
}
/**
* @notice Claims all available governance rewards from the external protocol
* @dev Owner only - governance hook
* Claims COMP accrued from lending on the USDC pool
*/
function claimVault() external onlyOwner {
ICErc20(registry().cUsdc()).comptroller().claimComp(address(this));
}
/**
* @notice Delegates voting power to `delegatee` for `token` governance token held by the reserve
* @dev Owner only - governance hook
* Works for all COMP-based governance tokens
* @param token Governance token to delegate voting power
* @param delegatee Account to receive reserve's voting power
*/
function delegateVault(address token, address delegatee) external onlyOwner {
IGovToken(token).delegate(delegatee);
}
}
/**
* @title ICErc20
* @dev Compound ICErc20 interface
*/
contract ICErc20 {
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint mintAmount) external returns (uint256);
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint redeemAmount) external returns (uint256);
/**
* @notice Get the token balance of the `account`
* @param account The address of the account to query
* @return The number of tokens owned by `account`
*/
function balanceOf(address account) external view returns (uint256);
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() external view returns (uint256);
/**
* @notice Contract which oversees inter-cToken operations
*/
function comptroller() public view returns (IComptroller);
}
/**
* @title IComptroller
* @dev Compound IComptroller interface
*/
contract IComptroller {
/**
* @notice Claim all the comp accrued by holder in all markets
* @param holder The address to claim COMP for
*/
function claimComp(address holder) public;
}
/*
Copyright 2021 Empty Set Squad <emptysetsquad@protonmail.com>
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 ReserveComptroller
* @notice Reserve accounting logic for managing the ESD stablecoin.
*/
contract ReserveComptroller is ReserveAccessors, ReserveVault {
using SafeMath for uint256;
using Decimal for Decimal.D256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `account` purchases `mintAmount` ESD from the reserve for `costAmount` USDC
*/
event Mint(address indexed account, uint256 mintAmount, uint256 costAmount);
/**
* @notice Emitted when `account` sells `costAmount` ESD to the reserve for `redeemAmount` USDC
*/
event Redeem(address indexed account, uint256 costAmount, uint256 redeemAmount);
/**
* @notice Emitted when `account` borrows `borrowAmount` ESD from the reserve
*/
event Borrow(address indexed account, uint256 borrowAmount);
/**
* @notice Emitted when `account` repays `repayAmount` ESD to the reserve
*/
event Repay(address indexed account, uint256 repayAmount);
/**
* @notice Helper constant to convert ESD to USDC and vice versa
*/
uint256 private constant USDC_DECIMAL_DIFF = 1e12;
// EXTERNAL
/**
* @notice The total value of the reserve-owned assets denominated in USDC
* @return Reserve total value
*/
function reserveBalance() public view returns (uint256) {
uint256 internalBalance = _balanceOf(registry().usdc(), address(this));
uint256 vaultBalance = _balanceOfVault();
return internalBalance.add(vaultBalance);
}
/**
* @notice The ratio of the {reserveBalance} to total ESD issuance
* @dev Assumes 1 ESD = 1 USDC, normalizing for decimals
* @return Reserve ratio
*/
function reserveRatio() public view returns (Decimal.D256 memory) {
uint256 issuance = _totalSupply(registry().dollar()).sub(totalDebt());
return issuance == 0 ? Decimal.one() : Decimal.ratio(_fromUsdcAmount(reserveBalance()), issuance);
}
/**
* @notice The price that one ESD can currently be sold to the reserve for
* @dev Returned as a Decimal.D256
* Normalizes for decimals (e.g. 1.00 USDC == Decimal.one())
* Equivalent to the current reserve ratio less the current redemption tax (if any)
* @return Current ESD redemption price
*/
function redeemPrice() public view returns (Decimal.D256 memory) {
return Decimal.min(reserveRatio(), Decimal.one());
}
/**
* @notice Mints `amount` ESD to the caller in exchange for an equivalent amount of USDC
* @dev Non-reentrant
* Normalizes for decimals
* Caller must approve reserve to transfer USDC
* @param amount Amount of ESD to mint
*/
function mint(uint256 amount) external nonReentrant {
uint256 costAmount = _toUsdcAmount(amount);
// Take the ceiling to ensure no "free" ESD is minted
costAmount = _fromUsdcAmount(costAmount) == amount ? costAmount : costAmount.add(1);
_transferFrom(registry().usdc(), msg.sender, address(this), costAmount);
_supplyVault(costAmount);
_mintDollar(msg.sender, amount);
emit Mint(msg.sender, amount, costAmount);
}
/**
* @notice Burns `amount` ESD from the caller in exchange for USDC at the rate of {redeemPrice}
* @dev Non-reentrant
* Normalizes for decimals
* Caller must approve reserve to transfer ESD
* @param amount Amount of ESD to mint
*/
function redeem(uint256 amount) external nonReentrant {
uint256 redeemAmount = _toUsdcAmount(redeemPrice().mul(amount).asUint256());
_transferFrom(registry().dollar(), msg.sender, address(this), amount);
_burnDollar(amount);
_redeemVault(redeemAmount);
_transfer(registry().usdc(), msg.sender, redeemAmount);
emit Redeem(msg.sender, amount, redeemAmount);
}
/**
* @notice Lends `amount` ESD to `to` while recording the corresponding debt entry
* @dev Non-reentrant
* Caller must be owner
* Used to pre-fund trusted contracts with ESD without backing (e.g. batchers)
* @param account Address to send the borrowed ESD to
* @param amount Amount of ESD to borrow
*/
function borrow(address account, uint256 amount) external onlyOwner nonReentrant {
require(_canBorrow(account, amount), "ReserveComptroller: cant borrow");
_incrementDebt(account, amount);
_mintDollar(account, amount);
emit Borrow(account, amount);
}
/**
* @notice Repays `amount` ESD on behalf of `to` while reducing its corresponding debt
* @dev Non-reentrant
* @param account Address to repay ESD on behalf of
* @param amount Amount of ESD to repay
*/
function repay(address account, uint256 amount) external nonReentrant {
_decrementDebt(account, amount, "ReserveComptroller: insufficient debt");
_transferFrom(registry().dollar(), msg.sender, address(this), amount);
_burnDollar(amount);
emit Repay(account, amount);
}
// INTERNAL
/**
* @notice Mints `amount` ESD to `account`
* @dev Internal only
* @param account Account to receive minted ESD
* @param amount Amount of ESD to mint
*/
function _mintDollar(address account, uint256 amount) internal {
address dollar = registry().dollar();
IManagedToken(dollar).mint(amount);
IERC20(dollar).safeTransfer(account, amount);
}
/**
* @notice Burns `amount` ESD held by the reserve
* @dev Internal only
* @param amount Amount of ESD to burn
*/
function _burnDollar(uint256 amount) internal {
IManagedToken(registry().dollar()).burn(amount);
}
/**
* @notice `token` balance of `account`
* @dev Internal only
* @param token Token to get the balance for
* @param account Account to get the balance of
*/
function _balanceOf(address token, address account) internal view returns (uint256) {
return IERC20(token).balanceOf(account);
}
/**
* @notice Total supply of `token`
* @dev Internal only
* @param token Token to get the total supply of
*/
function _totalSupply(address token) internal view returns (uint256) {
return IERC20(token).totalSupply();
}
/**
* @notice Safely transfers `amount` `token` from the caller to `receiver`
* @dev Internal only
* @param token Token to transfer
* @param receiver Account to receive the tokens
* @param amount Amount to transfer
*/
function _transfer(address token, address receiver, uint256 amount) internal {
IERC20(token).safeTransfer(receiver, amount);
}
/**
* @notice Safely transfers `amount` `token` from the `sender` to `receiver`
* @dev Internal only
Requires `amount` allowance from `sender` for caller
* @param token Token to transfer
* @param sender Account to send the tokens
* @param receiver Account to receive the tokens
* @param amount Amount to transfer
*/
function _transferFrom(address token, address sender, address receiver, uint256 amount) internal {
IERC20(token).safeTransferFrom(sender, receiver, amount);
}
/**
* @notice Converts ESD amount to USDC amount
* @dev Private only
* Converts an 18-decimal ERC20 amount to a 6-decimals ERC20 amount
* @param dec18Amount 18-decimal ERC20 amount
* @return 6-decimals ERC20 amount
*/
function _toUsdcAmount(uint256 dec18Amount) internal pure returns (uint256) {
return dec18Amount.div(USDC_DECIMAL_DIFF);
}
/**
* @notice Convert USDC amount to ESD amount
* @dev Private only
* Converts a 6-decimal ERC20 amount to an 18-decimals ERC20 amount
* @param usdcAmount 6-decimal ERC20 amount
* @return 18-decimals ERC20 amount
*/
function _fromUsdcAmount(uint256 usdcAmount) internal pure returns (uint256) {
return usdcAmount.mul(USDC_DECIMAL_DIFF);
}
function _canBorrow(address account, uint256 amount) private view returns (bool) {
uint256 totalBorrowAmount = debt(account).add(amount);
if ( // WrapOnlyBatcher
account == address(0x0B663CeaCEF01f2f88EB7451C70Aa069f19dB997) &&
totalBorrowAmount <= 1_000_000e18
) return true;
return false;
}
}
/*
Copyright 2021 Empty Set Squad <emptysetsquad@protonmail.com>
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 ReserveSwapper
* @notice Logic for managing outstanding reserve limit orders.
* Since the reserve is autonomous, it cannot use traditional DEXs without being front-run. The `ReserveSwapper`
* allows governance to place outstanding limit orders selling reserve assets in exchange for assets the reserve
* wishes to purchase. This is the main mechanism by which the reserve may diversify itself, or buy back ESDS
* using generated rewards.
*/
contract ReserveSwapper is ReserveComptroller {
using SafeMath for uint256;
using Decimal for Decimal.D256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `amount` of the `makerToken`-`takerToken` order is registered with price `price`
*/
event OrderRegistered(address indexed makerToken, address indexed takerToken, uint256 price, uint256 amount);
/**
* @notice Emitted when the reserve pays `takerAmount` of `takerToken` in exchange for `makerAmount` of `makerToken`
*/
event Swap(address indexed makerToken, address indexed takerToken, uint256 takerAmount, uint256 makerAmount);
/**
* @notice Sets the `price` and `amount` of the specified `makerToken`-`takerToken` order
* @dev Owner only - governance hook
* @param makerToken Token that the reserve wishes to sell
* @param takerToken Token that the reserve wishes to buy
* @param price Price as a ratio of takerAmount:makerAmount times 10^18
* @param amount Amount of the makerToken that reserve wishes to sell - uint256(-1) indicates all reserve funds
*/
function registerOrder(address makerToken, address takerToken, uint256 price, uint256 amount) external onlyOwner {
_updateOrder(makerToken, takerToken, price, amount);
emit OrderRegistered(makerToken, takerToken, price, amount);
}
/**
* @notice Purchases `makerToken` from the reserve in exchange for `takerAmount` of `takerToken`
* @dev Non-reentrant
* Uses the state-defined price for the `makerToken`-`takerToken` order
* Maker and taker tokens must be different
* Cannot swap ESD
* @param makerToken Token that the caller wishes to buy
* @param takerToken Token that the caller wishes to sell
* @param takerAmount Amount of takerToken to sell
*/
function swap(address makerToken, address takerToken, uint256 takerAmount) external nonReentrant {
address dollar = registry().dollar();
require(makerToken != dollar, "ReserveSwapper: unsupported token");
require(takerToken != dollar, "ReserveSwapper: unsupported token");
require(makerToken != takerToken, "ReserveSwapper: tokens equal");
ReserveTypes.Order memory order = order(makerToken, takerToken);
uint256 makerAmount = Decimal.from(takerAmount).div(order.price, "ReserveSwapper: no order").asUint256();
if (order.amount != uint256(-1))
_decrementOrderAmount(makerToken, takerToken, makerAmount, "ReserveSwapper: insufficient amount");
_transferFrom(takerToken, msg.sender, address(this), takerAmount);
_transfer(makerToken, msg.sender, makerAmount);
emit Swap(makerToken, takerToken, takerAmount, makerAmount);
}
}
/*
Copyright 2021 Empty Set Squad <emptysetsquad@protonmail.com>
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 ReserveIssuer
* @notice Logic to manage the supply of ESDS
*/
contract ReserveIssuer is ReserveAccessors {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @notice Emitted when `account` mints `amount` of ESDS
*/
event MintStake(address account, uint256 mintAmount);
/**
* @notice Emitted when `amount` of ESDS is burned from the reserve
*/
event BurnStake(uint256 burnAmount);
/**
* @notice Mints new ESDS tokens to a specified `account`
* @dev Non-reentrant
* Owner only - governance hook
* ESDS maxes out at ~79b total supply (2^96/10^18) due to its 96-bit limitation
* Will revert if totalSupply exceeds this maximum
* @param account Account to mint ESDS to
* @param amount Amount of ESDS to mint
*/
function mintStake(address account, uint256 amount) public onlyOwner {
address stake = registry().stake();
IManagedToken(stake).mint(amount);
IERC20(stake).safeTransfer(account, amount);
emit MintStake(account, amount);
}
/**
* @notice Burns all reserve-held ESDS tokens
* @dev Non-reentrant
* Owner only - governance hook
*/
function burnStake() public onlyOwner {
address stake = registry().stake();
uint256 stakeBalance = IERC20(stake).balanceOf(address(this));
IManagedToken(stake).burn(stakeBalance);
emit BurnStake(stakeBalance);
}
}
/*
Copyright 2021 Empty Set Squad <emptysetsquad@protonmail.com>
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 ReserveImpl
* @notice Top-level Reserve contract that extends all other reserve sub-contracts
* @dev This contract should be used an implementation contract for an AdminUpgradeabilityProxy
*/
contract ReserveImpl is IReserve, ReserveComptroller, ReserveIssuer, ReserveSwapper { }
|
Hook to surface arbitrary logic to be called after deployment by owner Governance hook Does not ensure that it is only called once because it is permissioned to governance only/ 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.
|
function setup() external onlyOwner {
_setNotEntered(true);
_setup();
}
| 12,066,218
|
./full_match/43113/0xA09322b0F84Ea97b327a25cECDB0A946Ef67A3B2/sources/GothSwapRouter02.sol
|
ADD LIQUIDITY create the pair if it doesn't exist yet
|
function _addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin
) internal virtual returns (uint amountA, uint amountB) {
if (IGothSwapFactory(factory).getPair(tokenA, tokenB) == address(0)) {
IGothSwapFactory(factory).createPair(tokenA, tokenB);
}
(uint reserveA, uint reserveB) = GothSwapLibrary.getReserves(factory, tokenA, tokenB);
if (reserveA == 0 && reserveB == 0) {
(amountA, amountB) = (amountADesired, amountBDesired);
uint amountBOptimal = GothSwapLibrary.quote(amountADesired, reserveA, reserveB);
if (amountBOptimal <= amountBDesired) {
require(amountBOptimal >= amountBMin, 'GothSwapRouter: INSUFFICIENT_B_AMOUNT');
(amountA, amountB) = (amountADesired, amountBOptimal);
uint amountAOptimal = GothSwapLibrary.quote(amountBDesired, reserveB, reserveA);
assert(amountAOptimal <= amountADesired);
require(amountAOptimal >= amountAMin, 'GothSwapRouter: INSUFFICIENT_A_AMOUNT');
(amountA, amountB) = (amountAOptimal, amountBDesired);
}
}
}
| 7,158,457
|
./full_match/42/0xa312e287d9E09792B2e2C45BE4bBC39cfFaD34BC/sources/8a173a65099261582a652ba18b7d96c1/APIConsumer.sol
|
Callback function for getting the view count on a video/Set contract variables to start the agreementTurn string total view count into an int and calculate pay
|
function viewCountFallback(bytes32 _requestId, bytes32 _viewCount) public recordChainlinkFulfillment(_requestId) {
string memory _viewCountString = bytes32ToString(_viewCount);
viewCount = uint256(parseInt(_viewCountString, 0));
payForWithdraw = (payPerView * viewCount) - accumulatedPay;
}
| 9,574,498
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.5.0;
import "@openzeppelin/contracts/math/SafeMath.sol";
contract Universe {
using SafeMath for uint;
//The register of poem creators
mapping (uint => address) public poemOwners;
//The maximum number of poems
uint constant public MAXPOEMS = 100;
//The array of all poems
bytes32[MAXPOEMS] public poems;
//A mask for selecting half of the poems
bytes32 mask = 0x00000000000000000000000000000000ffffffffffffffffffffffffffffffff;
//A mask to be used when selecting the other half
bytes32 mask2 = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
//The IPFS hash of the words
string URL = "https://ipfs.io/ipfs/QmbKfq8MUGduaTk71aegxpzUseBxmufXW9MPaLy7c31Bcu";
//An event to log all newly made poems
event LogNewPoem(uint rejectedPoemId, address owner, bytes32 newPoem);
/*
* constructor that creates the initial set of poems
* @emits new poems
*/
constructor() public {
//Create the first poem, using the contract creator's address as a random seed
poems[0] = keccak256(abi.encodePacked(msg.sender));
emit LogNewPoem(0, msg.sender, poems[0]);
//Create the remaining poems
for(uint i=1; i<poems.length; i++) {
poems[i] = keccak256(abi.encodePacked(poems[i-1]));
emit LogNewPoem(i, msg.sender, poems[i]);
}
}
/*
* A function to get hardcoded url of the dictionary
* @returns the url of the dictionary on ipfs
*/
function getDictionary() view public returns (string memory) {
return URL;
}
/*
* A function that will delete a poem from the array of poems and
* in its place will go a new poem created by evolvePoem function
* @param _selectedPoemId is the index of the poem in the array poems that will be spliced
* @param _rejectedPoemId is the index of the poem in the array poems that will be deleted
* @emits _rejectedPoemId, msg.sender and new poem
* @returns nothing
*/
function selectPoem(uint _selectedPoemId, uint _rejectedPoemId) public {
require(_selectedPoemId >= 0 && _selectedPoemId < MAXPOEMS && _rejectedPoemId >= 0 && _rejectedPoemId < MAXPOEMS && _selectedPoemId != _rejectedPoemId);
bytes32 newPoem = evolvePoem(_selectedPoemId);
poems[_rejectedPoemId] = newPoem;
poemOwners[_rejectedPoemId] = msg.sender;
emit LogNewPoem(_rejectedPoemId, msg.sender, newPoem);
}
/*
* A function to get all poems
* @returns the array of all poems
*/
function getPoems() view public returns (bytes32[MAXPOEMS] memory) {
return poems;
}
/*
* A function to get a poem at a given index
* @param id is the index of the poem in the array poems
* @returns the poem at the index specified
*/
function getPoem(uint id) view public returns (bytes32) {
return poems[id];
}
/*
* A function to get a poem's creator
* @param is the index of the poem in the array of poems
* @returns the poem at the index specified
*/
function getPoemOwner(uint id) view public returns (address poemOwner) {
require(id < MAXPOEMS);
return poemOwners[id];
}
/*
* A function to get two different arbitrary poems
* @returns two poems and their indices
*/
function getTwoPoems() view public returns (uint IDofFirstPoem, bytes32 poemA, uint IDofSecondPoem, bytes32 poemB) {
//Get one arbitrary poem ID using timestamp
uint arbitraryPoem1 = uint(block.timestamp.mod(MAXPOEMS));
uint arbitraryPoem2 = uint(block.number.mod(MAXPOEMS));
//Make sure second arbitrary poem ID using block height is difference from arbitraryPoem1
if(arbitraryPoem1 == arbitraryPoem2) {
arbitraryPoem2++;
}
return (arbitraryPoem1, poems[arbitraryPoem1], arbitraryPoem2, poems[arbitraryPoem2]);
}
/*
* An internal function to get the splice of two poems
* @returns one new poem
*/
function evolvePoem(uint _selectedPoemId) internal view returns (bytes32) {
//Get an arbitrary number
uint arbitraryMate = uint(block.timestamp.mod(MAXPOEMS));
//Move the mask to pick a random 128 contiguous bits
uint arbitraryGeneShare = uint(block.timestamp.mod(128));
//Move the mask
bytes32 tempMask1 = mask << arbitraryGeneShare;
//Create the opposite mask
bytes32 tempMask2 = mask2 ^ tempMask1;
//Mask selected poem to keep half
bytes32 keep1 = poems[_selectedPoemId] & tempMask1;
//Mask arbitrary poem to keep opposite half
bytes32 keep2 = poems[arbitraryMate] & tempMask2;
//Merge poems by masking one with the other
bytes32 evolvedPoem = keep1 | keep2;
return evolvedPoem;
}
}
|
A function to get a poem's creator is the index of the poem in the array of poems returns the poem at the index specified/
|
function getPoemOwner(uint id) view public returns (address poemOwner) {
require(id < MAXPOEMS);
return poemOwners[id];
}
| 1,086,880
|
./partial_match/1/0x67391801E7564994bdAa80544Ff916A7bCBFCB60/sources/MacroverseUniversalRegistry.sol
|
Transfer all Ether held by the contract to the owner./ For some reason Ownable doesn't insist that the owner is payable. This makes it payable.
|
function reclaimEther() external onlyOwner {
address(uint160(owner())).transfer(address(this).balance);
}
| 9,236,575
|
./full_match/1/0x3Bc988Da91b01d682C37e29f95bC0Ed18F3273Fc/sources/contracts/GraphcastRegistryV2.sol
|
Return Staking interface return Staking contract registered with Graph Proxy Controller/
|
function staking() internal view returns (Staking) {
return Staking(stakingAddr);
}
| 16,529,869
|
/*
Copyright [2019] - [2021], PERSISTENCE TECHNOLOGIES PTE. LTD. and the pStake-smartContracts contributors
SPDX-License-Identifier: Apache-2.0
*/
pragma solidity >=0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/EnumerableSetUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol";
import "./interfaces/ISTokensV2.sol";
import "./interfaces/IUTokensV2.sol";
import "./interfaces/IHolderV2.sol";
import "./libraries/FullMath.sol";
contract STokensV2 is
ERC20Upgradeable,
ISTokensV2,
PausableUpgradeable,
AccessControlUpgradeable
{
using SafeMathUpgradeable for uint256;
using FullMath for uint256;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet;
// constants defining access control ROLES
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
// variables pertaining to holder logic for whitelisted addresses & StakeLP
// deposit contract address for STokens in a DeFi product
EnumerableSetUpgradeable.AddressSet private _whitelistedAddresses;
// Holder contract address for this whitelisted contract. Many can point to one Holder contract
mapping(address => address) public _holderContractAddress;
// LP Token contract address which might be different from whitelisted contract
mapping(address => address) public _lpContractAddress;
// last timestamp when the holder reward calculation was performed for updating reward pool
mapping(address => uint256) public _lastHolderRewardTimestamp;
// _liquidStakingContract address does the mint and burn of STokens
address public _liquidStakingContract;
// _uTokens variable is used to do mint of UTokens
IUTokensV2 public _uTokens;
// variables pertaining to moving reward rate logic
uint256[] private _rewardRate;
uint256[] private _lastMovingRewardTimestamp;
uint256 public _valueDivisor;
mapping(address => uint256) public _lastUserRewardTimestamp;
// variable pertaining to contract upgrades versioning
uint256 public _version;
// required to store the whitelisting holder logic data initiated from WhitelistedEmission contract
address public _whitelistedPTokenEmissionContract;
/**
* @dev Constructor for initializing the SToken contract.
* @param uaddress - address of the UToken contract.
* @param pauserAddress - address of the pauser admin.
* @param rewardRate - set to rewardRate * 10^-5
* @param valueDivisor - valueDivisor set to 10^9.
*/
function initialize(
address uaddress,
address pauserAddress,
uint256 rewardRate,
uint256 valueDivisor
) public virtual initializer {
__ERC20_init("pSTAKE Staked ATOM", "stkATOM");
__AccessControl_init();
__Pausable_init();
_setupRole(DEFAULT_ADMIN_ROLE, _msgSender());
_setupRole(PAUSER_ROLE, pauserAddress);
setUTokensContract(uaddress);
_valueDivisor = valueDivisor;
require(rewardRate <= _valueDivisor.mul(100), "ST1");
_rewardRate.push(rewardRate);
_lastMovingRewardTimestamp.push(block.timestamp);
_setupDecimals(6);
}
/**
* @dev Calculate pending rewards for the provided 'address'. The rate is the moving reward rate.
* @param whitelistedAddress: whitelisted contract address
*/
function isContractWhitelisted(address whitelistedAddress)
public
view
virtual
override
returns (bool result)
{
result = _whitelistedAddresses.contains(whitelistedAddress);
return result;
}
/**
* @dev Calculate pending rewards for the provided 'address'. The rate is the moving reward rate.
* @param whitelistedAddress: contract address
*/
function getWhitelistData(address whitelistedAddress)
public
view
virtual
override
returns (
address holderAddress,
address lpAddress,
address uTokenAddress,
uint256 lastHolderRewardTimestamp
)
{
// Get the time in number of blocks
holderAddress = _holderContractAddress[whitelistedAddress];
lpAddress = _lpContractAddress[whitelistedAddress];
lastHolderRewardTimestamp = _lastHolderRewardTimestamp[
whitelistedAddress
];
uTokenAddress = (holderAddress == address(0) || lpAddress == address(0))
? address(0)
: address(_uTokens);
}
/**
* @dev get uToken address
*/
function getUTokenAddress()
public
view
virtual
override
returns (address uTokenAddress)
{
uTokenAddress = address(_uTokens);
}
/*
* @dev set reward rate called by admin
* @param rewardRate: reward rate
*
*
* Requirements:
*
* - `rate` cannot be less than or equal to zero.
*
*/
function setRewardRate(uint256 rewardRate)
public
virtual
override
returns (bool success)
{
// range checks for rewardRate. Since rewardRate cannot be more than 100%, the max cap
// is _valueDivisor * 100, which then brings the fees to 100 (percentage)
require(rewardRate <= _valueDivisor.mul(100), "ST18");
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST2");
_rewardRate.push(rewardRate);
_lastMovingRewardTimestamp.push(block.timestamp);
emit SetRewardRate(rewardRate);
return true;
}
/**
* @dev get reward rate, last moving reward timestamp and value divisor
*/
function getRewardRate()
public
view
virtual
override
returns (
uint256[] memory rewardRate,
uint256[] memory lastMovingRewardTimestamp,
uint256 valueDivisor
)
{
rewardRate = _rewardRate;
lastMovingRewardTimestamp = _lastMovingRewardTimestamp;
valueDivisor = _valueDivisor;
}
/**
* @dev Mint new stokens for the provided 'address' and 'tokens'
* @param to: account address, tokens: number of tokens
*
* Emits a {MintTokens} event with 'to' set to address and 'tokens' set to amount of tokens.
*
* Requirements:
*
* - `amount` cannot be less than zero.
*
*/
function mint(address to, uint256 tokens)
public
virtual
override
returns (bool)
{
require(_msgSender() == _liquidStakingContract, "ST3");
_mint(to, tokens);
return true;
}
/*
* @dev Burn stokens for the provided 'address' and 'tokens'
* @param to: account address, tokens: number of tokens
*
* Emits a {BurnTokens} event with 'to' set to address and 'tokens' set to amount of tokens.
*
* Requirements:
*
* - `amount` cannot be less than zero.
*
*/
function burn(address from, uint256 tokens)
public
virtual
override
returns (bool)
{
require(_msgSender() == _liquidStakingContract, "ST4");
_burn(from, tokens);
return true;
}
/**
* @dev Calculate pending rewards from the provided 'principal' & 'lastRewardTimestamp'. The rate is the moving reward rate.
* @param principal: principal amount
* @param lastRewardTimestamp: timestamp of last reward calculation performed
*/
function _calculatePendingRewards(
uint256 principal,
uint256 lastRewardTimestamp
) internal view returns (uint256 pendingRewards) {
uint256 _index;
uint256 _rewardBlocks;
uint256 _simpleInterestOfInterval;
uint256 _temp;
// return 0 if principal or timeperiod is zero
if (principal == 0 || block.timestamp.sub(lastRewardTimestamp) == 0)
return 0;
// calculate rewards for each interval period between rewardRate changes
uint256 _lastMovingRewardLength = _lastMovingRewardTimestamp.length.sub(
1
);
for (_index = _lastMovingRewardLength; _index >= 0; ) {
// logic applies for all indexes of array except last index
if (_index < _lastMovingRewardTimestamp.length.sub(1)) {
if (_lastMovingRewardTimestamp[_index] > lastRewardTimestamp) {
_rewardBlocks = (_lastMovingRewardTimestamp[_index.add(1)])
.sub(_lastMovingRewardTimestamp[_index]);
_temp = principal.mulDiv(_rewardRate[_index], 100);
_simpleInterestOfInterval = _temp.mulDiv(
_rewardBlocks,
_valueDivisor
);
pendingRewards = pendingRewards.add(
_simpleInterestOfInterval
);
} else {
_rewardBlocks = (_lastMovingRewardTimestamp[_index.add(1)])
.sub(lastRewardTimestamp);
_temp = principal.mulDiv(_rewardRate[_index], 100);
_simpleInterestOfInterval = _temp.mulDiv(
_rewardBlocks,
_valueDivisor
);
pendingRewards = pendingRewards.add(
_simpleInterestOfInterval
);
break;
}
}
// logic applies only for the last index of array
else {
if (_lastMovingRewardTimestamp[_index] > lastRewardTimestamp) {
_rewardBlocks = (block.timestamp).sub(
_lastMovingRewardTimestamp[_index]
);
_temp = principal.mulDiv(_rewardRate[_index], 100);
_simpleInterestOfInterval = _temp.mulDiv(
_rewardBlocks,
_valueDivisor
);
pendingRewards = pendingRewards.add(
_simpleInterestOfInterval
);
} else {
_rewardBlocks = (block.timestamp).sub(lastRewardTimestamp);
_temp = principal.mulDiv(_rewardRate[_index], 100);
_simpleInterestOfInterval = _temp.mulDiv(
_rewardBlocks,
_valueDivisor
);
pendingRewards = pendingRewards.add(
_simpleInterestOfInterval
);
break;
}
}
if (_index == 0) break;
else {
_index = _index.sub(1);
}
}
return pendingRewards;
}
/**
* @dev Calculate pending rewards for the provided 'address'. The rate is the moving reward rate.
* @param to: account address
*/
function calculatePendingRewards(address to)
public
view
virtual
override
returns (uint256 pendingRewards)
{
// Get the time in number of blocks
uint256 _lastRewardTimestamp = _lastUserRewardTimestamp[to];
// Get the balance of the account
uint256 _balance = balanceOf(to);
// calculate pending rewards using _calculatePendingRewards
pendingRewards = _calculatePendingRewards(
_balance,
_lastRewardTimestamp
);
return pendingRewards;
}
/**
* @dev Calculate rewards for the provided 'address'
* @param to: account address
*/
function _calculateRewards(address to) internal returns (uint256 _reward) {
// keep an if condition to check for address(0), instead of require condition, because address(0) is
// a valid condition when it is a mint/burn operation
if (to != address(0)) {
// Calculate the rewards pending
_reward = calculatePendingRewards(to);
// Set the new stakedBlock to the current,
// as per Checks-Effects-Interactions pattern
_lastUserRewardTimestamp[to] = block.timestamp;
// mint uTokens only if reward is greater than zero
if (_reward > 0) {
// Mint new uTokens and send to the callers account
_uTokens.mint(to, _reward);
emit CalculateRewards(to, _reward, block.timestamp);
}
}
return _reward;
}
/**
* @dev Calculate rewards for the provided 'address'
* @param to: account address
*
* Emits a {TriggeredCalculateRewards} event with 'to' set to address, 'reward' set to amount of tokens and 'timestamp'
*
*/
function calculateRewards(address to)
public
virtual
override
whenNotPaused
returns (uint256 reward)
{
bool isContractWhitelistedLocal = _whitelistedAddresses.contains(to);
require(to == _msgSender() && !isContractWhitelistedLocal, "ST5");
reward = _calculateRewards(to);
emit TriggeredCalculateRewards(to, reward, block.timestamp);
return reward;
}
/**
* @dev Calculate rewards for the provided 'holder address'
* @param to: holder address
*/
function _calculateHolderRewards(address to)
internal
returns (
uint256 rewards,
address holderAddress,
address lpTokenAddress
)
{
require(
_whitelistedAddresses.contains(to) &&
_holderContractAddress[to] != address(0) &&
_lpContractAddress[to] != address(0),
"ST6"
);
(
rewards,
holderAddress,
lpTokenAddress
) = calculatePendingHolderRewards(to);
// update the last timestamp of reward pool to the current time as per Checks-Effects-Interactions pattern
_lastHolderRewardTimestamp[to] = block.timestamp;
// Mint new uTokens and send to the holder contract account as updated reward pool
if (rewards > 0) {
_uTokens.mint(holderAddress, rewards);
}
emit CalculateHolderRewards(
to,
address(this),
rewards,
block.timestamp
);
}
/**
* @dev Calculate pending rewards for the provided 'address'. The rate is the moving reward rate.
* @param to: account address
*/
function calculatePendingHolderRewards(address to)
public
view
virtual
override
returns (
uint256 pendingRewards,
address holderAddress,
address lpAddress
)
{
// holderContract and lpContract (lp token contract) need to be validated together because
// it might not be practical to setup holder to collect reward pool but not StakeLP to distribute reward
// since the reward distribution calculation starts the minute reward pool is created
if (
_whitelistedAddresses.contains(to) &&
_holderContractAddress[to] != address(0) &&
_lpContractAddress[to] != address(0)
) {
uint256 _sTokenSupply = IHolderV2(_holderContractAddress[to])
.getSTokenSupply(to, address(this));
// calculate the reward applying the moving reward rate
if (_sTokenSupply > 0) {
pendingRewards = _calculatePendingRewards(
_sTokenSupply,
_lastHolderRewardTimestamp[to]
);
holderAddress = _holderContractAddress[to];
lpAddress = _lpContractAddress[to];
}
}
}
/**
* @dev Calculate rewards for the provided 'address'
* @param to: account address
*
* Emits a {TriggeredCalculateRewards} event with 'to' set to address, 'reward' set to amount of tokens and 'timestamp'
*
*/
function calculateHolderRewards(address to)
public
virtual
override
whenNotPaused
returns (
uint256 rewards,
address holderAddress,
address lpTokenAddress
)
{
(rewards, holderAddress, lpTokenAddress) = _calculateHolderRewards(to);
emit TriggeredCalculateHolderRewards(
to,
address(this),
rewards,
block.timestamp
);
}
/**
* @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.
*
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual override {
require(!paused(), "ST7");
super._beforeTokenTransfer(from, to, amount);
bool isFromContractWhitelisted = isContractWhitelisted(from);
bool isToContractWhitelisted = isContractWhitelisted(to);
if (!isFromContractWhitelisted) {
_calculateRewards(from);
if (!isToContractWhitelisted) {
_calculateRewards(to);
} else {
_calculateHolderRewards(to);
}
} else {
_calculateHolderRewards(from);
if (!isToContractWhitelisted) {
_calculateRewards(to);
} else {
_calculateHolderRewards(to);
}
}
}
/*
* @dev Set 'contract address', called from constructor
* @param whitelistedPTokenEmissionContract: whitelistedPTokenEmission contract address
*
* Emits a {SetWhitelistedPTokenEmissionContract} event with '_contract' set to the WhitelistedPTokenEmission contract address.
*
*/
function setWhitelistedPTokenEmissionContract(
address whitelistedPTokenEmissionContract
) public virtual override {
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST11");
_whitelistedPTokenEmissionContract = whitelistedPTokenEmissionContract;
emit SetWhitelistedPTokenEmissionContract(
whitelistedPTokenEmissionContract
);
}
/*
* @dev Set 'whitelisted address', performed by admin only
* @param whitelistedAddress: contract address of the whitelisted party
* @param holderContractAddress: holder contract address
* @param lpContractAddress: LP token contract address
*
* Emits a {setWhitelistedAddress} event
*
*/
function setWhitelistedAddress(
address whitelistedAddress,
address holderContractAddress,
address lpContractAddress
) public virtual override returns (bool success) {
require(_msgSender() == _whitelistedPTokenEmissionContract, "ST12");
// lpTokenERC20ContractAddress or sTokenReserveContractAddress can be address(0) but not whitelistedAddress
require(whitelistedAddress != address(0), "ST13");
// add the whitelistedAddress if it isn't already available
if (!_whitelistedAddresses.contains(whitelistedAddress))
_whitelistedAddresses.add(whitelistedAddress);
// add the contract addresses to holder mapping variable
_holderContractAddress[whitelistedAddress] = holderContractAddress;
_lpContractAddress[whitelistedAddress] = lpContractAddress;
emit SetWhitelistedAddress(
whitelistedAddress,
holderContractAddress,
lpContractAddress,
block.timestamp
);
success = true;
return success;
}
/*
* @dev remove 'whitelisted address', performed by admin only
* @param whitelistedAddress: contract address of the whitelisted party
*
* Emits a {RemoveWhitelistedAddress} event
*
*/
function removeWhitelistedAddress(address whitelistedAddress)
public
virtual
override
returns (bool success)
{
require(_msgSender() == _whitelistedPTokenEmissionContract, "ST14");
require(whitelistedAddress != address(0), "ST15");
// remove whitelistedAddress from the list
_whitelistedAddresses.remove(whitelistedAddress);
// emit an event
emit RemoveWhitelistedAddress(
whitelistedAddress,
_holderContractAddress[whitelistedAddress],
_lpContractAddress[whitelistedAddress],
_lastHolderRewardTimestamp[whitelistedAddress],
block.timestamp
);
// delete holder contract values
delete _holderContractAddress[whitelistedAddress];
delete _lpContractAddress[whitelistedAddress];
delete _lastHolderRewardTimestamp[whitelistedAddress];
success = true;
return success;
}
/*
* @dev Set 'contract address', called from constructor
* @param uTokenContract: utoken contract address
*
* Emits a {SetUTokensContract} event with '_contract' set to the utoken contract address.
*
*/
function setUTokensContract(address uTokenContract)
public
virtual
override
{
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST8");
_uTokens = IUTokensV2(uTokenContract);
emit SetUTokensContract(uTokenContract);
}
/*
* @dev Set 'contract address', called from constructor
* @param liquidStakingContract: liquidStaking contract address
*
* Emits a {SetLiquidStakingContract} event with '_contract' set to the liquidStaking contract address.
*
*/
function setLiquidStakingContract(address liquidStakingContract)
public
virtual
override
{
require(hasRole(DEFAULT_ADMIN_ROLE, _msgSender()), "ST9");
_liquidStakingContract = liquidStakingContract;
emit SetLiquidStakingContract(liquidStakingContract);
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function pause() public virtual override returns (bool success) {
require(hasRole(PAUSER_ROLE, _msgSender()), "ST16");
_pause();
return true;
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function unpause() public virtual override returns (bool success) {
require(hasRole(PAUSER_ROLE, _msgSender()), "ST17");
_unpause();
return true;
}
}
|
Set 'whitelisted address', performed by admin only whitelistedAddress: contract address of the whitelisted party holderContractAddress: holder contract address lpContractAddress: LP token contract address Emits a {setWhitelistedAddress} event/ lpTokenERC20ContractAddress or sTokenReserveContractAddress can be address(0) but not whitelistedAddress add the whitelistedAddress if it isn't already available add the contract addresses to holder mapping variable
|
function setWhitelistedAddress(
address whitelistedAddress,
address holderContractAddress,
address lpContractAddress
) public virtual override returns (bool success) {
require(_msgSender() == _whitelistedPTokenEmissionContract, "ST12");
require(whitelistedAddress != address(0), "ST13");
if (!_whitelistedAddresses.contains(whitelistedAddress))
_whitelistedAddresses.add(whitelistedAddress);
_holderContractAddress[whitelistedAddress] = holderContractAddress;
_lpContractAddress[whitelistedAddress] = lpContractAddress;
emit SetWhitelistedAddress(
whitelistedAddress,
holderContractAddress,
lpContractAddress,
block.timestamp
);
success = true;
return success;
}
| 12,967,255
|
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0;
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../interfaces/INFTComplexGemPoolData.sol";
import "../interfaces/ISwapQueryHelper.sol";
import "../interfaces/INFTGemMultiToken.sol";
import "../interfaces/INFTGemGovernor.sol";
import "../interfaces/INFTComplexGemPool.sol";
import "../interfaces/INFTGemFeeManager.sol";
import "../libs/AddressSet.sol";
library ComplexPoolLib {
using AddressSet for AddressSet.Set;
/**
* @dev Event generated when an NFT claim is created using base currency
*/
event NFTGemClaimCreated(
address indexed account,
address indexed pool,
uint256 indexed claimHash,
uint256 length,
uint256 quantity,
uint256 amountPaid
);
/**
* @dev Event generated when an NFT claim is created using ERC20 tokens
*/
event NFTGemERC20ClaimCreated(
address indexed account,
address indexed pool,
uint256 indexed claimHash,
uint256 length,
address token,
uint256 quantity,
uint256 conversionRate
);
/**
* @dev Event generated when an NFT claim is redeemed
*/
event NFTGemClaimRedeemed(
address indexed account,
address indexed pool,
uint256 indexed claimHash,
uint256 amountPaid,
uint256 quantity,
uint256 feeAssessed
);
/**
* @dev Event generated when an NFT erc20 claim is redeemed
*/
event NFTGemERC20ClaimRedeemed(
address indexed account,
address indexed pool,
uint256 indexed claimHash,
address token,
uint256 ethPrice,
uint256 tokenAmount,
uint256 quantity,
uint256 feeAssessed
);
/**
* @dev Event generated when a gem is created
*/
event NFTGemCreated(
address account,
address pool,
uint256 claimHash,
uint256 gemHash,
uint256 quantity
);
/**
* @dev data describes complex pool
*/
struct ComplexPoolData {
// governor and multitoken target
address pool;
address multitoken;
address governor;
address feeTracker;
address swapHelper;
uint256 category;
bool visible;
// it all starts with a symbol and a nams
string symbol;
string name;
string description;
// magic economy numbers
uint256 ethPrice;
uint256 minTime;
uint256 maxTime;
uint256 diffstep;
uint256 maxClaims;
uint256 maxQuantityPerClaim;
uint256 maxClaimsPerAccount;
bool validateerc20;
bool allowPurchase;
bool enabled;
INFTComplexGemPoolData.PriceIncrementType priceIncrementType;
mapping(uint256 => INFTGemMultiToken.TokenType) tokenTypes;
mapping(uint256 => uint256) tokenIds;
mapping(uint256 => address) tokenSources;
AddressSet.Set allowedTokenSources;
uint256[] tokenHashes;
// next ids of things
uint256 nextGemIdVal;
uint256 nextClaimIdVal;
uint256 totalStakedEth;
// records claim timestamp / ETH value / ERC token and amount sent
mapping(uint256 => uint256) claimLockTimestamps;
mapping(uint256 => address) claimLockToken;
mapping(uint256 => uint256) claimAmountPaid;
mapping(uint256 => uint256) claimQuant;
mapping(uint256 => uint256) claimTokenAmountPaid;
mapping(uint256 => mapping(address => uint256)) importedLegacyToken;
// input NFTs storage
mapping(uint256 => uint256) gemClaims;
mapping(uint256 => uint256[]) claimIds;
mapping(uint256 => uint256[]) claimQuantities;
mapping(address => bool) controllers;
mapping(address => uint256) claimsMade;
INFTComplexGemPoolData.InputRequirement[] inputRequirements;
AddressSet.Set allowedTokens;
}
function checkGemRequirement(
ComplexPoolData storage self,
uint256 _inputIndex,
address _holderAddress,
uint256 _quantity
) internal view returns (address) {
address gemtoken;
int256 required = int256(
self.inputRequirements[_inputIndex].minVal * _quantity
);
uint256[] memory hashes = INFTGemMultiToken(
self.inputRequirements[_inputIndex].token
).heldTokens(_holderAddress);
for (
uint256 _hashIndex = 0;
_hashIndex < hashes.length;
_hashIndex += 1
) {
uint256 hashAt = hashes[_hashIndex];
if (
INFTComplexGemPoolData(self.inputRequirements[_inputIndex].pool)
.tokenType(hashAt) == INFTGemMultiToken.TokenType.GEM
) {
gemtoken = self.inputRequirements[_inputIndex].token;
uint256 balance = IERC1155(
self.inputRequirements[_inputIndex].token
).balanceOf(_holderAddress, hashAt);
if (balance > uint256(required)) {
balance = uint256(required);
}
if (balance == 0) {
continue;
}
required = required - int256(balance);
}
if (
required == 0 &&
self.inputRequirements[_inputIndex].exactAmount == false
) {
break;
}
if (required < 0) {
require(required == 0, "EXACT_AMOUNT_REQUIRED");
}
}
require(required == 0, "UNMET_GEM_REQUIREMENT");
return gemtoken;
}
/**
* @dev checks to see that account owns all the pool requirements needed to mint at least the given quantity of NFT
*/
function requireInputReqs(
ComplexPoolData storage self,
address _holderAddress,
uint256 _quantity
) public view {
for (
uint256 _inputIndex = 0;
_inputIndex < self.inputRequirements.length;
_inputIndex += 1
) {
if (
self.inputRequirements[_inputIndex].inputType ==
INFTComplexGemPool.RequirementType.ERC20
) {
require(
IERC20(self.inputRequirements[_inputIndex].token).balanceOf(
_holderAddress
) >=
self.inputRequirements[_inputIndex].minVal *
(_quantity),
"UNMET_ERC20_REQUIREMENT"
);
} else if (
self.inputRequirements[_inputIndex].inputType ==
INFTComplexGemPool.RequirementType.ERC1155
) {
require(
IERC1155(self.inputRequirements[_inputIndex].token)
.balanceOf(
_holderAddress,
self.inputRequirements[_inputIndex].tokenId
) >=
self.inputRequirements[_inputIndex].minVal *
(_quantity),
"UNMET_ERC1155_REQUIREMENT"
);
} else if (
self.inputRequirements[_inputIndex].inputType ==
INFTComplexGemPool.RequirementType.POOL
) {
checkGemRequirement(
self,
_inputIndex,
_holderAddress,
_quantity
);
}
}
}
/**
* @dev Transfer a quantity of input reqs from to
*/
function takeInputReqsFrom(
ComplexPoolData storage self,
uint256 _claimHash,
address _fromAddress,
uint256 _quantity
) internal {
address gemtoken;
for (
uint256 _inputIndex = 0;
_inputIndex < self.inputRequirements.length;
_inputIndex += 1
) {
if (!self.inputRequirements[_inputIndex].takeCustody) {
continue;
}
if (
self.inputRequirements[_inputIndex].inputType ==
INFTComplexGemPool.RequirementType.ERC20
) {
IERC20 token = IERC20(
self.inputRequirements[_inputIndex].token
);
token.transferFrom(
_fromAddress,
self.pool,
self.inputRequirements[_inputIndex].minVal * (_quantity)
);
} else if (
self.inputRequirements[_inputIndex].inputType ==
INFTComplexGemPool.RequirementType.ERC1155
) {
IERC1155 token = IERC1155(
self.inputRequirements[_inputIndex].token
);
token.safeTransferFrom(
_fromAddress,
self.pool,
self.inputRequirements[_inputIndex].tokenId,
self.inputRequirements[_inputIndex].minVal * (_quantity),
""
);
} else if (
self.inputRequirements[_inputIndex].inputType ==
INFTComplexGemPool.RequirementType.POOL
) {
gemtoken = checkGemRequirement(
self,
_inputIndex,
_fromAddress,
_quantity
);
}
}
if (self.claimIds[_claimHash].length > 0 && gemtoken != address(0)) {
IERC1155(gemtoken).safeBatchTransferFrom(
_fromAddress,
self.pool,
self.claimIds[_claimHash],
self.claimQuantities[_claimHash],
""
);
}
}
/**
* @dev Return the returnable input requirements for claimhash to account
*/
function returnInputReqsTo(
ComplexPoolData storage self,
uint256 _claimHash,
address _toAddress,
uint256 _quantity
) internal {
address gemtoken;
for (uint256 i = 0; i < self.inputRequirements.length; i++) {
if (
self.inputRequirements[i].inputType ==
INFTComplexGemPool.RequirementType.ERC20 &&
self.inputRequirements[i].burn == false &&
self.inputRequirements[i].takeCustody == true
) {
IERC20 token = IERC20(self.inputRequirements[i].token);
token.transferFrom(
self.pool,
_toAddress,
self.inputRequirements[i].minVal * (_quantity)
);
} else if (
self.inputRequirements[i].inputType ==
INFTComplexGemPool.RequirementType.ERC1155 &&
self.inputRequirements[i].burn == false &&
self.inputRequirements[i].takeCustody == true
) {
IERC1155 token = IERC1155(self.inputRequirements[i].token);
token.safeTransferFrom(
self.pool,
_toAddress,
self.inputRequirements[i].tokenId,
self.inputRequirements[i].minVal * (_quantity),
""
);
} else if (
self.inputRequirements[i].inputType ==
INFTComplexGemPool.RequirementType.POOL &&
self.inputRequirements[i].burn == false &&
self.inputRequirements[i].takeCustody == true
) {
gemtoken = self.inputRequirements[i].token;
}
}
if (self.claimIds[_claimHash].length > 0 && gemtoken != address(0)) {
IERC1155(gemtoken).safeBatchTransferFrom(
self.pool,
_toAddress,
self.claimIds[_claimHash],
self.claimQuantities[_claimHash],
""
);
}
}
/**
* @dev add an input requirement for this token
*/
function addInputRequirement(
ComplexPoolData storage self,
address token,
address pool,
INFTComplexGemPool.RequirementType inputType,
uint256 tokenId,
uint256 minAmount,
bool takeCustody,
bool burn,
bool exactAmount
) public {
require(token != address(0), "INVALID_TOKEN");
require(
inputType == INFTComplexGemPool.RequirementType.ERC20 ||
inputType == INFTComplexGemPool.RequirementType.ERC1155 ||
inputType == INFTComplexGemPool.RequirementType.POOL,
"INVALID_INPUTTYPE"
);
require(
(inputType == INFTComplexGemPool.RequirementType.POOL &&
pool != address(0)) ||
inputType != INFTComplexGemPool.RequirementType.POOL,
"INVALID_POOL"
);
require(
(inputType == INFTComplexGemPool.RequirementType.ERC20 &&
tokenId == 0) ||
inputType == INFTComplexGemPool.RequirementType.ERC1155 ||
(inputType == INFTComplexGemPool.RequirementType.POOL &&
tokenId == 0),
"INVALID_TOKENID"
);
require(minAmount != 0, "ZERO_AMOUNT");
require(!(!takeCustody && burn), "INVALID_TOKENSTATE");
self.inputRequirements.push(
INFTComplexGemPoolData.InputRequirement(
token,
pool,
inputType,
tokenId,
minAmount,
takeCustody,
burn,
exactAmount
)
);
}
/**
* @dev update input requirement at index
*/
function updateInputRequirement(
ComplexPoolData storage self,
uint256 _index,
address _tokenAddress,
address _poolAddress,
INFTComplexGemPool.RequirementType _inputRequirementType,
uint256 _tokenId,
uint256 _minAmount,
bool _takeCustody,
bool _burn,
bool _exactAmount
) public {
require(_index < self.inputRequirements.length, "OUT_OF_RANGE");
require(_tokenAddress != address(0), "INVALID_TOKEN");
require(
_inputRequirementType == INFTComplexGemPool.RequirementType.ERC20 ||
_inputRequirementType ==
INFTComplexGemPool.RequirementType.ERC1155 ||
_inputRequirementType ==
INFTComplexGemPool.RequirementType.POOL,
"INVALID_INPUTTYPE"
);
require(
(_inputRequirementType == INFTComplexGemPool.RequirementType.POOL &&
_poolAddress != address(0)) ||
_inputRequirementType !=
INFTComplexGemPool.RequirementType.POOL,
"INVALID_POOL"
);
require(
(_inputRequirementType ==
INFTComplexGemPool.RequirementType.ERC20 &&
_tokenId == 0) ||
_inputRequirementType ==
INFTComplexGemPool.RequirementType.ERC1155 ||
(_inputRequirementType ==
INFTComplexGemPool.RequirementType.POOL &&
_tokenId == 0),
"INVALID_TOKENID"
);
require(_minAmount != 0, "ZERO_AMOUNT");
require(!(!_takeCustody && _burn), "INVALID_TOKENSTATE");
self.inputRequirements[_index] = INFTComplexGemPoolData
.InputRequirement(
_tokenAddress,
_poolAddress,
_inputRequirementType,
_tokenId,
_minAmount,
_takeCustody,
_burn,
_exactAmount
);
}
/**
* @dev count of input requirements
*/
function allInputRequirementsLength(ComplexPoolData storage self)
public
view
returns (uint256)
{
return self.inputRequirements.length;
}
/**
* @dev input requirements at index
*/
function allInputRequirements(ComplexPoolData storage self, uint256 _index)
public
view
returns (
address,
address,
INFTComplexGemPool.RequirementType,
uint256,
uint256,
bool,
bool,
bool
)
{
require(_index < self.inputRequirements.length, "OUT_OF_RANGE");
INFTComplexGemPoolData.InputRequirement memory req = self
.inputRequirements[_index];
return (
req.token,
req.pool,
req.inputType,
req.tokenId,
req.minVal,
req.takeCustody,
req.burn,
req.exactAmount
);
}
/**
* @dev attempt to create a claim using the given timeframe with count
*/
function createClaims(
ComplexPoolData storage self,
uint256 _timeframe,
uint256 _count
) public {
// enabled
require(self.enabled == true, "DISABLED");
// minimum timeframe
require(_timeframe >= self.minTime, "TIMEFRAME_TOO_SHORT");
// no ETH
require(msg.value != 0, "ZERO_BALANCE");
// zero qty
require(_count != 0, "ZERO_QUANTITY");
// maximum timeframe
require(
(self.maxTime != 0 && _timeframe <= self.maxTime) ||
self.maxTime == 0,
"TIMEFRAME_TOO_LONG"
);
// max quantity per claim
require(
(self.maxQuantityPerClaim != 0 &&
_count <= self.maxQuantityPerClaim) ||
self.maxQuantityPerClaim == 0,
"MAX_QUANTITY_EXCEEDED"
);
require(
(self.maxClaimsPerAccount != 0 &&
self.claimsMade[msg.sender] < self.maxClaimsPerAccount) ||
self.maxClaimsPerAccount == 0,
"MAX_QUANTITY_EXCEEDED"
);
uint256 adjustedBalance = msg.value / (_count);
// cost given this timeframe
uint256 cost = (self.ethPrice * (self.minTime)) / (_timeframe);
require(adjustedBalance >= cost, "INSUFFICIENT_ETH");
// get the nest claim hash, revert if no more claims
uint256 claimHash = nextClaimHash(self);
require(claimHash != 0, "NO_MORE_CLAIMABLE");
// require the user to have the input requirements
requireInputReqs(self, msg.sender, _count);
// mint the new claim to the caller's address
INFTGemMultiToken(self.multitoken).mint(msg.sender, claimHash, 1);
INFTGemMultiToken(self.multitoken).setTokenData(
claimHash,
INFTGemMultiToken.TokenType.CLAIM,
address(this)
);
addToken(self, claimHash, INFTGemMultiToken.TokenType.CLAIM);
// record the claim unlock time and cost paid for this claim
uint256 claimUnlockTimestamp = block.timestamp + (_timeframe);
self.claimLockTimestamps[claimHash] = claimUnlockTimestamp;
self.claimAmountPaid[claimHash] = cost * (_count);
self.claimQuant[claimHash] = _count;
self.claimsMade[msg.sender] = self.claimsMade[msg.sender] + (1);
// tranasfer NFT input requirements from user to pool
takeInputReqsFrom(self, claimHash, msg.sender, _count);
// emit an event about it
emit NFTGemClaimCreated(
msg.sender,
address(self.pool),
claimHash,
_timeframe,
_count,
cost
);
// increase the staked eth balance
self.totalStakedEth = self.totalStakedEth + (cost * (_count));
// return the extra to sender
if (msg.value > cost * (_count)) {
(bool success, ) = payable(msg.sender).call{
value: msg.value - (cost * (_count))
}("");
require(success, "REFUND_FAILED");
}
}
function getPoolFee(ComplexPoolData storage self, address tokenUsed)
internal
view
returns (uint256)
{
// get the fee for this pool if it exists
uint256 poolDivFeeHash = uint256(
keccak256(abi.encodePacked("pool_fee", address(self.pool)))
);
uint256 poolFee = INFTGemFeeManager(self.feeTracker).fee(
poolDivFeeHash
);
// get the pool fee for this token if it exists
uint256 poolTokenFeeHash = uint256(
keccak256(abi.encodePacked("pool_fee", address(tokenUsed)))
);
uint256 poolTokenFee = INFTGemFeeManager(self.feeTracker).fee(
poolTokenFeeHash
);
// get the default fee amoutn for this token
uint256 defaultFeeHash = uint256(
keccak256(abi.encodePacked("pool_fee"))
);
uint256 defaultFee = INFTGemFeeManager(self.feeTracker).fee(
defaultFeeHash
);
defaultFee = defaultFee == 0 ? 2000 : defaultFee;
// get the fee, preferring the token fee if available
uint256 feeNum = poolFee != poolTokenFee
? (poolTokenFee != 0 ? poolTokenFee : poolFee)
: poolFee;
// set the fee to default if it is 0
return feeNum == 0 ? defaultFee : feeNum;
}
function getMinimumLiquidity(
ComplexPoolData storage self,
address tokenUsed
) internal view returns (uint256) {
// get the fee for this pool if it exists
uint256 poolDivFeeHash = uint256(
keccak256(abi.encodePacked("min_liquidity", address(self.pool)))
);
uint256 poolFee = INFTGemFeeManager(self.feeTracker).fee(
poolDivFeeHash
);
// get the pool fee for this token if it exists
uint256 poolTokenFeeHash = uint256(
keccak256(abi.encodePacked("min_liquidity", address(tokenUsed)))
);
uint256 poolTokenFee = INFTGemFeeManager(self.feeTracker).fee(
poolTokenFeeHash
);
// get the default fee amoutn for this token
uint256 defaultFeeHash = uint256(
keccak256(abi.encodePacked("min_liquidity"))
);
uint256 defaultFee = INFTGemFeeManager(self.feeTracker).fee(
defaultFeeHash
);
defaultFee = defaultFee == 0 ? 50 : defaultFee;
// get the fee, preferring the token fee if available
uint256 feeNum = poolFee != poolTokenFee
? (poolTokenFee != 0 ? poolTokenFee : poolFee)
: poolFee;
// set the fee to default if it is 0
return feeNum == 0 ? defaultFee : feeNum;
}
/**
* @dev crate multiple gem claim using an erc20 token. this token must be tradeable in Uniswap or this call will fail
*/
function createERC20Claims(
ComplexPoolData storage self,
address erc20token,
uint256 tokenAmount,
uint256 count
) public {
// enabled
require(self.enabled == true, "DISABLED");
// must be a valid address
require(erc20token != address(0), "INVALID_ERC20_TOKEN");
// token is allowed
require(
(self.allowedTokens.count() > 0 &&
self.allowedTokens.exists(erc20token)) ||
self.allowedTokens.count() == 0,
"TOKEN_DISALLOWED"
);
// zero qty
require(count != 0, "ZERO_QUANTITY");
// max quantity per claim
require(
(self.maxQuantityPerClaim != 0 &&
count <= self.maxQuantityPerClaim) ||
self.maxQuantityPerClaim == 0,
"MAX_QUANTITY_EXCEEDED"
);
require(
(self.maxClaimsPerAccount != 0 &&
self.claimsMade[msg.sender] < self.maxClaimsPerAccount) ||
self.maxClaimsPerAccount == 0,
"MAX_QUANTITY_EXCEEDED"
);
// require the user to have the input requirements
requireInputReqs(self, msg.sender, count);
// Uniswap pool must exist
require(
ISwapQueryHelper(self.swapHelper).hasPool(erc20token) == true,
"NO_UNISWAP_POOL"
);
// must have an amount specified
require(tokenAmount >= 0, "NO_PAYMENT_INCLUDED");
// get a quote in ETH for the given token.
(
uint256 ethereum,
uint256 tokenReserve,
uint256 ethReserve
) = ISwapQueryHelper(self.swapHelper).coinQuote(
erc20token,
tokenAmount / (count)
);
// TODO: update liquidity multiple from fee manager
if (self.validateerc20 == true) {
uint256 minLiquidity = getMinimumLiquidity(self, erc20token);
// make sure the convertible amount is has reserves > 100x the token
require(
ethReserve >= ethereum * minLiquidity * (count),
"INSUFFICIENT_ETH_LIQUIDITY"
);
// make sure the convertible amount is has reserves > 100x the token
require(
tokenReserve >= tokenAmount * minLiquidity * (count),
"INSUFFICIENT_TOKEN_LIQUIDITY"
);
}
// make sure the convertible amount is less than max price
require(ethereum <= self.ethPrice, "OVERPAYMENT");
// calculate the maturity time given the converted eth
uint256 maturityTime = (self.ethPrice * (self.minTime)) / (ethereum);
// make sure the convertible amount is less than max price
require(maturityTime >= self.minTime, "INSUFFICIENT_TIME");
// get the next claim hash, revert if no more claims
uint256 claimHash = nextClaimHash(self);
require(claimHash != 0, "NO_MORE_CLAIMABLE");
// mint the new claim to the caller's address
INFTGemMultiToken(self.multitoken).mint(msg.sender, claimHash, 1);
INFTGemMultiToken(self.multitoken).setTokenData(
claimHash,
INFTGemMultiToken.TokenType.CLAIM,
address(this)
);
addToken(self, claimHash, INFTGemMultiToken.TokenType.CLAIM);
// record the claim unlock time and cost paid for this claim
uint256 claimUnlockTimestamp = block.timestamp + (maturityTime);
self.claimLockTimestamps[claimHash] = claimUnlockTimestamp;
self.claimAmountPaid[claimHash] = ethereum;
self.claimLockToken[claimHash] = erc20token;
self.claimTokenAmountPaid[claimHash] = tokenAmount;
self.claimQuant[claimHash] = count;
self.claimsMade[msg.sender] = self.claimsMade[msg.sender] + (1);
// tranasfer NFT input requirements from user to pool
takeInputReqsFrom(self, claimHash, msg.sender, count);
// increase staked eth amount
self.totalStakedEth = self.totalStakedEth + (ethereum);
// emit a message indicating that an erc20 claim has been created
emit NFTGemERC20ClaimCreated(
msg.sender,
address(self.pool),
claimHash,
maturityTime,
erc20token,
count,
ethereum
);
// transfer the caller's ERC20 tokens into the pool
IERC20(erc20token).transferFrom(
msg.sender,
address(self.pool),
tokenAmount
);
}
/**
* @dev collect an open claim (take custody of the funds the claim is redeeemable for and maybe a gem too)
*/
function collectClaim(
ComplexPoolData storage self,
uint256 _claimHash,
bool _requireMature
) public {
// enabled
require(self.enabled == true, "DISABLED");
// check the maturity of the claim - only issue gem if mature
uint256 unlockTime = self.claimLockTimestamps[_claimHash];
bool isMature = unlockTime < block.timestamp;
require(
!_requireMature || (_requireMature && isMature),
"IMMATURE_CLAIM"
);
__collectClaim(self, _claimHash);
}
/**
* @dev collect an open claim (take custody of the funds the claim is redeeemable for and maybe a gem too)
*/
function __collectClaim(ComplexPoolData storage self, uint256 claimHash)
internal
{
// validation checks - disallow if not owner (holds coin with claimHash)
// or if the unlockTime amd unlockPaid data is in an invalid state
require(
IERC1155(self.multitoken).balanceOf(msg.sender, claimHash) == 1,
"NOT_CLAIM_OWNER"
);
uint256 unlockTime = self.claimLockTimestamps[claimHash];
uint256 unlockPaid = self.claimAmountPaid[claimHash];
require(unlockTime != 0 && unlockPaid > 0, "INVALID_CLAIM");
// grab the erc20 token info if there is any
address tokenUsed = self.claimLockToken[claimHash];
uint256 unlockTokenPaid = self.claimTokenAmountPaid[claimHash];
// check the maturity of the claim - only issue gem if mature
bool isMature = unlockTime < block.timestamp;
// burn claim and transfer money back to user
INFTGemMultiToken(self.multitoken).burn(msg.sender, claimHash, 1);
// if they used erc20 tokens stake their claim, return their tokens
if (tokenUsed != address(0)) {
// calculate fee portion using fee tracker
uint256 feePortion = 0;
if (isMature == true) {
feePortion = unlockTokenPaid / getPoolFee(self, tokenUsed);
}
// assess a fee for minting the NFT. Fee is collectec in fee tracker
IERC20(tokenUsed).transferFrom(
address(self.pool),
self.feeTracker,
feePortion
);
// send the principal minus fees to the caller
IERC20(tokenUsed).transferFrom(
address(self.pool),
msg.sender,
unlockTokenPaid - (feePortion)
);
// emit an event that the claim was redeemed for ERC20
emit NFTGemERC20ClaimRedeemed(
msg.sender,
address(self.pool),
claimHash,
tokenUsed,
unlockPaid,
unlockTokenPaid,
self.claimQuant[claimHash],
feePortion
);
} else {
// calculate fee portion using fee tracker
uint256 feePortion = 0;
if (isMature == true) {
feePortion = unlockPaid / getPoolFee(self, address(0));
}
// transfer the ETH fee to fee tracker
payable(self.feeTracker).transfer(feePortion);
// transfer the ETH back to user
payable(msg.sender).transfer(unlockPaid - (feePortion));
// emit an event that the claim was redeemed for ETH
emit NFTGemClaimRedeemed(
msg.sender,
address(self.pool),
claimHash,
unlockPaid,
self.claimQuant[claimHash],
feePortion
);
}
// tranasfer NFT input requirements from pool to user
returnInputReqsTo(
self,
claimHash,
msg.sender,
self.claimQuant[claimHash]
);
// deduct the total staked ETH balance of the pool
self.totalStakedEth = self.totalStakedEth - (unlockPaid);
// if all this is happening before the unlocktime then we exit
// without minting a gem because the user is withdrawing early
if (!isMature) {
return;
}
// get the next gem hash, increase the staking sifficulty
// for the pool, and mint a gem token back to account
uint256 nextHash = nextGemHash(self);
// associate gem and claim
self.gemClaims[nextHash] = claimHash;
// mint the gem
INFTGemMultiToken(self.multitoken).mint(
msg.sender,
nextHash,
self.claimQuant[claimHash]
);
addToken(self, nextHash, INFTGemMultiToken.TokenType.GEM);
// emit an event about a gem getting created
emit NFTGemCreated(
msg.sender,
address(self.pool),
claimHash,
nextHash,
self.claimQuant[claimHash]
);
}
/**
* @dev purchase gem(s) at the listed pool price
*/
function purchaseGems(
ComplexPoolData storage self,
address sender,
uint256 value,
uint256 count
) public {
// enabled
require(self.enabled == true, "DISABLED");
// non-zero balance
require(value != 0, "ZERO_BALANCE");
// non-zero quantity
require(count != 0, "ZERO_QUANTITY");
// sufficient input eth
uint256 adjustedBalance = value / (count);
require(adjustedBalance >= self.ethPrice, "INSUFFICIENT_ETH");
require(self.allowPurchase == true, "PURCHASE_DISALLOWED");
// get the next gem hash, increase the staking sifficulty
// for the pool, and mint a gem token back to account
uint256 nextHash = nextGemHash(self);
// mint the gem
INFTGemMultiToken(self.multitoken).mint(sender, nextHash, count);
addToken(self, nextHash, INFTGemMultiToken.TokenType.GEM);
// transfer the funds for the gem to the fee tracker
payable(self.feeTracker).transfer(value);
// emit an event about a gem getting created
emit NFTGemCreated(sender, address(self.pool), 0, nextHash, count);
}
/**
* @dev create a token of token hash / token type
*/
function addToken(
ComplexPoolData storage self,
uint256 tokenHash,
INFTGemMultiToken.TokenType tokenType
) public {
require(
tokenType == INFTGemMultiToken.TokenType.CLAIM ||
tokenType == INFTGemMultiToken.TokenType.GEM,
"INVALID_TOKENTYPE"
);
self.tokenHashes.push(tokenHash);
self.tokenTypes[tokenHash] = tokenType;
self.tokenIds[tokenHash] = tokenType ==
INFTGemMultiToken.TokenType.CLAIM
? nextClaimId(self)
: nextGemId(self);
INFTGemMultiToken(self.multitoken).setTokenData(
tokenHash,
tokenType,
address(this)
);
if (tokenType == INFTGemMultiToken.TokenType.GEM) {
increaseDifficulty(self);
}
}
/**
* @dev get the next claim id
*/
function nextClaimId(ComplexPoolData storage self)
public
returns (uint256)
{
uint256 ncId = self.nextClaimIdVal;
self.nextClaimIdVal = self.nextClaimIdVal + (1);
return ncId;
}
/**
* @dev get the next gem id
*/
function nextGemId(ComplexPoolData storage self) public returns (uint256) {
uint256 ncId = self.nextGemIdVal;
self.nextGemIdVal = self.nextGemIdVal + (1);
return ncId;
}
/**
* @dev increase the pool's difficulty by calculating the step increase portion and adding it to the eth price of the market
*/
function increaseDifficulty(ComplexPoolData storage self) public {
if (
self.priceIncrementType ==
INFTComplexGemPoolData.PriceIncrementType.COMPOUND
) {
uint256 diffIncrease = self.ethPrice / (self.diffstep);
self.ethPrice = self.ethPrice + (diffIncrease);
} else if (
self.priceIncrementType ==
INFTComplexGemPoolData.PriceIncrementType.INVERSELOG
) {
uint256 diffIncrease = self.diffstep / (self.ethPrice);
self.ethPrice = self.ethPrice + (diffIncrease);
}
}
/**
* @dev the hash of the next gem to be minted
*/
function nextGemHash(ComplexPoolData storage self)
public
view
returns (uint256)
{
return
uint256(
keccak256(
abi.encodePacked(
"gem",
address(self.pool),
self.nextGemIdVal
)
)
);
}
/**
* @dev the hash of the next claim to be minted
*/
function nextClaimHash(ComplexPoolData storage self)
public
view
returns (uint256)
{
return
(self.maxClaims != 0 && self.nextClaimIdVal <= self.maxClaims) ||
self.maxClaims == 0
? uint256(
keccak256(
abi.encodePacked(
"claim",
address(self.pool),
self.nextClaimIdVal
)
)
)
: 0;
}
/**
* @dev get the token hash at index
*/
function allTokenHashes(ComplexPoolData storage self, uint256 ndx)
public
view
returns (uint256)
{
return self.tokenHashes[ndx];
}
/**
* @dev return the claim amount paid for this claim
*/
function claimAmount(ComplexPoolData storage self, uint256 claimHash)
public
view
returns (uint256)
{
return self.claimAmountPaid[claimHash];
}
/**
* @dev the claim quantity (count of gems staked) for the given claim hash
*/
function claimQuantity(ComplexPoolData storage self, uint256 claimHash)
public
view
returns (uint256)
{
return self.claimQuant[claimHash];
}
/**
* @dev the lock time for this claim hash. once past lock time a gem is minted
*/
function claimUnlockTime(ComplexPoolData storage self, uint256 claimHash)
public
view
returns (uint256)
{
return self.claimLockTimestamps[claimHash];
}
/**
* @dev return the claim token amount for this claim hash
*/
function claimTokenAmount(ComplexPoolData storage self, uint256 claimHash)
public
view
returns (uint256)
{
return self.claimTokenAmountPaid[claimHash];
}
/**
* @dev return the claim hash of the given gemhash
*/
function gemClaimHash(ComplexPoolData storage self, uint256 gemHash)
public
view
returns (uint256)
{
return self.gemClaims[gemHash];
}
/**
* @dev return the token that was staked to create the given token hash. 0 if the native token
*/
function stakedToken(ComplexPoolData storage self, uint256 claimHash)
public
view
returns (address)
{
return self.claimLockToken[claimHash];
}
/**
* @dev add a token that is allowed to be used to create a claim
*/
function addAllowedToken(ComplexPoolData storage self, address token)
public
{
if (!self.allowedTokens.exists(token)) {
self.allowedTokens.insert(token);
}
}
/**
* @dev remove a token that is allowed to be used to create a claim
*/
function removeAllowedToken(ComplexPoolData storage self, address token)
public
{
if (self.allowedTokens.exists(token)) {
self.allowedTokens.remove(token);
}
}
/**
* @dev deposit into pool
*/
function deposit(
ComplexPoolData storage self,
address erc20token,
uint256 tokenAmount
) public {
if (erc20token == address(0)) {
require(msg.sender.balance >= tokenAmount, "INSUFFICIENT_BALANCE");
self.totalStakedEth = self.totalStakedEth + (msg.sender.balance);
} else {
require(
IERC20(erc20token).balanceOf(msg.sender) >= tokenAmount,
"INSUFFICIENT_BALANCE"
);
IERC20(erc20token).transferFrom(
msg.sender,
address(self.pool),
tokenAmount
);
}
}
/**
* @dev deposit NFT into pool
*/
function depositNFT(
ComplexPoolData storage self,
address erc1155token,
uint256 tokenId,
uint256 tokenAmount
) public {
require(
IERC1155(erc1155token).balanceOf(msg.sender, tokenId) >=
tokenAmount,
"INSUFFICIENT_BALANCE"
);
IERC1155(erc1155token).safeTransferFrom(
msg.sender,
address(self.pool),
tokenId,
tokenAmount,
""
);
}
/**
* @dev withdraw pool contents
*/
function withdraw(
ComplexPoolData storage self,
address erc20token,
address destination,
uint256 tokenAmount
) public {
require(destination != address(0), "ZERO_ADDRESS");
require(
self.controllers[msg.sender] == true || msg.sender == self.governor,
"UNAUTHORIZED"
);
if (erc20token == address(0)) {
payable(destination).transfer(tokenAmount);
} else {
IERC20(erc20token).transferFrom(
address(self.pool),
address(destination),
tokenAmount
);
}
}
/**
* @dev withdraw pool NFT
*/
function withdrawNFT(
ComplexPoolData storage self,
address erc1155token,
address destination,
uint256 tokenId,
uint256 tokenAmount
) public {
require(
self.controllers[msg.sender] == true || msg.sender == self.governor,
"UNAUTHORIZED"
);
require(erc1155token != address(0), "ZERO_ADDRESS");
require(destination != address(0), "ZERO_ADDRESS");
require(
IERC1155(erc1155token).balanceOf(address(self.pool), tokenId) >=
tokenAmount,
"INSUFFICIENT_BALANCE"
);
IERC1155(erc1155token).safeTransferFrom(
address(self.pool),
address(destination),
tokenId,
tokenAmount,
""
);
}
/**
* @dev mint the genesis gems earned by the pools creator and funder
*/
function mintGenesisGems(
ComplexPoolData storage self,
address creator,
address funder
) public {
require(self.multitoken != address(0), "NO_MULTITOKEN");
require(
creator != address(0) && funder != address(0),
"ZERO_DESTINATION"
);
require(self.nextGemIdVal == 0, "ALREADY_MINTED");
uint256 gemHash = nextGemHash(self);
INFTGemMultiToken(self.multitoken).mint(creator, gemHash, 1);
addToken(self, gemHash, INFTGemMultiToken.TokenType.GEM);
// emit an event about a gem getting created
emit NFTGemCreated(creator, address(self.pool), 0, gemHash, 1);
gemHash = nextGemHash(self);
INFTGemMultiToken(self.multitoken).mint(funder, gemHash, 1);
addToken(self, gemHash, INFTGemMultiToken.TokenType.GEM);
// emit an event about a gem getting created
emit NFTGemCreated(funder, address(self.pool), 0, gemHash, 1);
}
}
|
the claim quantity (count of gems staked) for the given claim hash/
|
function claimQuantity(ComplexPoolData storage self, uint256 claimHash)
public
view
returns (uint256)
{
return self.claimQuant[claimHash];
}
| 15,863,495
|
pragma solidity 0.5.16;
import './TrustlessFund.sol';
import "@openzeppelin/contracts/ownership/Ownable.sol";
contract TrustlessFundFactory is Ownable {
/*** STORAGE VARIABLES ***/
/**
* @notice Maps unique IDs to funds.
*/
mapping(uint => address) funds;
/**
* @notice Maps user address to their corresponding funds.
*/
mapping(address => address[]) userFunds;
/**
* @notice Get the next fund ID.
*/
uint public nextId;
/**
* @notice The fee, in wei, charged to open a contract.
Note: This will remain 0 indefinitely.
*/
uint public fee;
/**
* @notice The total amount of fees, in wei, collected.
*/
uint public feesAccrued;
/*** EVENTS ***/
/**
* @notice Emits when a fund is created.
*/
event CreateFund(
uint expiration,
address indexed beneficiary,
address indexed owner
);
/*** PURE/VIEW FUNCTIONS ***/
/**
* @dev Given an id, return the corresponding fund address.
* @param _id The id of the fund.
*/
function getFund(uint _id) public view returns(address) {
return funds[_id];
}
/**
* @dev Given a user address, return all owned funds.
* @param _user The address of the user.
*/
function getUserFunds(address _user) public view returns(address[] memory) {
return userFunds[_user];
}
/**
* @dev Returns the fee, in wei, to open a contract.
*/
function getFee() public view returns(uint) {
return fee;
}
/*** OTHER FUNCTIONS ***/
/**
* @dev Deploy a TrustlessFund contract.
* @param _expiration Date time in seconds when timelock expires.
* @param _beneficiary Address permitted to withdraw funds after unlock.
*/
function createFund(uint _expiration, address _beneficiary) public payable returns(uint) {
require(funds[nextId] == address(0), 'id already in use');
require(msg.value == fee, 'must pay fee');
TrustlessFund fund = new TrustlessFund(_expiration, _beneficiary, msg.sender);
funds[nextId] = address(fund);
userFunds[msg.sender].push(address(fund));
nextId++;
emit CreateFund(_expiration, _beneficiary, msg.sender);
return nextId - 1;
}
/**
* @dev Sets the fee, in wei, to open a contract.
* @param _newFee The new fee, in wei.
*/
function setFee(uint _newFee) public onlyOwner() {
fee = _newFee;
}
/**
* @dev Collect accrued fees.
* @param _amount The amount to collect, in wei.
*/
function collectFees(uint _amount) public onlyOwner() {
require(feesAccrued > 0, 'no fees accrued');
feesAccrued -= _amount;
(bool success, ) = msg.sender.call.value(_amount)("");
require(success, "Transfer failed.");
}
}
|
Deploy a TrustlessFund contract. _expiration Date time in seconds when timelock expires. _beneficiary Address permitted to withdraw funds after unlock./
|
function createFund(uint _expiration, address _beneficiary) public payable returns(uint) {
require(funds[nextId] == address(0), 'id already in use');
require(msg.value == fee, 'must pay fee');
TrustlessFund fund = new TrustlessFund(_expiration, _beneficiary, msg.sender);
funds[nextId] = address(fund);
userFunds[msg.sender].push(address(fund));
nextId++;
emit CreateFund(_expiration, _beneficiary, msg.sender);
return nextId - 1;
}
| 933,201
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import { Lib_PredeployAddresses } from "../libraries/Lib_PredeployAddresses.sol";
import { StandardBridge } from "../universal/StandardBridge.sol";
import { OptimismMintableERC20 } from "../universal/OptimismMintableERC20.sol";
/**
* @title L2StandardBridge
* @dev This contract is an L2 predeploy that is responsible for facilitating
* deposits of tokens from L1 to L2.
* TODO: ensure that this has 1:1 backwards compatibility
*/
contract L2StandardBridge is StandardBridge {
/**********
* Events *
**********/
event WithdrawalInitiated(
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
event DepositFinalized(
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
event DepositFailed(
address indexed _l1Token,
address indexed _l2Token,
address indexed _from,
address _to,
uint256 _amount,
bytes _data
);
/********************
* Public Functions *
********************/
/**
* @notice Initialize the L2StandardBridge. This must only be callable
* once. `_initialize` ensures this.
*/
function initialize(address payable _otherBridge) public {
_initialize(payable(Lib_PredeployAddresses.L2_CROSS_DOMAIN_MESSENGER), _otherBridge);
}
/**
* @notice Withdraw tokens to self on L1
* @param _l2Token The L2 token address to withdraw
* @param _amount The amount of L2 token to withdraw
* @param _minGasLimit The min gas limit in the withdrawing call
* @param _data Additional calldata to pass along
*/
function withdraw(
address _l2Token,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _data
) external payable virtual {
_initiateWithdrawal(_l2Token, msg.sender, msg.sender, _amount, _minGasLimit, _data);
}
/**
* @notice Withdraw tokens to an address on L1
* @param _l2Token The L2 token address to withdraw
* @param _to The L1 account to withdraw to
* @param _amount The amount of L2 token to withdraw
* @param _minGasLimit The min gas limit in the withdrawing call
* @param _data Additional calldata to pass along
*/
function withdrawTo(
address _l2Token,
address _to,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _data
) external payable virtual {
_initiateWithdrawal(_l2Token, msg.sender, _to, _amount, _minGasLimit, _data);
}
/**
* @notice Finalize the L1 to L2 deposit. This should only be callable by
* a deposit through the L1StandardBridge.
* @param _l1Token The L1 token address
* @param _l2Token The corresponding L2 token address
* @param _from The sender of the tokens
* @param _to The recipient of the tokens
* @param _amount The amount of tokens
* @param _data Additional calldata
*/
function finalizeDeposit(
address _l1Token,
address _l2Token,
address _from,
address _to,
uint256 _amount,
bytes calldata _data
) external payable virtual {
if (_l1Token == address(0) && _l2Token == Lib_PredeployAddresses.OVM_ETH) {
finalizeBridgeETH(_from, _to, _amount, _data);
} else {
finalizeBridgeERC20(_l2Token, _l1Token, _from, _to, _amount, _data);
}
emit DepositFinalized(_l1Token, _l2Token, _from, _to, _amount, _data);
}
/**********************
* Internal Functions *
**********************/
/**
* @notice Handle withdrawals, taking into account the legacy form of ETH
* when it was represented as an ERC20 at the OVM_ETH contract.
* TODO: require(msg.value == _value) for OVM_ETH case?
*/
function _initiateWithdrawal(
address _l2Token,
address _from,
address _to,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _data
) internal {
address l1Token = OptimismMintableERC20(_l2Token).l1Token();
if (_l2Token == Lib_PredeployAddresses.OVM_ETH) {
_initiateBridgeETH(_from, _to, _amount, _minGasLimit, _data);
} else {
_initiateBridgeERC20(_l2Token, l1Token, _from, _to, _amount, _minGasLimit, _data);
}
emit WithdrawalInitiated(l1Token, _l2Token, msg.sender, _to, _amount, _data);
}
}
|
Withdraw tokens to self on L1 _l2Token The L2 token address to withdraw _amount The amount of L2 token to withdraw _minGasLimit The min gas limit in the withdrawing call _data Additional calldata to pass along/
|
function withdraw(
address _l2Token,
uint256 _amount,
uint32 _minGasLimit,
bytes calldata _data
) external payable virtual {
_initiateWithdrawal(_l2Token, msg.sender, msg.sender, _amount, _minGasLimit, _data);
}
| 13,129,869
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.5;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "../yearn/interfaces/VaultApi.sol";
import "../yearn/interfaces/StrategyApi.sol";
/*
* BaseStrategy implements all of the required functionality to interoperate closely
* with the core protocol. This contract should be inherited and the abstract methods
* implemented to adapt the strategy to the particular needs it has to create a return.
*/
abstract contract BaseStrategy is StrategyAPI {
// Version of this contract's StrategyAPI (must match Vault)
function apiVersion() override public pure returns (string memory) {
return "0.1.3";
}
address override public vault;
address public strategist;
address override public keeper;
address override public want;
// So indexers can keep track of this
event Harvested(uint256 profit);
// The minimum number of blocks between harvest calls
// NOTE: Override this value with your own, or set dynamically below
uint256 public minReportDelay = 6300; // ~ once a day
// The minimum multiple that `callCost` must be above the credit/profit to be "justifiable"
// NOTE: Override this value with your own, or set dynamically below
uint256 public profitFactor = 100;
// Use this to adjust the threshold at which running a debt causes a harvest trigger
uint256 public debtThreshold = 0;
// Adjust this using `setReserve(...)` to keep some of the position in reserve in the strategy,
// to accomodate larger variations needed to sustain the strategy's core positon(s)
uint256 private reserve = 0;
/*
* Provide an accurate estimate for the total amount of assets (principle + return)
* that this strategy is currently managing, denominated in terms of `want` tokens.
* This total should be "realizable" e.g. the total value that could *actually* be
* obtained from this strategy if it were to divest it's entire position based on
* current on-chain conditions.
*
* NOTE: care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through flashloan
* attacks, oracle manipulations, or other DeFi attack mechanisms).
*
* NOTE: It is up to governance to use this function to correctly order this strategy
* relative to its peers in the withdrawal queue to minimize losses for the Vault
* based on sudden withdrawals. This value should be higher than the total debt of
* the strategy and higher than it's expected value to be "safe".
*/
function estimatedTotalAssets() override public view virtual returns (uint256);
function getReserve() internal view returns (uint256) {
return reserve;
}
function setReserve(uint256 _reserve) internal {
if (_reserve != reserve) reserve = _reserve;
}
bool public emergencyExit;
constructor(address _vault) {
vault = _vault;
want = VaultAPI(vault).token();
IERC20(want).approve(_vault, type(uint256).max); // Give Vault unlimited access (might save gas)
strategist = msg.sender;
keeper = msg.sender;
}
function setStrategist(address _strategist) external {
require(
msg.sender == strategist || msg.sender == governance(),
"!authorized"
);
strategist = _strategist;
}
function setKeeper(address _keeper) external {
require(
msg.sender == strategist || msg.sender == governance(),
"!authorized"
);
keeper = _keeper;
}
function setMinReportDelay(uint256 _delay) external {
require(
msg.sender == strategist || msg.sender == governance(),
"!authorized"
);
minReportDelay = _delay;
}
function setProfitFactor(uint256 _profitFactor) external {
require(
msg.sender == strategist || msg.sender == governance(),
"!authorized"
);
profitFactor = _profitFactor;
}
function setDebtThreshold(uint256 _debtThreshold) external {
require(
msg.sender == strategist || msg.sender == governance(),
"!authorized"
);
debtThreshold = _debtThreshold;
}
/*
* Resolve governance address from Vault contract, used to make
* assertions on protected functions in the Strategy
*/
function governance() internal view returns (address) {
return VaultAPI(vault).governance();
}
/*
* Perform any strategy unwinding or other calls necessary to capture
* the "free return" this strategy has generated since the last time it's
* core position(s) were adusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and should
* be optimized to minimize losses as much as possible. It is okay to report
* "no returns", however this will affect the credit limit extended to the
* strategy and reduce it's overall position if lower than expected returns
* are sustained for long periods of time.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (uint256 _profit);
/*
* Perform any adjustments to the core position(s) of this strategy given
* what change the Vault made in the "investable capital" available to the
* strategy. Note that all "free capital" in the strategy after the report
* was made is available for reinvestment. Also note that this number could
* be 0, and you should handle that scenario accordingly.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/*
* Make as much capital as possible "free" for the Vault to take. Some slippage
* is allowed, since when this method is called the strategist is no longer receiving
* their performance fee. The goal is for the strategy to divest as quickly as possible
* while not suffering exorbitant losses. This function is used during emergency exit
* instead of `prepareReturn()`
*/
function exitPosition() internal virtual;
/*
* Vault calls this function after shares are created during `Vault.report()`.
* You can customize this function to any share distribution mechanism you want.
*/
function distributeRewards(uint256 _shares) external virtual {
// Send 100% of newly-minted shares to the strategist.
VaultAPI(vault).transfer(strategist, _shares);
}
/*
* Provide a signal to the keeper that `tend()` should be called. The keeper will provide
* the estimated gas cost that they would pay to call `tend()`, and this function should
* use that estimate to make a determination if calling it is "worth it" for the keeper.
* This is not the only consideration into issuing this trigger, for example if the position
* would be negatively affected if `tend()` is not called shortly, then this can return `true`
* even if the keeper might be "at a loss" (keepers are always reimbursed by Yearn)
*
* NOTE: `callCost` must be priced in terms of `want`
*
* NOTE: this call and `harvestTrigger` should never return `true` at the same time.
*/
function tendTrigger(uint256 callCost) override public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need active maintainence,
// overriding this function is how you would signal for that
return false;
}
function tend() override external {
if (keeper != address(0)) {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance(),
"!authorized"
);
}
// Don't take profits with this call, but adjust for better gains
adjustPosition(VaultAPI(vault).debtOutstanding());
}
/*
* Provide a signal to the keeper that `harvest()` should be called. The keeper will provide
* the estimated gas cost that they would pay to call `harvest()`, and this function should
* use that estimate to make a determination if calling it is "worth it" for the keeper.
* This is not the only consideration into issuing this trigger, for example if the position
* would be negatively affected if `harvest()` is not called shortly, then this can return `true`
* even if the keeper might be "at a loss" (keepers are always reimbursed by Yearn)
*
* NOTE: `callCost` must be priced in terms of `want`
*
* NOTE: this call and `tendTrigger` should never return `true` at the same time.
*/
function harvestTrigger(uint256 callCost)
override
public
view
virtual
returns (bool)
{
StrategyParams memory params = VaultAPI(vault).strategies(address(this));
// Should not trigger if strategy is not activated
if (params.activation == 0) return false;
// Should trigger if hadn't been called in a while
if (block.number - params.lastReport >= minReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is adjusted in step-wise fashion, it is appropiate to always trigger here,
// because the resulting change should be large (might not always be the case)
uint256 outstanding = VaultAPI(vault).debtOutstanding();
if (outstanding > 0) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total + debtThreshold < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total - params.totalDebt; // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost is <N% of value moved)
uint256 credit = VaultAPI(vault).creditAvailable();
return (profitFactor * callCost < credit + profit);
}
function harvest() override external {
if (keeper != address(0)) {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance(),
"!authorized"
);
}
uint256 profit = 0;
if (emergencyExit) {
exitPosition(); // Free up as much capital as possible
// NOTE: Don't take performance fee in this scenario
} else {
profit = prepareReturn(VaultAPI(vault).debtOutstanding()); // Free up returns for Vault to pull
}
if (reserve > IERC20(want).balanceOf(address(this)))
reserve = IERC20(want).balanceOf(address(this));
// Allow Vault to take up to the "harvested" balance of this contract, which is
// the amount it has earned since the last time it reported to the Vault
uint256 outstanding = VaultAPI(vault).report(
IERC20(want).balanceOf(address(this)) - reserve,
0, 0
);
// Check if free returns are left, and re-invest them
adjustPosition(outstanding);
emit Harvested(profit);
}
/*
* Liquidate as many assets as possible to `want`, irregardless of slippage,
* up to `_amountNeeded`. Any excess should be re-invested here as well.
*/
function liquidatePosition(uint256 _amountNeeded)
internal
virtual
returns (uint256 _amountFreed);
function withdraw(uint256 _amountNeeded) external {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amount`
uint256 amountFreed = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
IERC20(want).transfer(msg.sender, amountFreed);
// Adjust reserve to what we have after the freed amount is sent to the Vault
reserve = IERC20(want).balanceOf(address(this));
}
/*
* Do anything necesseary to prepare this strategy for migration, such
* as transfering any reserve or LP tokens, CDPs, or other tokens or stores of value.
*/
function prepareMigration(address _newStrategy) internal virtual;
function migrate(address _newStrategy) external {
require(msg.sender == address(vault) || msg.sender == governance());
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
IERC20(want).transfer(_newStrategy, IERC20(want).balanceOf(address(this)));
}
function setEmergencyExit() external {
require(
msg.sender == strategist || msg.sender == governance(),
"!authorized"
);
emergencyExit = true;
exitPosition();
VaultAPI(vault).revokeStrategy();
if (reserve > IERC20(want).balanceOf(address(this)))
reserve = IERC20(want).balanceOf(address(this));
}
// Override this to add all tokens/tokenized positions this contract manages
// on a *persistant* basis (e.g. not just for swapping back to want ephemerally)
// NOTE: Do *not* include `want`, already included in `sweep` below
//
// Example:
//
// function protectedTokens() internal override view returns (address[] memory) {
// address[] memory protected = new address[](3);
// protected[0] = tokenA;
// protected[1] = tokenB;
// protected[2] = tokenC;
// return protected;
// }
function protectedTokens() internal view virtual returns (address[] memory);
function sweep(address _token) external {
require(msg.sender == governance(), "!authorized");
require(_token != address(want), "!want");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++)
require(_token != _protectedTokens[i], "!protected");
IERC20(_token).transfer(
governance(),
IERC20(_token).balanceOf(address(this))
);
}
}
|
Resolve governance address from Vault contract, used to make assertions on protected functions in the Strategy/
|
function governance() internal view returns (address) {
return VaultAPI(vault).governance();
}
| 897,494
|
pragma solidity 0.5.17;
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "../interfaces/Comptroller.sol";
import "../interfaces/PriceOracle.sol";
import "../interfaces/CERC20.sol";
import "../interfaces/CEther.sol";
import "../Utils.sol";
contract CompoundOrder is Utils(address(0), address(0), address(0)), Ownable {
// Constants
uint256 internal constant NEGLIGIBLE_DEBT = 100; // we don't care about debts below 10^-4 USDC (0.1 cent)
uint256 internal constant MAX_REPAY_STEPS = 3; // Max number of times we attempt to repay remaining debt
uint256 internal constant DEFAULT_LIQUIDITY_SLIPPAGE = 10 ** 12; // 1e-6 slippage for redeeming liquidity when selling order
uint256 internal constant FALLBACK_LIQUIDITY_SLIPPAGE = 10 ** 15; // 0.1% slippage for redeeming liquidity when selling order
uint256 internal constant MAX_LIQUIDITY_SLIPPAGE = 10 ** 17; // 10% max slippage for redeeming liquidity when selling order
// Contract instances
Comptroller public COMPTROLLER; // The Compound comptroller
PriceOracle public ORACLE; // The Compound price oracle
CERC20 public CUSDC; // The Compound USDC market token
address public CETH_ADDR;
// Instance variables
uint256 public stake;
uint256 public collateralAmountInUSDC;
uint256 public loanAmountInUSDC;
uint256 public cycleNumber;
uint256 public buyTime; // Timestamp for order execution
uint256 public outputAmount; // Records the total output USDC after order is sold
address public compoundTokenAddr;
bool public isSold;
bool public orderType; // True for shorting, false for longing
bool internal initialized;
constructor() public {}
function init(
address _compoundTokenAddr,
uint256 _cycleNumber,
uint256 _stake,
uint256 _collateralAmountInUSDC,
uint256 _loanAmountInUSDC,
bool _orderType,
address _usdcAddr,
address payable _kyberAddr,
address _comptrollerAddr,
address _priceOracleAddr,
address _cUSDCAddr,
address _cETHAddr
) public {
require(!initialized);
initialized = true;
// Initialize details of order
require(_compoundTokenAddr != _cUSDCAddr);
require(_stake > 0 && _collateralAmountInUSDC > 0 && _loanAmountInUSDC > 0); // Validate inputs
stake = _stake;
collateralAmountInUSDC = _collateralAmountInUSDC;
loanAmountInUSDC = _loanAmountInUSDC;
cycleNumber = _cycleNumber;
compoundTokenAddr = _compoundTokenAddr;
orderType = _orderType;
COMPTROLLER = Comptroller(_comptrollerAddr);
ORACLE = PriceOracle(_priceOracleAddr);
CUSDC = CERC20(_cUSDCAddr);
CETH_ADDR = _cETHAddr;
USDC_ADDR = _usdcAddr;
KYBER_ADDR = _kyberAddr;
usdc = ERC20Detailed(_usdcAddr);
kyber = KyberNetwork(_kyberAddr);
// transfer ownership to msg.sender
_transferOwnership(msg.sender);
}
/**
* @notice Executes the Compound order
* @param _minPrice the minimum token price
* @param _maxPrice the maximum token price
*/
function executeOrder(uint256 _minPrice, uint256 _maxPrice) public;
/**
* @notice Sells the Compound order and returns assets to PeakDeFiFund
* @param _minPrice the minimum token price
* @param _maxPrice the maximum token price
*/
function sellOrder(uint256 _minPrice, uint256 _maxPrice) public returns (uint256 _inputAmount, uint256 _outputAmount);
/**
* @notice Repays the loans taken out to prevent the collateral ratio from dropping below threshold
* @param _repayAmountInUSDC the amount to repay, in USDC
*/
function repayLoan(uint256 _repayAmountInUSDC) public;
/**
* @notice Emergency method, which allow to transfer selected tokens to the fund address
* @param _tokenAddr address of withdrawn token
* @param _receiver address who should receive tokens
*/
function emergencyExitTokens(address _tokenAddr, address _receiver) public onlyOwner {
ERC20Detailed token = ERC20Detailed(_tokenAddr);
token.safeTransfer(_receiver, token.balanceOf(address(this)));
}
function getMarketCollateralFactor() public view returns (uint256);
function getCurrentCollateralInUSDC() public returns (uint256 _amount);
function getCurrentBorrowInUSDC() public returns (uint256 _amount);
function getCurrentCashInUSDC() public view returns (uint256 _amount);
/**
* @notice Calculates the current profit in USDC
* @return the profit amount
*/
function getCurrentProfitInUSDC() public returns (bool _isNegative, uint256 _amount) {
uint256 l;
uint256 r;
if (isSold) {
l = outputAmount;
r = collateralAmountInUSDC;
} else {
uint256 cash = getCurrentCashInUSDC();
uint256 supply = getCurrentCollateralInUSDC();
uint256 borrow = getCurrentBorrowInUSDC();
if (cash >= borrow) {
l = supply.add(cash);
r = borrow.add(collateralAmountInUSDC);
} else {
l = supply;
r = borrow.sub(cash).mul(PRECISION).div(getMarketCollateralFactor()).add(collateralAmountInUSDC);
}
}
if (l >= r) {
return (false, l.sub(r));
} else {
return (true, r.sub(l));
}
}
/**
* @notice Calculates the current collateral ratio on Compound, using 18 decimals
* @return the collateral ratio
*/
function getCurrentCollateralRatioInUSDC() public returns (uint256 _amount) {
uint256 supply = getCurrentCollateralInUSDC();
uint256 borrow = getCurrentBorrowInUSDC();
if (borrow == 0) {
return uint256(-1);
}
return supply.mul(PRECISION).div(borrow);
}
/**
* @notice Calculates the current liquidity (supply - collateral) on the Compound platform
* @return the liquidity
*/
function getCurrentLiquidityInUSDC() public returns (bool _isNegative, uint256 _amount) {
uint256 supply = getCurrentCollateralInUSDC();
uint256 borrow = getCurrentBorrowInUSDC().mul(PRECISION).div(getMarketCollateralFactor());
if (supply >= borrow) {
return (false, supply.sub(borrow));
} else {
return (true, borrow.sub(supply));
}
}
function __sellUSDCForToken(uint256 _usdcAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) {
ERC20Detailed t = __underlyingToken(compoundTokenAddr);
(,, _actualTokenAmount, _actualUSDCAmount) = __kyberTrade(usdc, _usdcAmount, t); // Sell USDC for tokens on Kyber
require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values
}
function __sellTokenForUSDC(uint256 _tokenAmount) internal returns (uint256 _actualUSDCAmount, uint256 _actualTokenAmount) {
ERC20Detailed t = __underlyingToken(compoundTokenAddr);
(,, _actualUSDCAmount, _actualTokenAmount) = __kyberTrade(t, _tokenAmount, usdc); // Sell tokens for USDC on Kyber
require(_actualUSDCAmount > 0 && _actualTokenAmount > 0); // Validate return values
}
// Convert a USDC amount to the amount of a given token that's of equal value
function __usdcToToken(address _cToken, uint256 _usdcAmount) internal view returns (uint256) {
ERC20Detailed t = __underlyingToken(_cToken);
return _usdcAmount.mul(PRECISION).div(10 ** getDecimals(usdc)).mul(10 ** getDecimals(t)).div(ORACLE.getUnderlyingPrice(_cToken).mul(10 ** getDecimals(t)).div(PRECISION));
}
// Convert a compound token amount to the amount of USDC that's of equal value
function __tokenToUSDC(address _cToken, uint256 _tokenAmount) internal view returns (uint256) {
return _tokenAmount.mul(ORACLE.getUnderlyingPrice(_cToken)).div(PRECISION).mul(10 ** getDecimals(usdc)).div(PRECISION);
}
function __underlyingToken(address _cToken) internal view returns (ERC20Detailed) {
if (_cToken == CETH_ADDR) {
// ETH
return ETH_TOKEN_ADDRESS;
}
CERC20 ct = CERC20(_cToken);
address underlyingToken = ct.underlying();
ERC20Detailed t = ERC20Detailed(underlyingToken);
return t;
}
function() external payable {}
}
pragma solidity ^0.5.0;
import "../GSN/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity 0.5.17;
// Compound finance comptroller
interface Comptroller {
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory);
function markets(address cToken) external view returns (bool isListed, uint256 collateralFactorMantissa);
}
pragma solidity 0.5.17;
// Compound finance's price oracle
interface PriceOracle {
// returns the price of the underlying token in USD, scaled by 10**(36 - underlyingPrecision)
function getUnderlyingPrice(address cToken) external view returns (uint);
}
pragma solidity 0.5.17;
// Compound finance ERC20 market interface
interface CERC20 {
function mint(uint mintAmount) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow(uint repayAmount) external returns (uint);
function borrowBalanceCurrent(address account) external returns (uint);
function exchangeRateCurrent() external returns (uint);
function balanceOf(address account) external view returns (uint);
function decimals() external view returns (uint);
function underlying() external view returns (address);
}
pragma solidity 0.5.17;
// Compound finance Ether market interface
interface CEther {
function mint() external payable;
function redeemUnderlying(uint redeemAmount) external returns (uint);
function borrow(uint borrowAmount) external returns (uint);
function repayBorrow() external payable;
function borrowBalanceCurrent(address account) external returns (uint);
function exchangeRateCurrent() external returns (uint);
function balanceOf(address account) external view returns (uint);
function decimals() external view returns (uint);
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "./interfaces/KyberNetwork.sol";
import "./interfaces/OneInchExchange.sol";
/**
* @title The smart contract for useful utility functions and constants.
* @author Zefram Lou (Zebang Liu)
*/
contract Utils {
using SafeMath for uint256;
using SafeERC20 for ERC20Detailed;
/**
* @notice Checks if `_token` is a valid token.
* @param _token the token's address
*/
modifier isValidToken(address _token) {
require(_token != address(0));
if (_token != address(ETH_TOKEN_ADDRESS)) {
require(isContract(_token));
}
_;
}
address public USDC_ADDR;
address payable public KYBER_ADDR;
address payable public ONEINCH_ADDR;
bytes public constant PERM_HINT = "PERM";
// The address Kyber Network uses to represent Ether
ERC20Detailed internal constant ETH_TOKEN_ADDRESS = ERC20Detailed(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
ERC20Detailed internal usdc;
KyberNetwork internal kyber;
uint256 constant internal PRECISION = (10**18);
uint256 constant internal MAX_QTY = (10**28); // 10B tokens
uint256 constant internal ETH_DECIMALS = 18;
uint256 constant internal MAX_DECIMALS = 18;
constructor(
address _usdcAddr,
address payable _kyberAddr,
address payable _oneInchAddr
) public {
USDC_ADDR = _usdcAddr;
KYBER_ADDR = _kyberAddr;
ONEINCH_ADDR = _oneInchAddr;
usdc = ERC20Detailed(_usdcAddr);
kyber = KyberNetwork(_kyberAddr);
}
/**
* @notice Get the number of decimals of a token
* @param _token the token to be queried
* @return number of decimals
*/
function getDecimals(ERC20Detailed _token) internal view returns(uint256) {
if (address(_token) == address(ETH_TOKEN_ADDRESS)) {
return uint256(ETH_DECIMALS);
}
return uint256(_token.decimals());
}
/**
* @notice Get the token balance of an account
* @param _token the token to be queried
* @param _addr the account whose balance will be returned
* @return token balance of the account
*/
function getBalance(ERC20Detailed _token, address _addr) internal view returns(uint256) {
if (address(_token) == address(ETH_TOKEN_ADDRESS)) {
return uint256(_addr.balance);
}
return uint256(_token.balanceOf(_addr));
}
/**
* @notice Calculates the rate of a trade. The rate is the price of the source token in the dest token, in 18 decimals.
* Note: the rate is on the token level, not the wei level, so for example if 1 Atoken = 10 Btoken, then the rate
* from A to B is 10 * 10**18, regardless of how many decimals each token uses.
* @param srcAmount amount of source token
* @param destAmount amount of dest token
* @param srcDecimals decimals used by source token
* @param dstDecimals decimals used by dest token
*/
function calcRateFromQty(uint256 srcAmount, uint256 destAmount, uint256 srcDecimals, uint256 dstDecimals)
internal pure returns(uint)
{
require(srcAmount <= MAX_QTY);
require(destAmount <= MAX_QTY);
if (dstDecimals >= srcDecimals) {
require((dstDecimals - srcDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION / ((10 ** (dstDecimals - srcDecimals)) * srcAmount));
} else {
require((srcDecimals - dstDecimals) <= MAX_DECIMALS);
return (destAmount * PRECISION * (10 ** (srcDecimals - dstDecimals)) / srcAmount);
}
}
/**
* @notice Wrapper function for doing token conversion on Kyber Network
* @param _srcToken the token to convert from
* @param _srcAmount the amount of tokens to be converted
* @param _destToken the destination token
* @return _destPriceInSrc the price of the dest token, in terms of source tokens
* _srcPriceInDest the price of the source token, in terms of dest tokens
* _actualDestAmount actual amount of dest token traded
* _actualSrcAmount actual amount of src token traded
*/
function __kyberTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken)
internal
returns(
uint256 _destPriceInSrc,
uint256 _srcPriceInDest,
uint256 _actualDestAmount,
uint256 _actualSrcAmount
)
{
require(_srcToken != _destToken);
uint256 beforeSrcBalance = getBalance(_srcToken, address(this));
uint256 msgValue;
if (_srcToken != ETH_TOKEN_ADDRESS) {
msgValue = 0;
_srcToken.safeApprove(KYBER_ADDR, 0);
_srcToken.safeApprove(KYBER_ADDR, _srcAmount);
} else {
msgValue = _srcAmount;
}
_actualDestAmount = kyber.tradeWithHint.value(msgValue)(
_srcToken,
_srcAmount,
_destToken,
toPayableAddr(address(this)),
MAX_QTY,
1,
address(0),
PERM_HINT
);
_actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this)));
require(_actualDestAmount > 0 && _actualSrcAmount > 0);
_destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken));
_srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken));
}
/**
* @notice Wrapper function for doing token conversion on 1inch
* @param _srcToken the token to convert from
* @param _srcAmount the amount of tokens to be converted
* @param _destToken the destination token
* @return _destPriceInSrc the price of the dest token, in terms of source tokens
* _srcPriceInDest the price of the source token, in terms of dest tokens
* _actualDestAmount actual amount of dest token traded
* _actualSrcAmount actual amount of src token traded
*/
function __oneInchTrade(ERC20Detailed _srcToken, uint256 _srcAmount, ERC20Detailed _destToken, bytes memory _calldata)
internal
returns(
uint256 _destPriceInSrc,
uint256 _srcPriceInDest,
uint256 _actualDestAmount,
uint256 _actualSrcAmount
)
{
require(_srcToken != _destToken);
uint256 beforeSrcBalance = getBalance(_srcToken, address(this));
uint256 beforeDestBalance = getBalance(_destToken, address(this));
// Note: _actualSrcAmount is being used as msgValue here, because otherwise we'd run into the stack too deep error
if (_srcToken != ETH_TOKEN_ADDRESS) {
_actualSrcAmount = 0;
OneInchExchange dex = OneInchExchange(ONEINCH_ADDR);
address approvalHandler = dex.spender();
_srcToken.safeApprove(approvalHandler, 0);
_srcToken.safeApprove(approvalHandler, _srcAmount);
} else {
_actualSrcAmount = _srcAmount;
}
// trade through 1inch proxy
(bool success,) = ONEINCH_ADDR.call.value(_actualSrcAmount)(_calldata);
require(success);
// calculate trade amounts and price
_actualDestAmount = getBalance(_destToken, address(this)).sub(beforeDestBalance);
_actualSrcAmount = beforeSrcBalance.sub(getBalance(_srcToken, address(this)));
require(_actualDestAmount > 0 && _actualSrcAmount > 0);
_destPriceInSrc = calcRateFromQty(_actualDestAmount, _actualSrcAmount, getDecimals(_destToken), getDecimals(_srcToken));
_srcPriceInDest = calcRateFromQty(_actualSrcAmount, _actualDestAmount, getDecimals(_srcToken), getDecimals(_destToken));
}
/**
* @notice Checks if an Ethereum account is a smart contract
* @param _addr the account to be checked
* @return True if the account is a smart contract, false otherwise
*/
function isContract(address _addr) internal view returns(bool) {
uint256 size;
if (_addr == address(0)) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
function toPayableAddr(address _addr) internal pure returns (address payable) {
return address(uint160(_addr));
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
/**
* @title The interface for the Kyber Network smart contract
* @author Zefram Lou (Zebang Liu)
*/
interface KyberNetwork {
function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint srcQty) external view
returns (uint expectedRate, uint slippageRate);
function tradeWithHint(
ERC20Detailed src, uint srcAmount, ERC20Detailed dest, address payable destAddress, uint maxDestAmount,
uint minConversionRate, address walletId, bytes calldata hint) external payable returns(uint);
}
pragma solidity 0.5.17;
interface OneInchExchange {
function spender() external view returns (address);
}
pragma solidity 0.5.17;
import "./LongCERC20Order.sol";
import "./LongCEtherOrder.sol";
import "./ShortCERC20Order.sol";
import "./ShortCEtherOrder.sol";
import "../lib/CloneFactory.sol";
contract CompoundOrderFactory is CloneFactory {
address public SHORT_CERC20_LOGIC_CONTRACT;
address public SHORT_CEther_LOGIC_CONTRACT;
address public LONG_CERC20_LOGIC_CONTRACT;
address public LONG_CEther_LOGIC_CONTRACT;
address public USDC_ADDR;
address payable public KYBER_ADDR;
address public COMPTROLLER_ADDR;
address public ORACLE_ADDR;
address public CUSDC_ADDR;
address public CETH_ADDR;
constructor(
address _shortCERC20LogicContract,
address _shortCEtherLogicContract,
address _longCERC20LogicContract,
address _longCEtherLogicContract,
address _usdcAddr,
address payable _kyberAddr,
address _comptrollerAddr,
address _priceOracleAddr,
address _cUSDCAddr,
address _cETHAddr
) public {
SHORT_CERC20_LOGIC_CONTRACT = _shortCERC20LogicContract;
SHORT_CEther_LOGIC_CONTRACT = _shortCEtherLogicContract;
LONG_CERC20_LOGIC_CONTRACT = _longCERC20LogicContract;
LONG_CEther_LOGIC_CONTRACT = _longCEtherLogicContract;
USDC_ADDR = _usdcAddr;
KYBER_ADDR = _kyberAddr;
COMPTROLLER_ADDR = _comptrollerAddr;
ORACLE_ADDR = _priceOracleAddr;
CUSDC_ADDR = _cUSDCAddr;
CETH_ADDR = _cETHAddr;
}
function createOrder(
address _compoundTokenAddr,
uint256 _cycleNumber,
uint256 _stake,
uint256 _collateralAmountInUSDC,
uint256 _loanAmountInUSDC,
bool _orderType
) external returns (CompoundOrder) {
require(_compoundTokenAddr != address(0));
CompoundOrder order;
address payable clone;
if (_compoundTokenAddr != CETH_ADDR) {
if (_orderType) {
// Short CERC20 Order
clone = toPayableAddr(createClone(SHORT_CERC20_LOGIC_CONTRACT));
} else {
// Long CERC20 Order
clone = toPayableAddr(createClone(LONG_CERC20_LOGIC_CONTRACT));
}
} else {
if (_orderType) {
// Short CEther Order
clone = toPayableAddr(createClone(SHORT_CEther_LOGIC_CONTRACT));
} else {
// Long CEther Order
clone = toPayableAddr(createClone(LONG_CEther_LOGIC_CONTRACT));
}
}
order = CompoundOrder(clone);
order.init(_compoundTokenAddr, _cycleNumber, _stake, _collateralAmountInUSDC, _loanAmountInUSDC, _orderType,
USDC_ADDR, KYBER_ADDR, COMPTROLLER_ADDR, ORACLE_ADDR, CUSDC_ADDR, CETH_ADDR);
order.transferOwnership(msg.sender);
return order;
}
function getMarketCollateralFactor(address _compoundTokenAddr) external view returns (uint256) {
Comptroller troll = Comptroller(COMPTROLLER_ADDR);
(, uint256 factor) = troll.markets(_compoundTokenAddr);
return factor;
}
function tokenIsListed(address _compoundTokenAddr) external view returns (bool) {
Comptroller troll = Comptroller(COMPTROLLER_ADDR);
(bool isListed,) = troll.markets(_compoundTokenAddr);
return isListed;
}
function toPayableAddr(address _addr) internal pure returns (address payable) {
return address(uint160(_addr));
}
}
pragma solidity 0.5.17;
import "./CompoundOrder.sol";
contract LongCERC20Order is CompoundOrder {
modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) {
// Ensure token's price is between _minPrice and _maxPrice
uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD
require(tokenPrice > 0); // Ensure asset exists on Compound
require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range
_;
}
function executeOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidToken(compoundTokenAddr)
isValidPrice(_minPrice, _maxPrice)
{
buyTime = now;
// Get funds in USDC from PeakDeFiFund
usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund
// Convert received USDC to longing token
(,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC);
// Enter Compound markets
CERC20 market = CERC20(compoundTokenAddr);
address[] memory markets = new address[](2);
markets[0] = compoundTokenAddr;
markets[1] = address(CUSDC);
uint[] memory errors = COMPTROLLER.enterMarkets(markets);
require(errors[0] == 0 && errors[1] == 0);
// Get loan from Compound in USDC
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound
token.safeApprove(compoundTokenAddr, actualTokenAmount); // Approve token transfer to Compound
require(market.mint(actualTokenAmount) == 0); // Transfer tokens into Compound as supply
token.safeApprove(compoundTokenAddr, 0); // Clear token allowance of Compound
require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC
(bool negLiquidity, ) = getCurrentLiquidityInUSDC();
require(!negLiquidity); // Ensure account liquidity is positive
// Convert borrowed USDC to longing token
__sellUSDCForToken(loanAmountInUSDC);
// Repay leftover USDC to avoid complications
if (usdc.balanceOf(address(this)) > 0) {
uint256 repayAmount = usdc.balanceOf(address(this));
usdc.safeApprove(address(CUSDC), 0);
usdc.safeApprove(address(CUSDC), repayAmount);
require(CUSDC.repayBorrow(repayAmount) == 0);
usdc.safeApprove(address(CUSDC), 0);
}
}
function sellOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidPrice(_minPrice, _maxPrice)
returns (uint256 _inputAmount, uint256 _outputAmount)
{
require(buyTime > 0); // Ensure the order has been executed
require(isSold == false);
isSold = true;
// Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral
// Repeat to ensure debt is exhausted
CERC20 market = CERC20(compoundTokenAddr);
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) {
uint256 currentDebt = getCurrentBorrowInUSDC();
if (currentDebt > NEGLIGIBLE_DEBT) {
// Determine amount to be repaid this step
uint256 currentBalance = getCurrentCashInUSDC();
uint256 repayAmount = 0; // amount to be repaid in USDC
if (currentDebt <= currentBalance) {
// Has enough money, repay all debt
repayAmount = currentDebt;
} else {
// Doesn't have enough money, repay whatever we can repay
repayAmount = currentBalance;
}
// Repay debt
repayLoan(repayAmount);
}
// Withdraw all available liquidity
(bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC();
if (!isNeg) {
liquidity = __usdcToToken(compoundTokenAddr, liquidity);
uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with fallback slippage
errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with max slippage
market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION));
}
}
}
if (currentDebt <= NEGLIGIBLE_DEBT) {
break;
}
}
// Sell all longing token to USDC
__sellTokenForUSDC(token.balanceOf(address(this)));
// Send USDC back to PeakDeFiFund and return
_inputAmount = collateralAmountInUSDC;
_outputAmount = usdc.balanceOf(address(this));
outputAmount = _outputAmount;
usdc.safeTransfer(owner(), usdc.balanceOf(address(this)));
uint256 leftoverTokens = token.balanceOf(address(this));
if (leftoverTokens > 0) {
token.safeTransfer(owner(), leftoverTokens); // Send back potential leftover tokens
}
}
// Allows manager to repay loan to avoid liquidation
function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner {
require(buyTime > 0); // Ensure the order has been executed
// Convert longing token to USDC
uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC);
(uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken);
// Check if amount is greater than borrow balance
uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this));
if (actualUSDCAmount > currentDebt) {
actualUSDCAmount = currentDebt;
}
// Repay loan to Compound
usdc.safeApprove(address(CUSDC), 0);
usdc.safeApprove(address(CUSDC), actualUSDCAmount);
require(CUSDC.repayBorrow(actualUSDCAmount) == 0);
usdc.safeApprove(address(CUSDC), 0);
}
function getMarketCollateralFactor() public view returns (uint256) {
(, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr));
return ratio;
}
function getCurrentCollateralInUSDC() public returns (uint256 _amount) {
CERC20 market = CERC20(compoundTokenAddr);
uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION));
return supply;
}
function getCurrentBorrowInUSDC() public returns (uint256 _amount) {
uint256 borrow = CUSDC.borrowBalanceCurrent(address(this));
return borrow;
}
function getCurrentCashInUSDC() public view returns (uint256 _amount) {
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this)));
return cash;
}
}
pragma solidity 0.5.17;
import "./CompoundOrder.sol";
contract LongCEtherOrder is CompoundOrder {
modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) {
// Ensure token's price is between _minPrice and _maxPrice
uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the longing token's price in USD
require(tokenPrice > 0); // Ensure asset exists on Compound
require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range
_;
}
function executeOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidToken(compoundTokenAddr)
isValidPrice(_minPrice, _maxPrice)
{
buyTime = now;
// Get funds in USDC from PeakDeFiFund
usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund
// Convert received USDC to longing token
(,uint256 actualTokenAmount) = __sellUSDCForToken(collateralAmountInUSDC);
// Enter Compound markets
CEther market = CEther(compoundTokenAddr);
address[] memory markets = new address[](2);
markets[0] = compoundTokenAddr;
markets[1] = address(CUSDC);
uint[] memory errors = COMPTROLLER.enterMarkets(markets);
require(errors[0] == 0 && errors[1] == 0);
// Get loan from Compound in USDC
market.mint.value(actualTokenAmount)(); // Transfer tokens into Compound as supply
require(CUSDC.borrow(loanAmountInUSDC) == 0);// Take out loan in USDC
(bool negLiquidity, ) = getCurrentLiquidityInUSDC();
require(!negLiquidity); // Ensure account liquidity is positive
// Convert borrowed USDC to longing token
__sellUSDCForToken(loanAmountInUSDC);
// Repay leftover USDC to avoid complications
if (usdc.balanceOf(address(this)) > 0) {
uint256 repayAmount = usdc.balanceOf(address(this));
usdc.safeApprove(address(CUSDC), 0);
usdc.safeApprove(address(CUSDC), repayAmount);
require(CUSDC.repayBorrow(repayAmount) == 0);
usdc.safeApprove(address(CUSDC), 0);
}
}
function sellOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidPrice(_minPrice, _maxPrice)
returns (uint256 _inputAmount, uint256 _outputAmount)
{
require(buyTime > 0); // Ensure the order has been executed
require(isSold == false);
isSold = true;
// Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral
// Repeat to ensure debt is exhausted
CEther market = CEther(compoundTokenAddr);
for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) {
uint256 currentDebt = getCurrentBorrowInUSDC();
if (currentDebt > NEGLIGIBLE_DEBT) {
// Determine amount to be repaid this step
uint256 currentBalance = getCurrentCashInUSDC();
uint256 repayAmount = 0; // amount to be repaid in USDC
if (currentDebt <= currentBalance) {
// Has enough money, repay all debt
repayAmount = currentDebt;
} else {
// Doesn't have enough money, repay whatever we can repay
repayAmount = currentBalance;
}
// Repay debt
repayLoan(repayAmount);
}
// Withdraw all available liquidity
(bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC();
if (!isNeg) {
liquidity = __usdcToToken(compoundTokenAddr, liquidity);
uint256 errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with fallback slippage
errorCode = market.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with max slippage
market.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION));
}
}
}
if (currentDebt <= NEGLIGIBLE_DEBT) {
break;
}
}
// Sell all longing token to USDC
__sellTokenForUSDC(address(this).balance);
// Send USDC back to PeakDeFiFund and return
_inputAmount = collateralAmountInUSDC;
_outputAmount = usdc.balanceOf(address(this));
outputAmount = _outputAmount;
usdc.safeTransfer(owner(), usdc.balanceOf(address(this)));
toPayableAddr(owner()).transfer(address(this).balance); // Send back potential leftover tokens
}
// Allows manager to repay loan to avoid liquidation
function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner {
require(buyTime > 0); // Ensure the order has been executed
// Convert longing token to USDC
uint256 repayAmountInToken = __usdcToToken(compoundTokenAddr, _repayAmountInUSDC);
(uint256 actualUSDCAmount,) = __sellTokenForUSDC(repayAmountInToken);
// Check if amount is greater than borrow balance
uint256 currentDebt = CUSDC.borrowBalanceCurrent(address(this));
if (actualUSDCAmount > currentDebt) {
actualUSDCAmount = currentDebt;
}
// Repay loan to Compound
usdc.safeApprove(address(CUSDC), 0);
usdc.safeApprove(address(CUSDC), actualUSDCAmount);
require(CUSDC.repayBorrow(actualUSDCAmount) == 0);
usdc.safeApprove(address(CUSDC), 0);
}
function getMarketCollateralFactor() public view returns (uint256) {
(, uint256 ratio) = COMPTROLLER.markets(address(compoundTokenAddr));
return ratio;
}
function getCurrentCollateralInUSDC() public returns (uint256 _amount) {
CEther market = CEther(compoundTokenAddr);
uint256 supply = __tokenToUSDC(compoundTokenAddr, market.balanceOf(address(this)).mul(market.exchangeRateCurrent()).div(PRECISION));
return supply;
}
function getCurrentBorrowInUSDC() public returns (uint256 _amount) {
uint256 borrow = CUSDC.borrowBalanceCurrent(address(this));
return borrow;
}
function getCurrentCashInUSDC() public view returns (uint256 _amount) {
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
uint256 cash = __tokenToUSDC(compoundTokenAddr, getBalance(token, address(this)));
return cash;
}
}
pragma solidity 0.5.17;
import "./CompoundOrder.sol";
contract ShortCERC20Order is CompoundOrder {
modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) {
// Ensure token's price is between _minPrice and _maxPrice
uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD
require(tokenPrice > 0); // Ensure asset exists on Compound
require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range
_;
}
function executeOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidToken(compoundTokenAddr)
isValidPrice(_minPrice, _maxPrice)
{
buyTime = now;
// Get funds in USDC from PeakDeFiFund
usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund
// Enter Compound markets
CERC20 market = CERC20(compoundTokenAddr);
address[] memory markets = new address[](2);
markets[0] = compoundTokenAddr;
markets[1] = address(CUSDC);
uint[] memory errors = COMPTROLLER.enterMarkets(markets);
require(errors[0] == 0 && errors[1] == 0);
// Get loan from Compound in tokenAddr
uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC);
usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market
usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market
require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply
usdc.safeApprove(address(CUSDC), 0);
require(market.borrow(loanAmountInToken) == 0);// Take out loan
(bool negLiquidity, ) = getCurrentLiquidityInUSDC();
require(!negLiquidity); // Ensure account liquidity is positive
// Convert loaned tokens to USDC
(uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken);
loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received
// Repay leftover tokens to avoid complications
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
if (token.balanceOf(address(this)) > 0) {
uint256 repayAmount = token.balanceOf(address(this));
token.safeApprove(compoundTokenAddr, 0);
token.safeApprove(compoundTokenAddr, repayAmount);
require(market.repayBorrow(repayAmount) == 0);
token.safeApprove(compoundTokenAddr, 0);
}
}
function sellOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidPrice(_minPrice, _maxPrice)
returns (uint256 _inputAmount, uint256 _outputAmount)
{
require(buyTime > 0); // Ensure the order has been executed
require(isSold == false);
isSold = true;
// Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral
// Repeat to ensure debt is exhausted
for (uint256 i = 0; i < MAX_REPAY_STEPS; i++) {
uint256 currentDebt = getCurrentBorrowInUSDC();
if (currentDebt > NEGLIGIBLE_DEBT) {
// Determine amount to be repaid this step
uint256 currentBalance = getCurrentCashInUSDC();
uint256 repayAmount = 0; // amount to be repaid in USDC
if (currentDebt <= currentBalance) {
// Has enough money, repay all debt
repayAmount = currentDebt;
} else {
// Doesn't have enough money, repay whatever we can repay
repayAmount = currentBalance;
}
// Repay debt
repayLoan(repayAmount);
}
// Withdraw all available liquidity
(bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC();
if (!isNeg) {
uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with fallback slippage
errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with max slippage
CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION));
}
}
}
if (currentDebt <= NEGLIGIBLE_DEBT) {
break;
}
}
// Send USDC back to PeakDeFiFund and return
_inputAmount = collateralAmountInUSDC;
_outputAmount = usdc.balanceOf(address(this));
outputAmount = _outputAmount;
usdc.safeTransfer(owner(), usdc.balanceOf(address(this)));
}
// Allows manager to repay loan to avoid liquidation
function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner {
require(buyTime > 0); // Ensure the order has been executed
// Convert USDC to shorting token
(,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC);
// Check if amount is greater than borrow balance
CERC20 market = CERC20(compoundTokenAddr);
uint256 currentDebt = market.borrowBalanceCurrent(address(this));
if (actualTokenAmount > currentDebt) {
actualTokenAmount = currentDebt;
}
// Repay loan to Compound
ERC20Detailed token = __underlyingToken(compoundTokenAddr);
token.safeApprove(compoundTokenAddr, 0);
token.safeApprove(compoundTokenAddr, actualTokenAmount);
require(market.repayBorrow(actualTokenAmount) == 0);
token.safeApprove(compoundTokenAddr, 0);
}
function getMarketCollateralFactor() public view returns (uint256) {
(, uint256 ratio) = COMPTROLLER.markets(address(CUSDC));
return ratio;
}
function getCurrentCollateralInUSDC() public returns (uint256 _amount) {
uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION);
return supply;
}
function getCurrentBorrowInUSDC() public returns (uint256 _amount) {
CERC20 market = CERC20(compoundTokenAddr);
uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this)));
return borrow;
}
function getCurrentCashInUSDC() public view returns (uint256 _amount) {
uint256 cash = getBalance(usdc, address(this));
return cash;
}
}
pragma solidity 0.5.17;
import "./CompoundOrder.sol";
contract ShortCEtherOrder is CompoundOrder {
modifier isValidPrice(uint256 _minPrice, uint256 _maxPrice) {
// Ensure token's price is between _minPrice and _maxPrice
uint256 tokenPrice = ORACLE.getUnderlyingPrice(compoundTokenAddr); // Get the shorting token's price in USD
require(tokenPrice > 0); // Ensure asset exists on Compound
require(tokenPrice >= _minPrice && tokenPrice <= _maxPrice); // Ensure price is within range
_;
}
function executeOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidToken(compoundTokenAddr)
isValidPrice(_minPrice, _maxPrice)
{
buyTime = now;
// Get funds in USDC from PeakDeFiFund
usdc.safeTransferFrom(owner(), address(this), collateralAmountInUSDC); // Transfer USDC from PeakDeFiFund
// Enter Compound markets
CEther market = CEther(compoundTokenAddr);
address[] memory markets = new address[](2);
markets[0] = compoundTokenAddr;
markets[1] = address(CUSDC);
uint[] memory errors = COMPTROLLER.enterMarkets(markets);
require(errors[0] == 0 && errors[1] == 0);
// Get loan from Compound in tokenAddr
uint256 loanAmountInToken = __usdcToToken(compoundTokenAddr, loanAmountInUSDC);
usdc.safeApprove(address(CUSDC), 0); // Clear USDC allowance of Compound USDC market
usdc.safeApprove(address(CUSDC), collateralAmountInUSDC); // Approve USDC transfer to Compound USDC market
require(CUSDC.mint(collateralAmountInUSDC) == 0); // Transfer USDC into Compound as supply
usdc.safeApprove(address(CUSDC), 0);
require(market.borrow(loanAmountInToken) == 0);// Take out loan
(bool negLiquidity, ) = getCurrentLiquidityInUSDC();
require(!negLiquidity); // Ensure account liquidity is positive
// Convert loaned tokens to USDC
(uint256 actualUSDCAmount,) = __sellTokenForUSDC(loanAmountInToken);
loanAmountInUSDC = actualUSDCAmount; // Change loan amount to actual USDC received
// Repay leftover tokens to avoid complications
if (address(this).balance > 0) {
uint256 repayAmount = address(this).balance;
market.repayBorrow.value(repayAmount)();
}
}
function sellOrder(uint256 _minPrice, uint256 _maxPrice)
public
onlyOwner
isValidPrice(_minPrice, _maxPrice)
returns (uint256 _inputAmount, uint256 _outputAmount)
{
require(buyTime > 0); // Ensure the order has been executed
require(isSold == false);
isSold = true;
// Siphon remaining collateral by repaying x USDC and getting back 1.5x USDC collateral
// Repeat to ensure debt is exhausted
for (uint256 i = 0; i < MAX_REPAY_STEPS; i = i++) {
uint256 currentDebt = getCurrentBorrowInUSDC();
if (currentDebt > NEGLIGIBLE_DEBT) {
// Determine amount to be repaid this step
uint256 currentBalance = getCurrentCashInUSDC();
uint256 repayAmount = 0; // amount to be repaid in USDC
if (currentDebt <= currentBalance) {
// Has enough money, repay all debt
repayAmount = currentDebt;
} else {
// Doesn't have enough money, repay whatever we can repay
repayAmount = currentBalance;
}
// Repay debt
repayLoan(repayAmount);
}
// Withdraw all available liquidity
(bool isNeg, uint256 liquidity) = getCurrentLiquidityInUSDC();
if (!isNeg) {
uint256 errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(DEFAULT_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with fallback slippage
errorCode = CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(FALLBACK_LIQUIDITY_SLIPPAGE)).div(PRECISION));
if (errorCode != 0) {
// error
// try again with max slippage
CUSDC.redeemUnderlying(liquidity.mul(PRECISION.sub(MAX_LIQUIDITY_SLIPPAGE)).div(PRECISION));
}
}
}
if (currentDebt <= NEGLIGIBLE_DEBT) {
break;
}
}
// Send USDC back to PeakDeFiFund and return
_inputAmount = collateralAmountInUSDC;
_outputAmount = usdc.balanceOf(address(this));
outputAmount = _outputAmount;
usdc.safeTransfer(owner(), usdc.balanceOf(address(this)));
}
// Allows manager to repay loan to avoid liquidation
function repayLoan(uint256 _repayAmountInUSDC) public onlyOwner {
require(buyTime > 0); // Ensure the order has been executed
// Convert USDC to shorting token
(,uint256 actualTokenAmount) = __sellUSDCForToken(_repayAmountInUSDC);
// Check if amount is greater than borrow balance
CEther market = CEther(compoundTokenAddr);
uint256 currentDebt = market.borrowBalanceCurrent(address(this));
if (actualTokenAmount > currentDebt) {
actualTokenAmount = currentDebt;
}
// Repay loan to Compound
market.repayBorrow.value(actualTokenAmount)();
}
function getMarketCollateralFactor() public view returns (uint256) {
(, uint256 ratio) = COMPTROLLER.markets(address(CUSDC));
return ratio;
}
function getCurrentCollateralInUSDC() public returns (uint256 _amount) {
uint256 supply = CUSDC.balanceOf(address(this)).mul(CUSDC.exchangeRateCurrent()).div(PRECISION);
return supply;
}
function getCurrentBorrowInUSDC() public returns (uint256 _amount) {
CEther market = CEther(compoundTokenAddr);
uint256 borrow = __tokenToUSDC(compoundTokenAddr, market.borrowBalanceCurrent(address(this)));
return borrow;
}
function getCurrentCashInUSDC() public view returns (uint256 _amount) {
uint256 cash = getBalance(usdc, address(this));
return cash;
}
}
pragma solidity 0.5.17;
/*
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)
}
}
function isClone(address target, address query) internal view returns (bool result) {
bytes20 targetBytes = bytes20(target);
assembly {
let clone := mload(0x40)
mstore(clone, 0x363d3d373d3d3d363d7300000000000000000000000000000000000000000000)
mstore(add(clone, 0xa), targetBytes)
mstore(add(clone, 0x1e), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
let other := add(clone, 0x40)
extcodecopy(query, other, 0, 0x2d)
result := and(
eq(mload(clone), mload(other)),
eq(mload(add(clone, 0xd)), mload(add(other, 0xd)))
)
}
}
}
pragma solidity 0.5.17;
interface IMiniMeToken {
function balanceOf(address _owner) external view returns (uint256 balance);
function totalSupply() external view returns(uint);
function generateTokens(address _owner, uint _amount) external returns (bool);
function destroyTokens(address _owner, uint _amount) external returns (bool);
function totalSupplyAt(uint _blockNumber) external view returns(uint);
function balanceOfAt(address _holder, uint _blockNumber) external view returns (uint);
function transferOwnership(address newOwner) external;
}
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
bool private _notEntered;
function __initReentrancyGuard() internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
_notEntered = true;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_notEntered = false;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_notEntered = true;
}
}
pragma solidity 0.5.17;
contract Migrations {
address public owner;
uint public last_completed_migration;
modifier restricted() {
if (msg.sender == owner) _;
}
constructor() public {
owner = msg.sender;
}
function setCompleted(uint completed) public restricted {
last_completed_migration = completed;
}
function upgrade(address new_address) public restricted {
Migrations upgraded = Migrations(new_address);
upgraded.setCompleted(last_completed_migration);
}
}
pragma solidity 0.5.17;
// interface for contract_v6/UniswapOracle.sol
interface IUniswapOracle {
function update() external returns (bool success);
function consult(address token, uint256 amountIn)
external
view
returns (uint256 amountOut);
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Capped.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
contract PeakToken is ERC20, ERC20Detailed, ERC20Capped, ERC20Burnable {
constructor(
string memory name,
string memory symbol,
uint8 decimals,
uint256 cap
) ERC20Detailed(name, symbol, decimals) ERC20Capped(cap) public {}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20Mintable}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance"));
}
}
pragma solidity ^0.5.0;
import "./ERC20Mintable.sol";
/**
* @dev Extension of {ERC20Mintable} that adds a cap to the supply of tokens.
*/
contract ERC20Capped is ERC20Mintable {
uint256 private _cap;
/**
* @dev Sets the value of the `cap`. This value is immutable, it can only be
* set once during construction.
*/
constructor (uint256 cap) public {
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 {ERC20Mintable-mint}.
*
* Requirements:
*
* - `value` must not cause the total supply to go over the cap.
*/
function _mint(address account, uint256 value) internal {
require(totalSupply().add(value) <= _cap, "ERC20Capped: cap exceeded");
super._mint(account, value);
}
}
pragma solidity ^0.5.0;
import "./ERC20.sol";
import "../../access/roles/MinterRole.sol";
/**
* @dev Extension of {ERC20} that adds a set of accounts with the {MinterRole},
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See {ERC20-_mint}.
*
* Requirements:
*
* - the caller must have the {MinterRole}.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "../Roles.sol";
contract MinterRole is Context {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(_msgSender());
}
modifier onlyMinter() {
require(isMinter(_msgSender()), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(_msgSender());
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "./ERC20.sol";
/**
* @dev Extension of {ERC20} that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is Context, ERC20 {
/**
* @dev Destroys `amount` tokens from the caller.
*
* See {ERC20-_burn}.
*/
function burn(uint256 amount) public {
_burn(_msgSender(), amount);
}
/**
* @dev See {ERC20-_burnFrom}.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/access/roles/SignerRole.sol";
import "../staking/PeakStaking.sol";
import "../PeakToken.sol";
import "../IUniswapOracle.sol";
contract PeakReward is SignerRole {
using SafeMath for uint256;
using SafeERC20 for IERC20;
event Register(address user, address referrer);
event RankChange(address user, uint256 oldRank, uint256 newRank);
event PayCommission(
address referrer,
address recipient,
address token,
uint256 amount,
uint8 level
);
event ChangedCareerValue(address user, uint256 changeAmount, bool positive);
event ReceiveRankReward(address user, uint256 peakReward);
modifier regUser(address user) {
if (!isUser[user]) {
isUser[user] = true;
emit Register(user, address(0));
}
_;
}
uint256 public constant PEAK_MINT_CAP = 5 * 10**15; // 50 million PEAK
uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20%
uint256 internal constant PEAK_PRECISION = 10**8;
uint256 internal constant USDC_PRECISION = 10**6;
uint8 internal constant COMMISSION_LEVELS = 8;
mapping(address => address) public referrerOf;
mapping(address => bool) public isUser;
mapping(address => uint256) public careerValue; // AKA DSV
mapping(address => uint256) public rankOf;
mapping(uint256 => mapping(uint256 => uint256)) public rankReward; // (beforeRank, afterRank) => rewardInPeak
mapping(address => mapping(uint256 => uint256)) public downlineRanks; // (referrer, rank) => numReferredUsersWithRank
uint256[] public commissionPercentages;
uint256[] public commissionStakeRequirements;
uint256 public mintedPeakTokens;
address public marketPeakWallet;
PeakStaking public peakStaking;
PeakToken public peakToken;
address public stablecoin;
IUniswapOracle public oracle;
constructor(
address _marketPeakWallet,
address _peakStaking,
address _peakToken,
address _stablecoin,
address _oracle
) public {
// initialize commission percentages for each level
commissionPercentages.push(10 * (10**16)); // 10%
commissionPercentages.push(4 * (10**16)); // 4%
commissionPercentages.push(2 * (10**16)); // 2%
commissionPercentages.push(1 * (10**16)); // 1%
commissionPercentages.push(1 * (10**16)); // 1%
commissionPercentages.push(1 * (10**16)); // 1%
commissionPercentages.push(5 * (10**15)); // 0.5%
commissionPercentages.push(5 * (10**15)); // 0.5%
// initialize commission stake requirements for each level
commissionStakeRequirements.push(0);
commissionStakeRequirements.push(PEAK_PRECISION.mul(2000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(4000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(6000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(7000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(8000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(9000));
commissionStakeRequirements.push(PEAK_PRECISION.mul(10000));
// initialize rank rewards
for (uint256 i = 0; i < 8; i = i.add(1)) {
uint256 rewardInUSDC = 0;
for (uint256 j = i.add(1); j <= 8; j = j.add(1)) {
if (j == 1) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(100));
} else if (j == 2) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(300));
} else if (j == 3) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(600));
} else if (j == 4) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(1200));
} else if (j == 5) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(2400));
} else if (j == 6) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(7500));
} else if (j == 7) {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(15000));
} else {
rewardInUSDC = rewardInUSDC.add(USDC_PRECISION.mul(50000));
}
rankReward[i][j] = rewardInUSDC;
}
}
marketPeakWallet = _marketPeakWallet;
peakStaking = PeakStaking(_peakStaking);
peakToken = PeakToken(_peakToken);
stablecoin = _stablecoin;
oracle = IUniswapOracle(_oracle);
}
/**
@notice Registers a group of referrals relationship.
@param users The array of users
@param referrers The group of referrers of `users`
*/
function multiRefer(address[] calldata users, address[] calldata referrers) external onlySigner {
require(users.length == referrers.length, "PeakReward: arrays length are not equal");
for (uint256 i = 0; i < users.length; i++) {
refer(users[i], referrers[i]);
}
}
/**
@notice Registers a referral relationship
@param user The user who is being referred
@param referrer The referrer of `user`
*/
function refer(address user, address referrer) public onlySigner {
require(!isUser[user], "PeakReward: referred is already a user");
require(user != referrer, "PeakReward: can't refer self");
require(
user != address(0) && referrer != address(0),
"PeakReward: 0 address"
);
isUser[user] = true;
isUser[referrer] = true;
referrerOf[user] = referrer;
downlineRanks[referrer][0] = downlineRanks[referrer][0].add(1);
emit Register(user, referrer);
}
function canRefer(address user, address referrer)
public
view
returns (bool)
{
return
!isUser[user] &&
user != referrer &&
user != address(0) &&
referrer != address(0);
}
/**
@notice Distributes commissions to a referrer and their referrers
@param referrer The referrer who will receive commission
@param commissionToken The ERC20 token that the commission is paid in
@param rawCommission The raw commission that will be distributed amongst referrers
@param returnLeftovers If true, leftover commission is returned to the sender. If false, leftovers will be paid to MarketPeak.
*/
function payCommission(
address referrer,
address commissionToken,
uint256 rawCommission,
bool returnLeftovers
) public regUser(referrer) onlySigner returns (uint256 leftoverAmount) {
// transfer the raw commission from `msg.sender`
IERC20 token = IERC20(commissionToken);
token.safeTransferFrom(msg.sender, address(this), rawCommission);
// payout commissions to referrers of different levels
address ptr = referrer;
uint256 commissionLeft = rawCommission;
uint8 i = 0;
while (ptr != address(0) && i < COMMISSION_LEVELS) {
if (_peakStakeOf(ptr) >= commissionStakeRequirements[i]) {
// referrer has enough stake, give commission
uint256 com = rawCommission.mul(commissionPercentages[i]).div(
COMMISSION_RATE
);
if (com > commissionLeft) {
com = commissionLeft;
}
token.safeTransfer(ptr, com);
commissionLeft = commissionLeft.sub(com);
if (commissionToken == address(peakToken)) {
incrementCareerValueInPeak(ptr, com);
} else if (commissionToken == stablecoin) {
incrementCareerValueInUsdc(ptr, com);
}
emit PayCommission(referrer, ptr, commissionToken, com, i);
}
ptr = referrerOf[ptr];
i += 1;
}
// handle leftovers
if (returnLeftovers) {
// return leftovers to `msg.sender`
token.safeTransfer(msg.sender, commissionLeft);
return commissionLeft;
} else {
// give leftovers to MarketPeak wallet
token.safeTransfer(marketPeakWallet, commissionLeft);
return 0;
}
}
/**
@notice Increments a user's career value
@param user The user
@param incCV The CV increase amount, in Usdc
*/
function incrementCareerValueInUsdc(address user, uint256 incCV)
public
regUser(user)
onlySigner
{
careerValue[user] = careerValue[user].add(incCV);
emit ChangedCareerValue(user, incCV, true);
}
/**
@notice Increments a user's career value
@param user The user
@param incCVInPeak The CV increase amount, in PEAK tokens
*/
function incrementCareerValueInPeak(address user, uint256 incCVInPeak)
public
regUser(user)
onlySigner
{
uint256 peakPriceInUsdc = _getPeakPriceInUsdc();
uint256 incCVInUsdc = incCVInPeak.mul(peakPriceInUsdc).div(
PEAK_PRECISION
);
careerValue[user] = careerValue[user].add(incCVInUsdc);
emit ChangedCareerValue(user, incCVInUsdc, true);
}
/**
@notice Returns a user's rank in the PeakDeFi system based only on career value
@param user The user whose rank will be queried
*/
function cvRankOf(address user) public view returns (uint256) {
uint256 cv = careerValue[user];
if (cv < USDC_PRECISION.mul(100)) {
return 0;
} else if (cv < USDC_PRECISION.mul(250)) {
return 1;
} else if (cv < USDC_PRECISION.mul(750)) {
return 2;
} else if (cv < USDC_PRECISION.mul(1500)) {
return 3;
} else if (cv < USDC_PRECISION.mul(3000)) {
return 4;
} else if (cv < USDC_PRECISION.mul(10000)) {
return 5;
} else if (cv < USDC_PRECISION.mul(50000)) {
return 6;
} else if (cv < USDC_PRECISION.mul(150000)) {
return 7;
} else {
return 8;
}
}
function rankUp(address user) external {
// verify rank up conditions
uint256 currentRank = rankOf[user];
uint256 cvRank = cvRankOf(user);
require(cvRank > currentRank, "PeakReward: career value is not enough!");
require(downlineRanks[user][currentRank] >= 2 || currentRank == 0, "PeakReward: downlines count and requirement not passed!");
// Target rank always should be +1 rank from current rank
uint256 targetRank = currentRank + 1;
// increase user rank
rankOf[user] = targetRank;
emit RankChange(user, currentRank, targetRank);
address referrer = referrerOf[user];
if (referrer != address(0)) {
downlineRanks[referrer][targetRank] = downlineRanks[referrer][targetRank]
.add(1);
downlineRanks[referrer][currentRank] = downlineRanks[referrer][currentRank]
.sub(1);
}
// give user rank reward
uint256 rewardInPeak = rankReward[currentRank][targetRank]
.mul(PEAK_PRECISION)
.div(_getPeakPriceInUsdc());
if (mintedPeakTokens.add(rewardInPeak) <= PEAK_MINT_CAP) {
// mint if under cap, do nothing if over cap
mintedPeakTokens = mintedPeakTokens.add(rewardInPeak);
peakToken.mint(user, rewardInPeak);
emit ReceiveRankReward(user, rewardInPeak);
}
}
function canRankUp(address user) external view returns (bool) {
uint256 currentRank = rankOf[user];
uint256 cvRank = cvRankOf(user);
return
(cvRank > currentRank) &&
(downlineRanks[user][currentRank] >= 2 || currentRank == 0);
}
/**
@notice Returns a user's current staked PEAK amount, scaled by `PEAK_PRECISION`.
@param user The user whose stake will be queried
*/
function _peakStakeOf(address user) internal view returns (uint256) {
return peakStaking.userStakeAmount(user);
}
/**
@notice Returns the price of PEAK token in Usdc, scaled by `USDC_PRECISION`.
*/
function _getPeakPriceInUsdc() internal returns (uint256) {
oracle.update();
uint256 priceInUSDC = oracle.consult(address(peakToken), PEAK_PRECISION);
if (priceInUSDC == 0) {
return USDC_PRECISION.mul(3).div(10);
}
return priceInUSDC;
}
}
pragma solidity ^0.5.0;
import "../../GSN/Context.sol";
import "../Roles.sol";
contract SignerRole is Context {
using Roles for Roles.Role;
event SignerAdded(address indexed account);
event SignerRemoved(address indexed account);
Roles.Role private _signers;
constructor () internal {
_addSigner(_msgSender());
}
modifier onlySigner() {
require(isSigner(_msgSender()), "SignerRole: caller does not have the Signer role");
_;
}
function isSigner(address account) public view returns (bool) {
return _signers.has(account);
}
function addSigner(address account) public onlySigner {
_addSigner(account);
}
function renounceSigner() public {
_removeSigner(_msgSender());
}
function _addSigner(address account) internal {
_signers.add(account);
emit SignerAdded(account);
}
function _removeSigner(address account) internal {
_signers.remove(account);
emit SignerRemoved(account);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../reward/PeakReward.sol";
import "../PeakToken.sol";
contract PeakStaking {
using SafeMath for uint256;
using SafeERC20 for PeakToken;
event CreateStake(
uint256 idx,
address user,
address referrer,
uint256 stakeAmount,
uint256 stakeTimeInDays,
uint256 interestAmount
);
event ReceiveStakeReward(uint256 idx, address user, uint256 rewardAmount);
event WithdrawReward(uint256 idx, address user, uint256 rewardAmount);
event WithdrawStake(uint256 idx, address user);
uint256 internal constant PRECISION = 10**18;
uint256 internal constant PEAK_PRECISION = 10**8;
uint256 internal constant INTEREST_SLOPE = 2 * (10**8); // Interest rate factor drops to 0 at 5B mintedPeakTokens
uint256 internal constant BIGGER_BONUS_DIVISOR = 10**15; // biggerBonus = stakeAmount / (10 million peak)
uint256 internal constant MAX_BIGGER_BONUS = 10**17; // biggerBonus <= 10%
uint256 internal constant DAILY_BASE_REWARD = 15 * (10**14); // dailyBaseReward = 0.0015
uint256 internal constant DAILY_GROWING_REWARD = 10**12; // dailyGrowingReward = 1e-6
uint256 internal constant MAX_STAKE_PERIOD = 1000; // Max staking time is 1000 days
uint256 internal constant MIN_STAKE_PERIOD = 10; // Min staking time is 10 days
uint256 internal constant DAY_IN_SECONDS = 86400;
uint256 internal constant COMMISSION_RATE = 20 * (10**16); // 20%
uint256 internal constant REFERRAL_STAKER_BONUS = 3 * (10**16); // 3%
uint256 internal constant YEAR_IN_DAYS = 365;
uint256 public constant PEAK_MINT_CAP = 7 * 10**16; // 700 million PEAK
struct Stake {
address staker;
uint256 stakeAmount;
uint256 interestAmount;
uint256 withdrawnInterestAmount;
uint256 stakeTimestamp;
uint256 stakeTimeInDays;
bool active;
}
Stake[] public stakeList;
mapping(address => uint256) public userStakeAmount;
uint256 public mintedPeakTokens;
bool public initialized;
PeakToken public peakToken;
PeakReward public peakReward;
constructor(address _peakToken) public {
peakToken = PeakToken(_peakToken);
}
function init(address _peakReward) public {
require(!initialized, "PeakStaking: Already initialized");
initialized = true;
peakReward = PeakReward(_peakReward);
}
function stake(
uint256 stakeAmount,
uint256 stakeTimeInDays,
address referrer
) public returns (uint256 stakeIdx) {
require(
stakeTimeInDays >= MIN_STAKE_PERIOD,
"PeakStaking: stakeTimeInDays < MIN_STAKE_PERIOD"
);
require(
stakeTimeInDays <= MAX_STAKE_PERIOD,
"PeakStaking: stakeTimeInDays > MAX_STAKE_PERIOD"
);
// record stake
uint256 interestAmount = getInterestAmount(
stakeAmount,
stakeTimeInDays
);
stakeIdx = stakeList.length;
stakeList.push(
Stake({
staker: msg.sender,
stakeAmount: stakeAmount,
interestAmount: interestAmount,
withdrawnInterestAmount: 0,
stakeTimestamp: now,
stakeTimeInDays: stakeTimeInDays,
active: true
})
);
mintedPeakTokens = mintedPeakTokens.add(interestAmount);
userStakeAmount[msg.sender] = userStakeAmount[msg.sender].add(
stakeAmount
);
// transfer PEAK from msg.sender
peakToken.safeTransferFrom(msg.sender, address(this), stakeAmount);
// mint PEAK interest
peakToken.mint(address(this), interestAmount);
// handle referral
if (peakReward.canRefer(msg.sender, referrer)) {
peakReward.refer(msg.sender, referrer);
}
address actualReferrer = peakReward.referrerOf(msg.sender);
if (actualReferrer != address(0)) {
// pay referral bonus to referrer
uint256 rawCommission = interestAmount.mul(COMMISSION_RATE).div(
PRECISION
);
peakToken.mint(address(this), rawCommission);
peakToken.safeApprove(address(peakReward), rawCommission);
uint256 leftoverAmount = peakReward.payCommission(
actualReferrer,
address(peakToken),
rawCommission,
true
);
peakToken.burn(leftoverAmount);
// pay referral bonus to staker
uint256 referralStakerBonus = interestAmount
.mul(REFERRAL_STAKER_BONUS)
.div(PRECISION);
peakToken.mint(msg.sender, referralStakerBonus);
mintedPeakTokens = mintedPeakTokens.add(
rawCommission.sub(leftoverAmount).add(referralStakerBonus)
);
emit ReceiveStakeReward(stakeIdx, msg.sender, referralStakerBonus);
}
require(mintedPeakTokens <= PEAK_MINT_CAP, "PeakStaking: reached cap");
emit CreateStake(
stakeIdx,
msg.sender,
actualReferrer,
stakeAmount,
stakeTimeInDays,
interestAmount
);
}
function withdraw(uint256 stakeIdx) public {
Stake storage stakeObj = stakeList[stakeIdx];
require(
stakeObj.staker == msg.sender,
"PeakStaking: Sender not staker"
);
require(stakeObj.active, "PeakStaking: Not active");
// calculate amount that can be withdrawn
uint256 stakeTimeInSeconds = stakeObj.stakeTimeInDays.mul(
DAY_IN_SECONDS
);
uint256 withdrawAmount;
if (now >= stakeObj.stakeTimestamp.add(stakeTimeInSeconds)) {
// matured, withdraw all
withdrawAmount = stakeObj
.stakeAmount
.add(stakeObj.interestAmount)
.sub(stakeObj.withdrawnInterestAmount);
stakeObj.active = false;
stakeObj.withdrawnInterestAmount = stakeObj.interestAmount;
userStakeAmount[msg.sender] = userStakeAmount[msg.sender].sub(
stakeObj.stakeAmount
);
emit WithdrawReward(
stakeIdx,
msg.sender,
stakeObj.interestAmount.sub(stakeObj.withdrawnInterestAmount)
);
emit WithdrawStake(stakeIdx, msg.sender);
} else {
// not mature, partial withdraw
withdrawAmount = stakeObj
.interestAmount
.mul(uint256(now).sub(stakeObj.stakeTimestamp))
.div(stakeTimeInSeconds)
.sub(stakeObj.withdrawnInterestAmount);
// record withdrawal
stakeObj.withdrawnInterestAmount = stakeObj
.withdrawnInterestAmount
.add(withdrawAmount);
emit WithdrawReward(stakeIdx, msg.sender, withdrawAmount);
}
// withdraw interest to sender
peakToken.safeTransfer(msg.sender, withdrawAmount);
}
function getInterestAmount(uint256 stakeAmount, uint256 stakeTimeInDays)
public
view
returns (uint256)
{
uint256 earlyFactor = _earlyFactor(mintedPeakTokens);
uint256 biggerBonus = stakeAmount.mul(PRECISION).div(
BIGGER_BONUS_DIVISOR
);
if (biggerBonus > MAX_BIGGER_BONUS) {
biggerBonus = MAX_BIGGER_BONUS;
}
// convert yearly bigger bonus to stake time
biggerBonus = biggerBonus.mul(stakeTimeInDays).div(YEAR_IN_DAYS);
uint256 longerBonus = _longerBonus(stakeTimeInDays);
uint256 interestRate = biggerBonus.add(longerBonus).mul(earlyFactor).div(
PRECISION
);
uint256 interestAmount = stakeAmount.mul(interestRate).div(PRECISION);
return interestAmount;
}
function _longerBonus(uint256 stakeTimeInDays)
internal
pure
returns (uint256)
{
return
DAILY_BASE_REWARD.mul(stakeTimeInDays).add(
DAILY_GROWING_REWARD
.mul(stakeTimeInDays)
.mul(stakeTimeInDays.add(1))
.div(2)
);
}
function _earlyFactor(uint256 _mintedPeakTokens)
internal
pure
returns (uint256)
{
uint256 tmp = INTEREST_SLOPE.mul(_mintedPeakTokens).div(PEAK_PRECISION);
if (tmp > PRECISION) {
return 0;
}
return PRECISION.sub(tmp);
}
}
pragma solidity 0.5.17;
import "./lib/CloneFactory.sol";
import "./tokens/minime/MiniMeToken.sol";
import "./PeakDeFiFund.sol";
import "./PeakDeFiProxy.sol";
import "@openzeppelin/contracts/utils/Address.sol";
contract PeakDeFiFactory is CloneFactory {
using Address for address;
event CreateFund(address fund);
event InitFund(address fund, address proxy);
address public usdcAddr;
address payable public kyberAddr;
address payable public oneInchAddr;
address payable public peakdefiFund;
address public peakdefiLogic;
address public peakdefiLogic2;
address public peakdefiLogic3;
address public peakRewardAddr;
address public peakStakingAddr;
MiniMeTokenFactory public minimeFactory;
mapping(address => address) public fundCreator;
constructor(
address _usdcAddr,
address payable _kyberAddr,
address payable _oneInchAddr,
address payable _peakdefiFund,
address _peakdefiLogic,
address _peakdefiLogic2,
address _peakdefiLogic3,
address _peakRewardAddr,
address _peakStakingAddr,
address _minimeFactoryAddr
) public {
usdcAddr = _usdcAddr;
kyberAddr = _kyberAddr;
oneInchAddr = _oneInchAddr;
peakdefiFund = _peakdefiFund;
peakdefiLogic = _peakdefiLogic;
peakdefiLogic2 = _peakdefiLogic2;
peakdefiLogic3 = _peakdefiLogic3;
peakRewardAddr = _peakRewardAddr;
peakStakingAddr = _peakStakingAddr;
minimeFactory = MiniMeTokenFactory(_minimeFactoryAddr);
}
function createFund() external returns (PeakDeFiFund) {
// create fund
PeakDeFiFund fund = PeakDeFiFund(createClone(peakdefiFund).toPayable());
fund.initOwner();
// give PeakReward signer rights to fund
PeakReward peakReward = PeakReward(peakRewardAddr);
peakReward.addSigner(address(fund));
fundCreator[address(fund)] = msg.sender;
emit CreateFund(address(fund));
return fund;
}
function initFund1(
PeakDeFiFund fund,
string calldata reptokenName,
string calldata reptokenSymbol,
string calldata sharesName,
string calldata sharesSymbol
) external {
require(
fundCreator[address(fund)] == msg.sender,
"PeakDeFiFactory: not creator"
);
// create tokens
MiniMeToken reptoken = minimeFactory.createCloneToken(
address(0),
0,
reptokenName,
18,
reptokenSymbol,
false
);
MiniMeToken shares = minimeFactory.createCloneToken(
address(0),
0,
sharesName,
18,
sharesSymbol,
true
);
MiniMeToken peakReferralToken = minimeFactory.createCloneToken(
address(0),
0,
"Peak Referral Token",
18,
"PRT",
false
);
// transfer token ownerships to fund
reptoken.transferOwnership(address(fund));
shares.transferOwnership(address(fund));
peakReferralToken.transferOwnership(address(fund));
fund.initInternalTokens(
address(reptoken),
address(shares),
address(peakReferralToken)
);
}
function initFund2(
PeakDeFiFund fund,
address payable _devFundingAccount,
uint256 _devFundingRate,
uint256[2] calldata _phaseLengths,
address _compoundFactoryAddr
) external {
require(
fundCreator[address(fund)] == msg.sender,
"PeakDeFiFactory: not creator"
);
fund.initParams(
_devFundingAccount,
_phaseLengths,
_devFundingRate,
address(0),
usdcAddr,
kyberAddr,
_compoundFactoryAddr,
peakdefiLogic,
peakdefiLogic2,
peakdefiLogic3,
1,
oneInchAddr,
peakRewardAddr,
peakStakingAddr
);
}
function initFund3(
PeakDeFiFund fund,
uint256 _newManagerRepToken,
uint256 _maxNewManagersPerCycle,
uint256 _reptokenPrice,
uint256 _peakManagerStakeRequired,
bool _isPermissioned
) external {
require(
fundCreator[address(fund)] == msg.sender,
"PeakDeFiFactory: not creator"
);
fund.initRegistration(
_newManagerRepToken,
_maxNewManagersPerCycle,
_reptokenPrice,
_peakManagerStakeRequired,
_isPermissioned
);
}
function initFund4(
PeakDeFiFund fund,
address[] calldata _kyberTokens,
address[] calldata _compoundTokens
) external {
require(
fundCreator[address(fund)] == msg.sender,
"PeakDeFiFactory: not creator"
);
fund.initTokenListings(_kyberTokens, _compoundTokens);
// deploy and set PeakDeFiProxy
PeakDeFiProxy proxy = new PeakDeFiProxy(address(fund));
fund.setProxy(address(proxy).toPayable());
// transfer fund ownership to msg.sender
fund.transferOwnership(msg.sender);
emit InitFund(address(fund), address(proxy));
}
}
pragma solidity 0.5.17;
/*
Copyright 2016, Jordi Baylina
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/// @title MiniMeToken Contract
/// @author Jordi Baylina
/// @dev This token contract's goal is to make it easy for anyone to clone this
/// token using the token distribution at a given block, this will allow DAO's
/// and DApps to upgrade their features in a decentralized manner without
/// affecting the original token
/// @dev It is ERC20 compliant, but still needs to under go further testing.
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "./TokenController.sol";
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 _amount, address _token, bytes memory _data) public;
}
/// @dev The actual token contract, the default owner is the msg.sender
/// that deploys the contract, so usually this token will be deployed by a
/// token owner contract, which Giveth will call a "Campaign"
contract MiniMeToken is Ownable {
string public name; //The Token's name: e.g. DigixDAO Tokens
uint8 public decimals; //Number of decimals of the smallest unit
string public symbol; //An identifier: e.g. REP
string public version = "MMT_0.2"; //An arbitrary versioning scheme
/// @dev `Checkpoint` is the structure that attaches a block number to a
/// given value, the block number attached is the one that last changed the
/// value
struct Checkpoint {
// `fromBlock` is the block number that the value was generated from
uint128 fromBlock;
// `value` is the amount of tokens at a specific block number
uint128 value;
}
// `parentToken` is the Token address that was cloned to produce this token;
// it will be 0x0 for a token that was not cloned
MiniMeToken public parentToken;
// `parentSnapShotBlock` is the block number from the Parent Token that was
// used to determine the initial distribution of the Clone Token
uint public parentSnapShotBlock;
// `creationBlock` is the block number that the Clone Token was created
uint public creationBlock;
// `balances` is the map that tracks the balance of each address, in this
// contract when the balance changes the block number that the change
// occurred is also included in the map
mapping (address => Checkpoint[]) balances;
// `allowed` tracks any extra transfer rights as in all ERC20 tokens
mapping (address => mapping (address => uint256)) allowed;
// Tracks the history of the `totalSupply` of the token
Checkpoint[] totalSupplyHistory;
// Flag that determines if the token is transferable or not.
bool public transfersEnabled;
// The factory used to create new clone tokens
MiniMeTokenFactory public tokenFactory;
////////////////
// Constructor
////////////////
/// @notice Constructor to create a MiniMeToken
/// @param _tokenFactory The address of the MiniMeTokenFactory contract that
/// will create the Clone token contracts, the token factory needs to be
/// deployed first
/// @param _parentToken Address of the parent token, set to 0x0 if it is a
/// new token
/// @param _parentSnapShotBlock Block of the parent token that will
/// determine the initial distribution of the clone token, set to 0 if it
/// is a new token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
constructor(
address _tokenFactory,
address payable _parentToken,
uint _parentSnapShotBlock,
string memory _tokenName,
uint8 _decimalUnits,
string memory _tokenSymbol,
bool _transfersEnabled
) public {
tokenFactory = MiniMeTokenFactory(_tokenFactory);
name = _tokenName; // Set the name
decimals = _decimalUnits; // Set the decimals
symbol = _tokenSymbol; // Set the symbol
parentToken = MiniMeToken(_parentToken);
parentSnapShotBlock = _parentSnapShotBlock;
transfersEnabled = _transfersEnabled;
creationBlock = block.number;
}
///////////////////
// ERC20 Methods
///////////////////
/// @notice Send `_amount` tokens to `_to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return Whether the transfer was successful or not
function transfer(address _to, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
doTransfer(msg.sender, _to, _amount);
return true;
}
/// @notice Send `_amount` tokens to `_to` from `_from` on the condition it
/// is approved by `_from`
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function transferFrom(address _from, address _to, uint256 _amount
) public returns (bool success) {
// The owner of this contract can move tokens around at will,
// this is important to recognize! Confirm that you trust the
// owner of this contract, which in most situations should be
// another open source smart contract or 0x0
if (msg.sender != owner()) {
require(transfersEnabled);
// The standard ERC 20 transferFrom functionality
require(allowed[_from][msg.sender] >= _amount);
allowed[_from][msg.sender] -= _amount;
}
doTransfer(_from, _to, _amount);
return true;
}
/// @dev This is the actual transfer function in the token contract, it can
/// only be called by other functions in this contract.
/// @param _from The address holding the tokens being transferred
/// @param _to The address of the recipient
/// @param _amount The amount of tokens to be transferred
/// @return True if the transfer was successful
function doTransfer(address _from, address _to, uint _amount
) internal {
if (_amount == 0) {
emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0
return;
}
require(parentSnapShotBlock < block.number);
// Do not allow transfer to 0x0 or the token contract itself
require((_to != address(0)) && (_to != address(this)));
// If the amount being transfered is more than the balance of the
// account the transfer throws
uint previousBalanceFrom = balanceOfAt(_from, block.number);
require(previousBalanceFrom >= _amount);
// Alerts the token owner of the transfer
if (isContract(owner())) {
require(TokenController(owner()).onTransfer(_from, _to, _amount));
}
// First update the balance array with the new value for the address
// sending the tokens
updateValueAtNow(balances[_from], previousBalanceFrom - _amount);
// Then update the balance array with the new value for the address
// receiving the tokens
uint previousBalanceTo = balanceOfAt(_to, block.number);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(balances[_to], previousBalanceTo + _amount);
// An event to make the transfer easy to find on the blockchain
emit Transfer(_from, _to, _amount);
}
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) public view returns (uint256 balance) {
return balanceOfAt(_owner, block.number);
}
/// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on
/// its behalf. This is a modified version of the ERC20 approve function
/// to be a little bit safer
/// @param _spender The address of the account able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the approval was successful
function approve(address _spender, uint256 _amount) public returns (bool success) {
require(transfersEnabled);
// To change the approve amount you first have to reduce the addresses`
// allowance to zero by calling `approve(_spender,0)` if it is not
// already 0 to mitigate the race condition described here:
// https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
require((_amount == 0) || (allowed[msg.sender][_spender] == 0));
// Alerts the token owner of the approve function call
if (isContract(owner())) {
require(TokenController(owner()).onApprove(msg.sender, _spender, _amount));
}
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/// @dev This function makes it easy to read the `allowed[]` map
/// @param _owner The address of the account that owns the token
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens of _owner that _spender is allowed
/// to spend
function allowance(address _owner, address _spender
) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/// @notice `msg.sender` approves `_spender` to send `_amount` tokens on
/// its behalf, and then a function is triggered in the contract that is
/// being approved, `_spender`. This allows users to use their tokens to
/// interact with contracts in one function call instead of two
/// @param _spender The address of the contract able to transfer the tokens
/// @param _amount The amount of tokens to be approved for transfer
/// @return True if the function call was successful
function approveAndCall(address _spender, uint256 _amount, bytes memory _extraData
) public returns (bool success) {
require(approve(_spender, _amount));
ApproveAndCallFallBack(_spender).receiveApproval(
msg.sender,
_amount,
address(this),
_extraData
);
return true;
}
/// @dev This function makes it easy to get the total number of tokens
/// @return The total number of tokens
function totalSupply() public view returns (uint) {
return totalSupplyAt(block.number);
}
////////////////
// Query balance and totalSupply in History
////////////////
/// @dev Queries the balance of `_owner` at a specific `_blockNumber`
/// @param _owner The address from which the balance will be retrieved
/// @param _blockNumber The block number when the balance is queried
/// @return The balance at `_blockNumber`
function balanceOfAt(address _owner, uint _blockNumber) public view
returns (uint) {
// These next few lines are used when the balance of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.balanceOfAt` be queried at the
// genesis block for that token as this contains initial balance of
// this token
if ((balances[_owner].length == 0)
|| (balances[_owner][0].fromBlock > _blockNumber)) {
if (address(parentToken) != address(0)) {
return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock));
} else {
// Has no parent
return 0;
}
// This will return the expected balance during normal situations
} else {
return getValueAt(balances[_owner], _blockNumber);
}
}
/// @notice Total amount of tokens at a specific `_blockNumber`.
/// @param _blockNumber The block number when the totalSupply is queried
/// @return The total amount of tokens at `_blockNumber`
function totalSupplyAt(uint _blockNumber) public view returns(uint) {
// These next few lines are used when the totalSupply of the token is
// requested before a check point was ever created for this token, it
// requires that the `parentToken.totalSupplyAt` be queried at the
// genesis block for this token as that contains totalSupply of this
// token at this block number.
if ((totalSupplyHistory.length == 0)
|| (totalSupplyHistory[0].fromBlock > _blockNumber)) {
if (address(parentToken) != address(0)) {
return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock));
} else {
return 0;
}
// This will return the expected totalSupply during normal situations
} else {
return getValueAt(totalSupplyHistory, _blockNumber);
}
}
////////////////
// Clone Token Method
////////////////
/// @notice Creates a new clone token with the initial distribution being
/// this token at `_snapshotBlock`
/// @param _cloneTokenName Name of the clone token
/// @param _cloneDecimalUnits Number of decimals of the smallest unit
/// @param _cloneTokenSymbol Symbol of the clone token
/// @param _snapshotBlock Block when the distribution of the parent token is
/// copied to set the initial distribution of the new clone token;
/// if the block is zero than the actual block, the current block is used
/// @param _transfersEnabled True if transfers are allowed in the clone
/// @return The address of the new MiniMeToken Contract
function createCloneToken(
string memory _cloneTokenName,
uint8 _cloneDecimalUnits,
string memory _cloneTokenSymbol,
uint _snapshotBlock,
bool _transfersEnabled
) public returns(address) {
uint snapshotBlock = _snapshotBlock;
if (snapshotBlock == 0) snapshotBlock = block.number;
MiniMeToken cloneToken = tokenFactory.createCloneToken(
address(this),
snapshotBlock,
_cloneTokenName,
_cloneDecimalUnits,
_cloneTokenSymbol,
_transfersEnabled
);
cloneToken.transferOwnership(msg.sender);
// An event to make the token easy to find on the blockchain
emit NewCloneToken(address(cloneToken), snapshotBlock);
return address(cloneToken);
}
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount
) public onlyOwner returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow
uint previousBalanceTo = balanceOf(_owner);
require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow
updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount);
updateValueAtNow(balances[_owner], previousBalanceTo + _amount);
emit Transfer(address(0), _owner, _amount);
return true;
}
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount
) onlyOwner public returns (bool) {
uint curTotalSupply = totalSupply();
require(curTotalSupply >= _amount);
uint previousBalanceFrom = balanceOf(_owner);
require(previousBalanceFrom >= _amount);
updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount);
updateValueAtNow(balances[_owner], previousBalanceFrom - _amount);
emit Transfer(_owner, address(0), _amount);
return true;
}
////////////////
// Enable tokens transfers
////////////////
/// @notice Enables token holders to transfer their tokens freely if true
/// @param _transfersEnabled True if transfers are allowed in the clone
function enableTransfers(bool _transfersEnabled) public onlyOwner {
transfersEnabled = _transfersEnabled;
}
////////////////
// Internal helper functions to query and set a value in a snapshot array
////////////////
/// @dev `getValueAt` retrieves the number of tokens at a given block number
/// @param checkpoints The history of values being queried
/// @param _block The block number to retrieve the value at
/// @return The number of tokens being queried
function getValueAt(Checkpoint[] storage checkpoints, uint _block
) view internal returns (uint) {
if (checkpoints.length == 0) return 0;
// Shortcut for the actual value
if (_block >= checkpoints[checkpoints.length-1].fromBlock)
return checkpoints[checkpoints.length-1].value;
if (_block < checkpoints[0].fromBlock) return 0;
// Binary search of the value in the array
uint min = 0;
uint max = checkpoints.length-1;
while (max > min) {
uint mid = (max + min + 1)/ 2;
if (checkpoints[mid].fromBlock<=_block) {
min = mid;
} else {
max = mid-1;
}
}
return checkpoints[min].value;
}
/// @dev `updateValueAtNow` used to update the `balances` map and the
/// `totalSupplyHistory`
/// @param checkpoints The history of data being updated
/// @param _value The new number of tokens
function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value
) internal {
if ((checkpoints.length == 0)
|| (checkpoints[checkpoints.length -1].fromBlock < block.number)) {
Checkpoint storage newCheckPoint = checkpoints[ checkpoints.length++ ];
newCheckPoint.fromBlock = uint128(block.number);
newCheckPoint.value = uint128(_value);
} else {
Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1];
oldCheckPoint.value = uint128(_value);
}
}
/// @dev Internal function to determine if an address is a contract
/// @param _addr The address being queried
/// @return True if `_addr` is a contract
function isContract(address _addr) view internal returns(bool) {
uint size;
if (_addr == address(0)) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
/// @dev Helper function to return a min betwen the two uints
function min(uint a, uint b) pure internal returns (uint) {
return a < b ? a : b;
}
/// @notice The fallback function: If the contract's owner has not been
/// set to 0, then the `proxyPayment` method is called which relays the
/// ether and creates tokens as described in the token owner contract
function () external payable {
require(isContract(owner()));
require(TokenController(owner()).proxyPayment.value(msg.value)(msg.sender));
}
//////////
// Safety Methods
//////////
/// @notice This method can be used by the owner to extract mistakenly
/// sent tokens to this contract.
/// @param _token The address of the token contract that you want to recover
/// set to 0 in case you want to extract ether.
function claimTokens(address payable _token) public onlyOwner {
if (_token == address(0)) {
address(uint160(owner())).transfer(address(this).balance);
return;
}
MiniMeToken token = MiniMeToken(_token);
uint balance = token.balanceOf(address(this));
require(token.transfer(owner(), balance));
emit ClaimedTokens(_token, owner(), balance);
}
////////////////
// Events
////////////////
event ClaimedTokens(address indexed _token, address indexed _owner, uint _amount);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _amount
);
}
////////////////
// MiniMeTokenFactory
////////////////
/// @dev This contract is used to generate clone contracts from a contract.
/// In solidity this is the way to create a contract from a contract of the
/// same class
contract MiniMeTokenFactory {
event CreatedToken(string symbol, address addr);
/// @notice Update the DApp by creating a new token with new functionalities
/// the msg.sender becomes the owner of this clone token
/// @param _parentToken Address of the token being cloned
/// @param _snapshotBlock Block of the parent token that will
/// determine the initial distribution of the clone token
/// @param _tokenName Name of the new token
/// @param _decimalUnits Number of decimals of the new token
/// @param _tokenSymbol Token Symbol for the new token
/// @param _transfersEnabled If true, tokens will be able to be transferred
/// @return The address of the new token contract
function createCloneToken(
address payable _parentToken,
uint _snapshotBlock,
string memory _tokenName,
uint8 _decimalUnits,
string memory _tokenSymbol,
bool _transfersEnabled
) public returns (MiniMeToken) {
MiniMeToken newToken = new MiniMeToken(
address(this),
_parentToken,
_snapshotBlock,
_tokenName,
_decimalUnits,
_tokenSymbol,
_transfersEnabled
);
newToken.transferOwnership(msg.sender);
emit CreatedToken(_tokenSymbol, address(newToken));
return newToken;
}
}
pragma solidity 0.5.17;
/// @dev The token controller contract must implement these functions
contract TokenController {
/// @notice Called when `_owner` sends ether to the MiniMe Token contract
/// @param _owner The address that sent the ether to create tokens
/// @return True if the ether is accepted, false if it throws
function proxyPayment(address _owner) public payable returns(bool);
/// @notice Notifies the controller about a token transfer allowing the
/// controller to react if desired
/// @param _from The origin of the transfer
/// @param _to The destination of the transfer
/// @param _amount The amount of the transfer
/// @return False if the controller does not authorize the transfer
function onTransfer(address _from, address _to, uint _amount) public returns(bool);
/// @notice Notifies the controller about an approval allowing the
/// controller to react if desired
/// @param _owner The address that calls `approve()`
/// @param _spender The spender in the `approve()` call
/// @param _amount The amount in the `approve()` call
/// @return False if the controller does not authorize the approval
function onApprove(address _owner, address _spender, uint _amount) public
returns(bool);
}
pragma solidity 0.5.17;
import "./PeakDeFiStorage.sol";
import "./derivatives/CompoundOrderFactory.sol";
/**
* @title The main smart contract of the PeakDeFi hedge fund.
* @author Zefram Lou (Zebang Liu)
*/
contract PeakDeFiFund is
PeakDeFiStorage,
Utils(address(0), address(0), address(0)),
TokenController
{
/**
* @notice Passes if the fund is ready for migrating to the next version
*/
modifier readyForUpgradeMigration {
require(hasFinalizedNextVersion == true);
require(
now >
startTimeOfCyclePhase.add(
phaseLengths[uint256(CyclePhase.Intermission)]
)
);
_;
}
/**
* Meta functions
*/
function initParams(
address payable _devFundingAccount,
uint256[2] calldata _phaseLengths,
uint256 _devFundingRate,
address payable _previousVersion,
address _usdcAddr,
address payable _kyberAddr,
address _compoundFactoryAddr,
address _peakdefiLogic,
address _peakdefiLogic2,
address _peakdefiLogic3,
uint256 _startCycleNumber,
address payable _oneInchAddr,
address _peakRewardAddr,
address _peakStakingAddr
) external {
require(proxyAddr == address(0));
devFundingAccount = _devFundingAccount;
phaseLengths = _phaseLengths;
devFundingRate = _devFundingRate;
cyclePhase = CyclePhase.Intermission;
compoundFactoryAddr = _compoundFactoryAddr;
peakdefiLogic = _peakdefiLogic;
peakdefiLogic2 = _peakdefiLogic2;
peakdefiLogic3 = _peakdefiLogic3;
previousVersion = _previousVersion;
cycleNumber = _startCycleNumber;
peakReward = PeakReward(_peakRewardAddr);
peakStaking = PeakStaking(_peakStakingAddr);
USDC_ADDR = _usdcAddr;
KYBER_ADDR = _kyberAddr;
ONEINCH_ADDR = _oneInchAddr;
usdc = ERC20Detailed(_usdcAddr);
kyber = KyberNetwork(_kyberAddr);
__initReentrancyGuard();
}
function initOwner() external {
require(proxyAddr == address(0));
_transferOwnership(msg.sender);
}
function initInternalTokens(
address payable _repAddr,
address payable _sTokenAddr,
address payable _peakReferralTokenAddr
) external onlyOwner {
require(controlTokenAddr == address(0));
require(_repAddr != address(0));
controlTokenAddr = _repAddr;
shareTokenAddr = _sTokenAddr;
cToken = IMiniMeToken(_repAddr);
sToken = IMiniMeToken(_sTokenAddr);
peakReferralToken = IMiniMeToken(_peakReferralTokenAddr);
}
function initRegistration(
uint256 _newManagerRepToken,
uint256 _maxNewManagersPerCycle,
uint256 _reptokenPrice,
uint256 _peakManagerStakeRequired,
bool _isPermissioned
) external onlyOwner {
require(_newManagerRepToken > 0 && newManagerRepToken == 0);
newManagerRepToken = _newManagerRepToken;
maxNewManagersPerCycle = _maxNewManagersPerCycle;
reptokenPrice = _reptokenPrice;
peakManagerStakeRequired = _peakManagerStakeRequired;
isPermissioned = _isPermissioned;
}
function initTokenListings(
address[] calldata _kyberTokens,
address[] calldata _compoundTokens
) external onlyOwner {
// May only initialize once
require(!hasInitializedTokenListings);
hasInitializedTokenListings = true;
uint256 i;
for (i = 0; i < _kyberTokens.length; i++) {
isKyberToken[_kyberTokens[i]] = true;
}
CompoundOrderFactory factory = CompoundOrderFactory(compoundFactoryAddr);
for (i = 0; i < _compoundTokens.length; i++) {
require(factory.tokenIsListed(_compoundTokens[i]));
isCompoundToken[_compoundTokens[i]] = true;
}
}
/**
* @notice Used during deployment to set the PeakDeFiProxy contract address.
* @param _proxyAddr the proxy's address
*/
function setProxy(address payable _proxyAddr) external onlyOwner {
require(_proxyAddr != address(0));
require(proxyAddr == address(0));
proxyAddr = _proxyAddr;
proxy = PeakDeFiProxyInterface(_proxyAddr);
}
/**
* Upgrading functions
*/
/**
* @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to.
* The developer may change the candidate during the Intermission phase.
* @param _candidate the address of the candidate smart contract
* @return True if successfully changed candidate, false otherwise.
*/
function developerInitiateUpgrade(address payable _candidate)
public
returns (bool _success)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.developerInitiateUpgrade.selector,
_candidate
)
);
if (!success) {
return false;
}
return abi.decode(result, (bool));
}
/**
* @notice Transfers ownership of RepToken & Share token contracts to the next version. Also updates PeakDeFiFund's
* address in PeakDeFiProxy.
*/
function migrateOwnedContractsToNextVersion()
public
nonReentrant
readyForUpgradeMigration
{
cToken.transferOwnership(nextVersion);
sToken.transferOwnership(nextVersion);
peakReferralToken.transferOwnership(nextVersion);
proxy.updatePeakDeFiFundAddress();
}
/**
* @notice Transfers assets to the next version.
* @param _assetAddress the address of the asset to be transferred. Use ETH_TOKEN_ADDRESS to transfer Ether.
*/
function transferAssetToNextVersion(address _assetAddress)
public
nonReentrant
readyForUpgradeMigration
isValidToken(_assetAddress)
{
if (_assetAddress == address(ETH_TOKEN_ADDRESS)) {
nextVersion.transfer(address(this).balance);
} else {
ERC20Detailed token = ERC20Detailed(_assetAddress);
token.safeTransfer(nextVersion, token.balanceOf(address(this)));
}
}
/**
* Getters
*/
/**
* @notice Returns the length of the user's investments array.
* @return length of the user's investments array
*/
function investmentsCount(address _userAddr)
public
view
returns (uint256 _count)
{
return userInvestments[_userAddr].length;
}
/**
* @notice Returns the length of the user's compound orders array.
* @return length of the user's compound orders array
*/
function compoundOrdersCount(address _userAddr)
public
view
returns (uint256 _count)
{
return userCompoundOrders[_userAddr].length;
}
/**
* @notice Returns the phaseLengths array.
* @return the phaseLengths array
*/
function getPhaseLengths()
public
view
returns (uint256[2] memory _phaseLengths)
{
return phaseLengths;
}
/**
* @notice Returns the commission balance of `_manager`
* @return the commission balance and the received penalty, denoted in USDC
*/
function commissionBalanceOf(address _manager)
public
returns (uint256 _commission, uint256 _penalty)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(this.commissionBalanceOf.selector, _manager)
);
if (!success) {
return (0, 0);
}
return abi.decode(result, (uint256, uint256));
}
/**
* @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle
* @return the commission amount and the received penalty, denoted in USDC
*/
function commissionOfAt(address _manager, uint256 _cycle)
public
returns (uint256 _commission, uint256 _penalty)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.commissionOfAt.selector,
_manager,
_cycle
)
);
if (!success) {
return (0, 0);
}
return abi.decode(result, (uint256, uint256));
}
/**
* Parameter setters
*/
/**
* @notice Changes the address to which the developer fees will be sent. Only callable by owner.
* @param _newAddr the new developer fee address
*/
function changeDeveloperFeeAccount(address payable _newAddr)
public
onlyOwner
{
require(_newAddr != address(0) && _newAddr != address(this));
devFundingAccount = _newAddr;
}
/**
* @notice Changes the proportion of fund balance sent to the developers each cycle. May only decrease. Only callable by owner.
* @param _newProp the new proportion, fixed point decimal
*/
function changeDeveloperFeeRate(uint256 _newProp) public onlyOwner {
require(_newProp < PRECISION);
require(_newProp < devFundingRate);
devFundingRate = _newProp;
}
/**
* @notice Allows managers to invest in a token. Only callable by owner.
* @param _token address of the token to be listed
*/
function listKyberToken(address _token) public onlyOwner {
isKyberToken[_token] = true;
}
/**
* @notice Allows managers to invest in a Compound token. Only callable by owner.
* @param _token address of the Compound token to be listed
*/
function listCompoundToken(address _token) public onlyOwner {
CompoundOrderFactory factory = CompoundOrderFactory(
compoundFactoryAddr
);
require(factory.tokenIsListed(_token));
isCompoundToken[_token] = true;
}
/**
* @notice Moves the fund to the next phase in the investment cycle.
*/
function nextPhase() public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(this.nextPhase.selector)
);
if (!success) {
revert();
}
}
/**
* Manager registration
*/
/**
* @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
*/
function registerWithUSDC() public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.registerWithUSDC.selector)
);
if (!success) {
revert();
}
}
/**
* @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
*/
function registerWithETH() public payable {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.registerWithETH.selector)
);
if (!success) {
revert();
}
}
/**
* @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
* @param _token the token to be used for payment
* @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals
*/
function registerWithToken(address _token, uint256 _donationInTokens)
public
{
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.registerWithToken.selector,
_token,
_donationInTokens
)
);
if (!success) {
revert();
}
}
/**
* Intermission phase functions
*/
/**
* @notice Deposit Ether into the fund. Ether will be converted into USDC.
*/
function depositEther(address _referrer) public payable {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.depositEther.selector, _referrer)
);
if (!success) {
revert();
}
}
function depositEtherAdvanced(
bool _useKyber,
bytes calldata _calldata,
address _referrer
) external payable {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.depositEtherAdvanced.selector,
_useKyber,
_calldata,
_referrer
)
);
if (!success) {
revert();
}
}
/**
* @notice Deposit USDC Stablecoin into the fund.
* @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount.
*/
function depositUSDC(uint256 _usdcAmount, address _referrer) public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.depositUSDC.selector,
_usdcAmount,
_referrer
)
);
if (!success) {
revert();
}
}
/**
* @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC.
* @param _tokenAddr the address of the token to be deposited
* @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount.
*/
function depositToken(
address _tokenAddr,
uint256 _tokenAmount,
address _referrer
) public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.depositToken.selector,
_tokenAddr,
_tokenAmount,
_referrer
)
);
if (!success) {
revert();
}
}
function depositTokenAdvanced(
address _tokenAddr,
uint256 _tokenAmount,
bool _useKyber,
bytes calldata _calldata,
address _referrer
) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.depositTokenAdvanced.selector,
_tokenAddr,
_tokenAmount,
_useKyber,
_calldata,
_referrer
)
);
if (!success) {
revert();
}
}
/**
* @notice Withdraws Ether by burning Shares.
* @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
*/
function withdrawEther(uint256 _amountInUSDC) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.withdrawEther.selector, _amountInUSDC)
);
if (!success) {
revert();
}
}
function withdrawEtherAdvanced(
uint256 _amountInUSDC,
bool _useKyber,
bytes calldata _calldata
) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.withdrawEtherAdvanced.selector,
_amountInUSDC,
_useKyber,
_calldata
)
);
if (!success) {
revert();
}
}
/**
* @notice Withdraws Ether by burning Shares.
* @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
*/
function withdrawUSDC(uint256 _amountInUSDC) public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(this.withdrawUSDC.selector, _amountInUSDC)
);
if (!success) {
revert();
}
}
/**
* @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network.
* @param _tokenAddr the address of the token to be withdrawn into the caller's account
* @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
*/
function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.withdrawToken.selector,
_tokenAddr,
_amountInUSDC
)
);
if (!success) {
revert();
}
}
function withdrawTokenAdvanced(
address _tokenAddr,
uint256 _amountInUSDC,
bool _useKyber,
bytes calldata _calldata
) external {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.withdrawTokenAdvanced.selector,
_tokenAddr,
_amountInUSDC,
_useKyber,
_calldata
)
);
if (!success) {
revert();
}
}
/**
* @notice Redeems commission.
*/
function redeemCommission(bool _inShares) public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(this.redeemCommission.selector, _inShares)
);
if (!success) {
revert();
}
}
/**
* @notice Redeems commission for a particular cycle.
* @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC
* @param _cycle the cycle for which the commission will be redeemed.
* Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber.
*/
function redeemCommissionForCycle(bool _inShares, uint256 _cycle) public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.redeemCommissionForCycle.selector,
_inShares,
_cycle
)
);
if (!success) {
revert();
}
}
/**
* @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer.
* @param _tokenAddr address of the token to be sold
* @param _calldata the 1inch trade call data
*/
function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata)
external
{
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.sellLeftoverToken.selector,
_tokenAddr,
_calldata
)
);
if (!success) {
revert();
}
}
/**
* @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer.
* @param _orderAddress address of the CompoundOrder to be sold
*/
function sellLeftoverCompoundOrder(address payable _orderAddress) public {
(bool success, ) = peakdefiLogic2.delegatecall(
abi.encodeWithSelector(
this.sellLeftoverCompoundOrder.selector,
_orderAddress
)
);
if (!success) {
revert();
}
}
/**
* @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles
* @param _deadman the manager whose RepToken balance will be burned
*/
function burnDeadman(address _deadman) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(this.burnDeadman.selector, _deadman)
);
if (!success) {
revert();
}
}
/**
* Manage phase functions
*/
function createInvestmentWithSignature(
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice,
bytes calldata _calldata,
bool _useKyber,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createInvestmentWithSignature.selector,
_tokenAddress,
_stake,
_maxPrice,
_calldata,
_useKyber,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
function sellInvestmentWithSignature(
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice,
uint256 _maxPrice,
bytes calldata _calldata,
bool _useKyber,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellInvestmentWithSignature.selector,
_investmentId,
_tokenAmount,
_minPrice,
_maxPrice,
_calldata,
_useKyber,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
function createCompoundOrderWithSignature(
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 _minPrice,
uint256 _maxPrice,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createCompoundOrderWithSignature.selector,
_orderType,
_tokenAddress,
_stake,
_minPrice,
_maxPrice,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
function sellCompoundOrderWithSignature(
uint256 _orderId,
uint256 _minPrice,
uint256 _maxPrice,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellCompoundOrderWithSignature.selector,
_orderId,
_minPrice,
_maxPrice,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
function repayCompoundOrderWithSignature(
uint256 _orderId,
uint256 _repayAmountInUSDC,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.repayCompoundOrderWithSignature.selector,
_orderId,
_repayAmountInUSDC,
_manager,
_salt,
_signature
)
);
if (!success) {
revert();
}
}
/**
* @notice Creates a new investment for an ERC20 token.
* @param _tokenAddress address of the ERC20 token contract
* @param _stake amount of RepTokens to be staked in support of the investment
* @param _maxPrice the maximum price for the trade
*/
function createInvestment(
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createInvestment.selector,
_tokenAddress,
_stake,
_maxPrice
)
);
if (!success) {
revert();
}
}
/**
* @notice Creates a new investment for an ERC20 token.
* @param _tokenAddress address of the ERC20 token contract
* @param _stake amount of RepTokens to be staked in support of the investment
* @param _maxPrice the maximum price for the trade
* @param _calldata calldata for 1inch trading
* @param _useKyber true for Kyber Network, false for 1inch
*/
function createInvestmentV2(
address _sender,
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice,
bytes memory _calldata,
bool _useKyber
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createInvestmentV2.selector,
_sender,
_tokenAddress,
_stake,
_maxPrice,
_calldata,
_useKyber
)
);
if (!success) {
revert();
}
}
/**
* @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user.
* The user can sell only part of the investment by changing _tokenAmount.
* @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with
* the original buy price and however much tokens that are not sold.
* @param _investmentId the ID of the investment
* @param _tokenAmount the amount of tokens to be sold.
* @param _minPrice the minimum price for the trade
*/
function sellInvestmentAsset(
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellInvestmentAsset.selector,
_investmentId,
_tokenAmount,
_minPrice
)
);
if (!success) {
revert();
}
}
/**
* @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user.
* The user can sell only part of the investment by changing _tokenAmount.
* @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with
* the original buy price and however much tokens that are not sold.
* @param _investmentId the ID of the investment
* @param _tokenAmount the amount of tokens to be sold.
* @param _minPrice the minimum price for the trade
*/
function sellInvestmentAssetV2(
address _sender,
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice,
bytes memory _calldata,
bool _useKyber
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellInvestmentAssetV2.selector,
_sender,
_investmentId,
_tokenAmount,
_minPrice,
_calldata,
_useKyber
)
);
if (!success) {
revert();
}
}
/**
* @notice Creates a new Compound order to either short or leverage long a token.
* @param _orderType true for a short order, false for a levarage long order
* @param _tokenAddress address of the Compound token to be traded
* @param _stake amount of RepTokens to be staked
* @param _minPrice the minimum token price for the trade
* @param _maxPrice the maximum token price for the trade
*/
function createCompoundOrder(
address _sender,
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 _minPrice,
uint256 _maxPrice
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.createCompoundOrder.selector,
_sender,
_orderType,
_tokenAddress,
_stake,
_minPrice,
_maxPrice
)
);
if (!success) {
revert();
}
}
/**
* @notice Sells a compound order
* @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender])
* @param _minPrice the minimum token price for the trade
* @param _maxPrice the maximum token price for the trade
*/
function sellCompoundOrder(
address _sender,
uint256 _orderId,
uint256 _minPrice,
uint256 _maxPrice
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.sellCompoundOrder.selector,
_sender,
_orderId,
_minPrice,
_maxPrice
)
);
if (!success) {
revert();
}
}
/**
* @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold.
* @param _orderId the ID of the Compound order
* @param _repayAmountInUSDC amount of USDC to use for repaying debt
*/
function repayCompoundOrder(
address _sender,
uint256 _orderId,
uint256 _repayAmountInUSDC
) public {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.repayCompoundOrder.selector,
_sender,
_orderId,
_repayAmountInUSDC
)
);
if (!success) {
revert();
}
}
/**
* @notice Emergency exit the tokens from order contract during intermission stage
* @param _sender the address of trader, who created the order
* @param _orderId the ID of the Compound order
* @param _tokenAddr the address of token which should be transferred
* @param _receiver the address of receiver
*/
function emergencyExitCompoundTokens(
address _sender,
uint256 _orderId,
address _tokenAddr,
address _receiver
) public onlyOwner {
(bool success, ) = peakdefiLogic.delegatecall(
abi.encodeWithSelector(
this.emergencyExitCompoundTokens.selector,
_sender,
_orderId,
_tokenAddr,
_receiver
)
);
if (!success) {
revert();
}
}
/**
* Internal use functions
*/
// MiniMe TokenController functions, not used right now
/**
* @notice Called when `_owner` sends ether to the MiniMe Token contract
* @return True if the ether is accepted, false if it throws
*/
function proxyPayment(
address /*_owner*/
) public payable returns (bool) {
return false;
}
/**
* @notice Notifies the controller about a token transfer allowing the
* controller to react if desired
* @return False if the controller does not authorize the transfer
*/
function onTransfer(
address, /*_from*/
address, /*_to*/
uint256 /*_amount*/
) public returns (bool) {
return true;
}
/**
* @notice Notifies the controller about an approval allowing the
* controller to react if desired
* @return False if the controller does not authorize the approval
*/
function onApprove(
address, /*_owner*/
address, /*_spender*/
uint256 /*_amount*/
) public returns (bool) {
return true;
}
function() external payable {}
/**
PeakDeFi
*/
/**
* @notice Returns the commission balance of `_referrer`
* @return the commission balance and the received penalty, denoted in USDC
*/
function peakReferralCommissionBalanceOf(address _referrer)
public
returns (uint256 _commission)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.peakReferralCommissionBalanceOf.selector,
_referrer
)
);
if (!success) {
return 0;
}
return abi.decode(result, (uint256));
}
/**
* @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle
* @return the commission amount and the received penalty, denoted in USDC
*/
function peakReferralCommissionOfAt(address _referrer, uint256 _cycle)
public
returns (uint256 _commission)
{
(bool success, bytes memory result) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.peakReferralCommissionOfAt.selector,
_referrer,
_cycle
)
);
if (!success) {
return 0;
}
return abi.decode(result, (uint256));
}
/**
* @notice Redeems commission.
*/
function peakReferralRedeemCommission() public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(this.peakReferralRedeemCommission.selector)
);
if (!success) {
revert();
}
}
/**
* @notice Redeems commission for a particular cycle.
* @param _cycle the cycle for which the commission will be redeemed.
* Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber.
*/
function peakReferralRedeemCommissionForCycle(uint256 _cycle) public {
(bool success, ) = peakdefiLogic3.delegatecall(
abi.encodeWithSelector(
this.peakReferralRedeemCommissionForCycle.selector,
_cycle
)
);
if (!success) {
revert();
}
}
/**
* @notice Changes the required PEAK stake of a new manager. Only callable by owner.
* @param _newValue the new value
*/
function peakChangeManagerStakeRequired(uint256 _newValue)
public
onlyOwner
{
peakManagerStakeRequired = _newValue;
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "./lib/ReentrancyGuard.sol";
import "./interfaces/IMiniMeToken.sol";
import "./tokens/minime/TokenController.sol";
import "./Utils.sol";
import "./PeakDeFiProxyInterface.sol";
import "./peak/reward/PeakReward.sol";
import "./peak/staking/PeakStaking.sol";
/**
* @title The storage layout of PeakDeFiFund
* @author Zefram Lou (Zebang Liu)
*/
contract PeakDeFiStorage is Ownable, ReentrancyGuard {
using SafeMath for uint256;
enum CyclePhase {Intermission, Manage}
enum VoteDirection {Empty, For, Against}
enum Subchunk {Propose, Vote}
struct Investment {
address tokenAddress;
uint256 cycleNumber;
uint256 stake;
uint256 tokenAmount;
uint256 buyPrice; // token buy price in 18 decimals in USDC
uint256 sellPrice; // token sell price in 18 decimals in USDC
uint256 buyTime;
uint256 buyCostInUSDC;
bool isSold;
}
// Fund parameters
uint256 public constant COMMISSION_RATE = 15 * (10**16); // The proportion of profits that gets distributed to RepToken holders every cycle.
uint256 public constant ASSET_FEE_RATE = 1 * (10**15); // The proportion of fund balance that gets distributed to RepToken holders every cycle.
uint256 public constant NEXT_PHASE_REWARD = 1 * (10**18); // Amount of RepToken rewarded to the user who calls nextPhase().
uint256 public constant COLLATERAL_RATIO_MODIFIER = 75 * (10**16); // Modifies Compound's collateral ratio, gets 2:1 from 1.5:1 ratio
uint256 public constant MIN_RISK_TIME = 3 days; // Mininum risk taken to get full commissions is 9 days * reptokenBalance
uint256 public constant INACTIVE_THRESHOLD = 2; // Number of inactive cycles after which a manager's RepToken balance can be burned
uint256 public constant ROI_PUNISH_THRESHOLD = 1 * (10**17); // ROI worse than 10% will see punishment in stake
uint256 public constant ROI_BURN_THRESHOLD = 25 * (10**16); // ROI worse than 25% will see their stake all burned
uint256 public constant ROI_PUNISH_SLOPE = 6; // repROI = -(6 * absROI - 0.5)
uint256 public constant ROI_PUNISH_NEG_BIAS = 5 * (10**17); // repROI = -(6 * absROI - 0.5)
uint256 public constant PEAK_COMMISSION_RATE = 20 * (10**16); // The proportion of profits that gets distributed to PeakDeFi referrers every cycle.
// Instance variables
// Checks if the token listing initialization has been completed.
bool public hasInitializedTokenListings;
// Checks if the fund has been initialized
bool public isInitialized;
// Address of the RepToken token contract.
address public controlTokenAddr;
// Address of the share token contract.
address public shareTokenAddr;
// Address of the PeakDeFiProxy contract.
address payable public proxyAddr;
// Address of the CompoundOrderFactory contract.
address public compoundFactoryAddr;
// Address of the PeakDeFiLogic contract.
address public peakdefiLogic;
address public peakdefiLogic2;
address public peakdefiLogic3;
// Address to which the development team funding will be sent.
address payable public devFundingAccount;
// Address of the previous version of PeakDeFiFund.
address payable public previousVersion;
// The number of the current investment cycle.
uint256 public cycleNumber;
// The amount of funds held by the fund.
uint256 public totalFundsInUSDC;
// The total funds at the beginning of the current management phase
uint256 public totalFundsAtManagePhaseStart;
// The start time for the current investment cycle phase, in seconds since Unix epoch.
uint256 public startTimeOfCyclePhase;
// The proportion of PeakDeFi Shares total supply to mint and use for funding the development team. Fixed point decimal.
uint256 public devFundingRate;
// Total amount of commission unclaimed by managers
uint256 public totalCommissionLeft;
// Stores the lengths of each cycle phase in seconds.
uint256[2] public phaseLengths;
// The number of managers onboarded during the current cycle
uint256 public managersOnboardedThisCycle;
// The amount of RepToken tokens a new manager receves
uint256 public newManagerRepToken;
// The max number of new managers that can be onboarded in one cycle
uint256 public maxNewManagersPerCycle;
// The price of RepToken in USDC
uint256 public reptokenPrice;
// The last cycle where a user redeemed all of their remaining commission.
mapping(address => uint256) internal _lastCommissionRedemption;
// Marks whether a manager has redeemed their commission for a certain cycle
mapping(address => mapping(uint256 => bool))
internal _hasRedeemedCommissionForCycle;
// The stake-time measured risk that a manager has taken in a cycle
mapping(address => mapping(uint256 => uint256)) internal _riskTakenInCycle;
// In case a manager joined the fund during the current cycle, set the fallback base stake for risk threshold calculation
mapping(address => uint256) internal _baseRiskStakeFallback;
// List of investments of a manager in the current cycle.
mapping(address => Investment[]) public userInvestments;
// List of short/long orders of a manager in the current cycle.
mapping(address => address payable[]) public userCompoundOrders;
// Total commission to be paid for work done in a certain cycle (will be redeemed in the next cycle's Intermission)
mapping(uint256 => uint256) internal _totalCommissionOfCycle;
// The block number at which the Manage phase ended for a given cycle
mapping(uint256 => uint256) internal _managePhaseEndBlock;
// The last cycle where a manager made an investment
mapping(address => uint256) internal _lastActiveCycle;
// Checks if an address points to a whitelisted Kyber token.
mapping(address => bool) public isKyberToken;
// Checks if an address points to a whitelisted Compound token. Returns false for cUSDC and other stablecoin CompoundTokens.
mapping(address => bool) public isCompoundToken;
// The current cycle phase.
CyclePhase public cyclePhase;
// Upgrade governance related variables
bool public hasFinalizedNextVersion; // Denotes if the address of the next smart contract version has been finalized
address payable public nextVersion; // Address of the next version of PeakDeFiFund.
// Contract instances
IMiniMeToken internal cToken;
IMiniMeToken internal sToken;
PeakDeFiProxyInterface internal proxy;
// PeakDeFi
uint256 public peakReferralTotalCommissionLeft;
uint256 public peakManagerStakeRequired;
mapping(uint256 => uint256) internal _peakReferralTotalCommissionOfCycle;
mapping(address => uint256) internal _peakReferralLastCommissionRedemption;
mapping(address => mapping(uint256 => bool))
internal _peakReferralHasRedeemedCommissionForCycle;
IMiniMeToken public peakReferralToken;
PeakReward public peakReward;
PeakStaking public peakStaking;
bool public isPermissioned;
mapping(address => mapping(uint256 => bool)) public hasUsedSalt;
// Events
event ChangedPhase(
uint256 indexed _cycleNumber,
uint256 indexed _newPhase,
uint256 _timestamp,
uint256 _totalFundsInUSDC
);
event Deposit(
uint256 indexed _cycleNumber,
address indexed _sender,
address _tokenAddress,
uint256 _tokenAmount,
uint256 _usdcAmount,
uint256 _timestamp
);
event Withdraw(
uint256 indexed _cycleNumber,
address indexed _sender,
address _tokenAddress,
uint256 _tokenAmount,
uint256 _usdcAmount,
uint256 _timestamp
);
event CreatedInvestment(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _tokenAddress,
uint256 _stakeInWeis,
uint256 _buyPrice,
uint256 _costUSDCAmount,
uint256 _tokenAmount
);
event SoldInvestment(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _tokenAddress,
uint256 _receivedRepToken,
uint256 _sellPrice,
uint256 _earnedUSDCAmount
);
event CreatedCompoundOrder(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _order,
bool _orderType,
address _tokenAddress,
uint256 _stakeInWeis,
uint256 _costUSDCAmount
);
event SoldCompoundOrder(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _order,
bool _orderType,
address _tokenAddress,
uint256 _receivedRepToken,
uint256 _earnedUSDCAmount
);
event RepaidCompoundOrder(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _id,
address _order,
uint256 _repaidUSDCAmount
);
event CommissionPaid(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _commission
);
event TotalCommissionPaid(
uint256 indexed _cycleNumber,
uint256 _totalCommissionInUSDC
);
event Register(
address indexed _manager,
uint256 _donationInUSDC,
uint256 _reptokenReceived
);
event BurnDeadman(address indexed _manager, uint256 _reptokenBurned);
event DeveloperInitiatedUpgrade(
uint256 indexed _cycleNumber,
address _candidate
);
event FinalizedNextVersion(
uint256 indexed _cycleNumber,
address _nextVersion
);
event PeakReferralCommissionPaid(
uint256 indexed _cycleNumber,
address indexed _sender,
uint256 _commission
);
event PeakReferralTotalCommissionPaid(
uint256 indexed _cycleNumber,
uint256 _totalCommissionInUSDC
);
/*
Helper functions shared by both PeakDeFiLogic & PeakDeFiFund
*/
function lastCommissionRedemption(address _manager)
public
view
returns (uint256)
{
if (_lastCommissionRedemption[_manager] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).lastCommissionRedemption(
_manager
);
}
return _lastCommissionRedemption[_manager];
}
function hasRedeemedCommissionForCycle(address _manager, uint256 _cycle)
public
view
returns (bool)
{
if (_hasRedeemedCommissionForCycle[_manager][_cycle] == false) {
return
previousVersion == address(0)
? false
: PeakDeFiStorage(previousVersion)
.hasRedeemedCommissionForCycle(_manager, _cycle);
}
return _hasRedeemedCommissionForCycle[_manager][_cycle];
}
function riskTakenInCycle(address _manager, uint256 _cycle)
public
view
returns (uint256)
{
if (_riskTakenInCycle[_manager][_cycle] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).riskTakenInCycle(
_manager,
_cycle
);
}
return _riskTakenInCycle[_manager][_cycle];
}
function baseRiskStakeFallback(address _manager)
public
view
returns (uint256)
{
if (_baseRiskStakeFallback[_manager] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).baseRiskStakeFallback(
_manager
);
}
return _baseRiskStakeFallback[_manager];
}
function totalCommissionOfCycle(uint256 _cycle)
public
view
returns (uint256)
{
if (_totalCommissionOfCycle[_cycle] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).totalCommissionOfCycle(
_cycle
);
}
return _totalCommissionOfCycle[_cycle];
}
function managePhaseEndBlock(uint256 _cycle) public view returns (uint256) {
if (_managePhaseEndBlock[_cycle] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).managePhaseEndBlock(
_cycle
);
}
return _managePhaseEndBlock[_cycle];
}
function lastActiveCycle(address _manager) public view returns (uint256) {
if (_lastActiveCycle[_manager] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).lastActiveCycle(_manager);
}
return _lastActiveCycle[_manager];
}
/**
PeakDeFi
*/
function peakReferralLastCommissionRedemption(address _manager)
public
view
returns (uint256)
{
if (_peakReferralLastCommissionRedemption[_manager] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion)
.peakReferralLastCommissionRedemption(_manager);
}
return _peakReferralLastCommissionRedemption[_manager];
}
function peakReferralHasRedeemedCommissionForCycle(
address _manager,
uint256 _cycle
) public view returns (bool) {
if (
_peakReferralHasRedeemedCommissionForCycle[_manager][_cycle] ==
false
) {
return
previousVersion == address(0)
? false
: PeakDeFiStorage(previousVersion)
.peakReferralHasRedeemedCommissionForCycle(
_manager,
_cycle
);
}
return _peakReferralHasRedeemedCommissionForCycle[_manager][_cycle];
}
function peakReferralTotalCommissionOfCycle(uint256 _cycle)
public
view
returns (uint256)
{
if (_peakReferralTotalCommissionOfCycle[_cycle] == 0) {
return
previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion)
.peakReferralTotalCommissionOfCycle(_cycle);
}
return _peakReferralTotalCommissionOfCycle[_cycle];
}
}
pragma solidity 0.5.17;
interface PeakDeFiProxyInterface {
function peakdefiFundAddress() external view returns (address payable);
function updatePeakDeFiFundAddress() external;
}
pragma solidity 0.5.17;
import "./PeakDeFiFund.sol";
contract PeakDeFiProxy {
address payable public peakdefiFundAddress;
event UpdatedFundAddress(address payable _newFundAddr);
constructor(address payable _fundAddr) public {
peakdefiFundAddress = _fundAddr;
emit UpdatedFundAddress(_fundAddr);
}
function updatePeakDeFiFundAddress() public {
require(msg.sender == peakdefiFundAddress, "Sender not PeakDeFiFund");
address payable nextVersion = PeakDeFiFund(peakdefiFundAddress)
.nextVersion();
require(nextVersion != address(0), "Next version can't be empty");
peakdefiFundAddress = nextVersion;
emit UpdatedFundAddress(peakdefiFundAddress);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/cryptography/ECDSA.sol";
import "./PeakDeFiStorage.sol";
import "./derivatives/CompoundOrderFactory.sol";
/**
* @title Part of the functions for PeakDeFiFund
* @author Zefram Lou (Zebang Liu)
*/
contract PeakDeFiLogic is
PeakDeFiStorage,
Utils(address(0), address(0), address(0))
{
/**
* @notice Executes function only during the given cycle phase.
* @param phase the cycle phase during which the function may be called
*/
modifier during(CyclePhase phase) {
require(cyclePhase == phase);
if (cyclePhase == CyclePhase.Intermission) {
require(isInitialized);
}
_;
}
/**
* @notice Returns the length of the user's investments array.
* @return length of the user's investments array
*/
function investmentsCount(address _userAddr)
public
view
returns (uint256 _count)
{
return userInvestments[_userAddr].length;
}
/**
* @notice Burns the RepToken balance of a manager who has been inactive for a certain number of cycles
* @param _deadman the manager whose RepToken balance will be burned
*/
function burnDeadman(address _deadman)
public
nonReentrant
during(CyclePhase.Intermission)
{
require(_deadman != address(this));
require(
cycleNumber.sub(lastActiveCycle(_deadman)) > INACTIVE_THRESHOLD
);
uint256 balance = cToken.balanceOf(_deadman);
require(cToken.destroyTokens(_deadman, balance));
emit BurnDeadman(_deadman, balance);
}
/**
* @notice Creates a new investment for an ERC20 token. Backwards compatible.
* @param _tokenAddress address of the ERC20 token contract
* @param _stake amount of RepTokens to be staked in support of the investment
* @param _maxPrice the maximum price for the trade
*/
function createInvestment(
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice
) public {
bytes memory nil;
createInvestmentV2(
msg.sender,
_tokenAddress,
_stake,
_maxPrice,
nil,
true
);
}
function createInvestmentWithSignature(
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice,
bytes calldata _calldata,
bool _useKyber,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.createInvestmentWithSignature.selector,
abi.encode(
_tokenAddress,
_stake,
_maxPrice,
_calldata,
_useKyber
),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.createInvestmentV2(
_manager,
_tokenAddress,
_stake,
_maxPrice,
_calldata,
_useKyber
);
}
/**
* @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user.
* The user can sell only part of the investment by changing _tokenAmount. Backwards compatible.
* @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with
* the original buy price and however much tokens that are not sold.
* @param _investmentId the ID of the investment
* @param _tokenAmount the amount of tokens to be sold.
* @param _minPrice the minimum price for the trade
*/
function sellInvestmentAsset(
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice
) public {
bytes memory nil;
sellInvestmentAssetV2(
msg.sender,
_investmentId,
_tokenAmount,
_minPrice,
nil,
true
);
}
function sellInvestmentWithSignature(
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice,
bytes calldata _calldata,
bool _useKyber,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.sellInvestmentWithSignature.selector,
abi.encode(
_investmentId,
_tokenAmount,
_minPrice,
_calldata,
_useKyber
),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.sellInvestmentAssetV2(
_manager,
_investmentId,
_tokenAmount,
_minPrice,
_calldata,
_useKyber
);
}
/**
* @notice Creates a new investment for an ERC20 token.
* @param _tokenAddress address of the ERC20 token contract
* @param _stake amount of RepTokens to be staked in support of the investment
* @param _maxPrice the maximum price for the trade
* @param _calldata calldata for 1inch trading
* @param _useKyber true for Kyber Network, false for 1inch
*/
function createInvestmentV2(
address _sender,
address _tokenAddress,
uint256 _stake,
uint256 _maxPrice,
bytes memory _calldata,
bool _useKyber
)
public
during(CyclePhase.Manage)
nonReentrant
isValidToken(_tokenAddress)
{
require(msg.sender == _sender || msg.sender == address(this));
require(_stake > 0);
require(isKyberToken[_tokenAddress]);
// Verify user peak stake
uint256 peakStake = peakStaking.userStakeAmount(_sender);
require(peakStake >= peakManagerStakeRequired);
// Collect stake
require(cToken.generateTokens(address(this), _stake));
require(cToken.destroyTokens(_sender, _stake));
// Add investment to list
userInvestments[_sender].push(
Investment({
tokenAddress: _tokenAddress,
cycleNumber: cycleNumber,
stake: _stake,
tokenAmount: 0,
buyPrice: 0,
sellPrice: 0,
buyTime: now,
buyCostInUSDC: 0,
isSold: false
})
);
// Invest
uint256 investmentId = investmentsCount(_sender).sub(1);
__handleInvestment(
_sender,
investmentId,
0,
_maxPrice,
true,
_calldata,
_useKyber
);
// Update last active cycle
_lastActiveCycle[_sender] = cycleNumber;
// Emit event
__emitCreatedInvestmentEvent(_sender, investmentId);
}
/**
* @notice Called by user to sell the assets an investment invested in. Returns the staked RepToken plus rewards/penalties to the user.
* The user can sell only part of the investment by changing _tokenAmount.
* @dev When selling only part of an investment, the old investment would be "fully" sold and a new investment would be created with
* the original buy price and however much tokens that are not sold.
* @param _investmentId the ID of the investment
* @param _tokenAmount the amount of tokens to be sold.
* @param _minPrice the minimum price for the trade
*/
function sellInvestmentAssetV2(
address _sender,
uint256 _investmentId,
uint256 _tokenAmount,
uint256 _minPrice,
bytes memory _calldata,
bool _useKyber
) public nonReentrant during(CyclePhase.Manage) {
require(msg.sender == _sender || msg.sender == address(this));
Investment storage investment = userInvestments[_sender][_investmentId];
require(
investment.buyPrice > 0 &&
investment.cycleNumber == cycleNumber &&
!investment.isSold
);
require(_tokenAmount > 0 && _tokenAmount <= investment.tokenAmount);
// Create new investment for leftover tokens
bool isPartialSell = false;
uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div(
investment.tokenAmount
);
if (_tokenAmount != investment.tokenAmount) {
isPartialSell = true;
__createInvestmentForLeftovers(
_sender,
_investmentId,
_tokenAmount
);
__emitCreatedInvestmentEvent(
_sender,
investmentsCount(_sender).sub(1)
);
}
// Update investment info
investment.isSold = true;
// Sell asset
(
uint256 actualDestAmount,
uint256 actualSrcAmount
) = __handleInvestment(
_sender,
_investmentId,
_minPrice,
uint256(-1),
false,
_calldata,
_useKyber
);
__sellInvestmentUpdate(
_sender,
_investmentId,
stakeOfSoldTokens,
actualDestAmount
);
}
function __sellInvestmentUpdate(
address _sender,
uint256 _investmentId,
uint256 stakeOfSoldTokens,
uint256 actualDestAmount
) internal {
Investment storage investment = userInvestments[_sender][_investmentId];
// Return staked RepToken
uint256 receiveRepTokenAmount = getReceiveRepTokenAmount(
stakeOfSoldTokens,
investment.sellPrice,
investment.buyPrice
);
__returnStake(receiveRepTokenAmount, stakeOfSoldTokens);
// Record risk taken in investment
__recordRisk(_sender, investment.stake, investment.buyTime);
// Update total funds
totalFundsInUSDC = totalFundsInUSDC.sub(investment.buyCostInUSDC).add(
actualDestAmount
);
// Emit event
__emitSoldInvestmentEvent(
_sender,
_investmentId,
receiveRepTokenAmount,
actualDestAmount
);
}
function __emitSoldInvestmentEvent(
address _sender,
uint256 _investmentId,
uint256 _receiveRepTokenAmount,
uint256 _actualDestAmount
) internal {
Investment storage investment = userInvestments[_sender][_investmentId];
emit SoldInvestment(
cycleNumber,
_sender,
_investmentId,
investment.tokenAddress,
_receiveRepTokenAmount,
investment.sellPrice,
_actualDestAmount
);
}
function __createInvestmentForLeftovers(
address _sender,
uint256 _investmentId,
uint256 _tokenAmount
) internal {
Investment storage investment = userInvestments[_sender][_investmentId];
uint256 stakeOfSoldTokens = investment.stake.mul(_tokenAmount).div(
investment.tokenAmount
);
// calculate the part of original USDC cost attributed to the sold tokens
uint256 soldBuyCostInUSDC = investment
.buyCostInUSDC
.mul(_tokenAmount)
.div(investment.tokenAmount);
userInvestments[_sender].push(
Investment({
tokenAddress: investment.tokenAddress,
cycleNumber: cycleNumber,
stake: investment.stake.sub(stakeOfSoldTokens),
tokenAmount: investment.tokenAmount.sub(_tokenAmount),
buyPrice: investment.buyPrice,
sellPrice: 0,
buyTime: investment.buyTime,
buyCostInUSDC: investment.buyCostInUSDC.sub(soldBuyCostInUSDC),
isSold: false
})
);
// update the investment object being sold
investment.tokenAmount = _tokenAmount;
investment.stake = stakeOfSoldTokens;
investment.buyCostInUSDC = soldBuyCostInUSDC;
}
function __emitCreatedInvestmentEvent(address _sender, uint256 _id)
internal
{
Investment storage investment = userInvestments[_sender][_id];
emit CreatedInvestment(
cycleNumber,
_sender,
_id,
investment.tokenAddress,
investment.stake,
investment.buyPrice,
investment.buyCostInUSDC,
investment.tokenAmount
);
}
function createCompoundOrderWithSignature(
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 _minPrice,
uint256 _maxPrice,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.createCompoundOrderWithSignature.selector,
abi.encode(
_orderType,
_tokenAddress,
_stake,
_minPrice,
_maxPrice
),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.createCompoundOrder(
_manager,
_orderType,
_tokenAddress,
_stake,
_minPrice,
_maxPrice
);
}
function sellCompoundOrderWithSignature(
uint256 _orderId,
uint256 _minPrice,
uint256 _maxPrice,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.sellCompoundOrderWithSignature.selector,
abi.encode(_orderId, _minPrice, _maxPrice),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.sellCompoundOrder(_manager, _orderId, _minPrice, _maxPrice);
}
function repayCompoundOrderWithSignature(
uint256 _orderId,
uint256 _repayAmountInUSDC,
address _manager,
uint256 _salt,
bytes calldata _signature
) external {
require(!hasUsedSalt[_manager][_salt]);
bytes32 naiveHash = keccak256(
abi.encodeWithSelector(
this.repayCompoundOrderWithSignature.selector,
abi.encode(_orderId, _repayAmountInUSDC),
"|END|",
_salt,
address(this)
)
);
bytes32 msgHash = ECDSA.toEthSignedMessageHash(naiveHash);
address recoveredAddress = ECDSA.recover(msgHash, _signature);
require(recoveredAddress == _manager);
// Signature valid, record use of salt
hasUsedSalt[_manager][_salt] = true;
this.repayCompoundOrder(_manager, _orderId, _repayAmountInUSDC);
}
/**
* @notice Creates a new Compound order to either short or leverage long a token.
* @param _orderType true for a short order, false for a levarage long order
* @param _tokenAddress address of the Compound token to be traded
* @param _stake amount of RepTokens to be staked
* @param _minPrice the minimum token price for the trade
* @param _maxPrice the maximum token price for the trade
*/
function createCompoundOrder(
address _sender,
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 _minPrice,
uint256 _maxPrice
)
public
during(CyclePhase.Manage)
nonReentrant
isValidToken(_tokenAddress)
{
require(msg.sender == _sender || msg.sender == address(this));
require(_minPrice <= _maxPrice);
require(_stake > 0);
require(isCompoundToken[_tokenAddress]);
// Verify user peak stake
uint256 peakStake = peakStaking.userStakeAmount(_sender);
require(peakStake >= peakManagerStakeRequired);
// Collect stake
require(cToken.generateTokens(address(this), _stake));
require(cToken.destroyTokens(_sender, _stake));
// Create compound order and execute
uint256 collateralAmountInUSDC = totalFundsInUSDC.mul(_stake).div(
cToken.totalSupply()
);
CompoundOrder order = __createCompoundOrder(
_orderType,
_tokenAddress,
_stake,
collateralAmountInUSDC
);
usdc.safeApprove(address(order), 0);
usdc.safeApprove(address(order), collateralAmountInUSDC);
order.executeOrder(_minPrice, _maxPrice);
// Add order to list
userCompoundOrders[_sender].push(address(order));
// Update last active cycle
_lastActiveCycle[_sender] = cycleNumber;
__emitCreatedCompoundOrderEvent(
_sender,
address(order),
_orderType,
_tokenAddress,
_stake,
collateralAmountInUSDC
);
}
function __emitCreatedCompoundOrderEvent(
address _sender,
address order,
bool _orderType,
address _tokenAddress,
uint256 _stake,
uint256 collateralAmountInUSDC
) internal {
// Emit event
emit CreatedCompoundOrder(
cycleNumber,
_sender,
userCompoundOrders[_sender].length - 1,
address(order),
_orderType,
_tokenAddress,
_stake,
collateralAmountInUSDC
);
}
/**
* @notice Sells a compound order
* @param _orderId the ID of the order to be sold (index in userCompoundOrders[msg.sender])
* @param _minPrice the minimum token price for the trade
* @param _maxPrice the maximum token price for the trade
*/
function sellCompoundOrder(
address _sender,
uint256 _orderId,
uint256 _minPrice,
uint256 _maxPrice
) public during(CyclePhase.Manage) nonReentrant {
require(msg.sender == _sender || msg.sender == address(this));
// Load order info
require(userCompoundOrders[_sender][_orderId] != address(0));
CompoundOrder order = CompoundOrder(
userCompoundOrders[_sender][_orderId]
);
require(order.isSold() == false && order.cycleNumber() == cycleNumber);
// Sell order
(uint256 inputAmount, uint256 outputAmount) = order.sellOrder(
_minPrice,
_maxPrice
);
// Return staked RepToken
uint256 stake = order.stake();
uint256 receiveRepTokenAmount = getReceiveRepTokenAmount(
stake,
outputAmount,
inputAmount
);
__returnStake(receiveRepTokenAmount, stake);
// Record risk taken
__recordRisk(_sender, stake, order.buyTime());
// Update total funds
totalFundsInUSDC = totalFundsInUSDC.sub(inputAmount).add(outputAmount);
// Emit event
emit SoldCompoundOrder(
cycleNumber,
_sender,
userCompoundOrders[_sender].length - 1,
address(order),
order.orderType(),
order.compoundTokenAddr(),
receiveRepTokenAmount,
outputAmount
);
}
/**
* @notice Repys debt for a Compound order to prevent the collateral ratio from dropping below threshold.
* @param _orderId the ID of the Compound order
* @param _repayAmountInUSDC amount of USDC to use for repaying debt
*/
function repayCompoundOrder(
address _sender,
uint256 _orderId,
uint256 _repayAmountInUSDC
) public during(CyclePhase.Manage) nonReentrant {
require(msg.sender == _sender || msg.sender == address(this));
// Load order info
require(userCompoundOrders[_sender][_orderId] != address(0));
CompoundOrder order = CompoundOrder(
userCompoundOrders[_sender][_orderId]
);
require(order.isSold() == false && order.cycleNumber() == cycleNumber);
// Repay loan
order.repayLoan(_repayAmountInUSDC);
// Emit event
emit RepaidCompoundOrder(
cycleNumber,
_sender,
userCompoundOrders[_sender].length - 1,
address(order),
_repayAmountInUSDC
);
}
function emergencyExitCompoundTokens(
address _sender,
uint256 _orderId,
address _tokenAddr,
address _receiver
) public during(CyclePhase.Intermission) nonReentrant {
CompoundOrder order = CompoundOrder(userCompoundOrders[_sender][_orderId]);
order.emergencyExitTokens(_tokenAddr, _receiver);
}
function getReceiveRepTokenAmount(
uint256 stake,
uint256 output,
uint256 input
) public pure returns (uint256 _amount) {
if (output >= input) {
// positive ROI, simply return stake * (1 + ROI)
return stake.mul(output).div(input);
} else {
// negative ROI
uint256 absROI = input.sub(output).mul(PRECISION).div(input);
if (absROI <= ROI_PUNISH_THRESHOLD) {
// ROI better than -10%, no punishment
return stake.mul(output).div(input);
} else if (
absROI > ROI_PUNISH_THRESHOLD && absROI < ROI_BURN_THRESHOLD
) {
// ROI between -10% and -25%, punish
// return stake * (1 + roiWithPunishment) = stake * (1 + (-(6 * absROI - 0.5)))
return
stake
.mul(
PRECISION.sub(
ROI_PUNISH_SLOPE.mul(absROI).sub(
ROI_PUNISH_NEG_BIAS
)
)
)
.div(PRECISION);
} else {
// ROI greater than 25%, burn all stake
return 0;
}
}
}
/**
* @notice Handles and investment by doing the necessary trades using __kyberTrade() or Fulcrum trading
* @param _investmentId the ID of the investment to be handled
* @param _minPrice the minimum price for the trade
* @param _maxPrice the maximum price for the trade
* @param _buy whether to buy or sell the given investment
* @param _calldata calldata for 1inch trading
* @param _useKyber true for Kyber Network, false for 1inch
*/
function __handleInvestment(
address _sender,
uint256 _investmentId,
uint256 _minPrice,
uint256 _maxPrice,
bool _buy,
bytes memory _calldata,
bool _useKyber
) internal returns (uint256 _actualDestAmount, uint256 _actualSrcAmount) {
Investment storage investment = userInvestments[_sender][_investmentId];
address token = investment.tokenAddress;
// Basic trading
uint256 dInS; // price of dest token denominated in src token
uint256 sInD; // price of src token denominated in dest token
if (_buy) {
if (_useKyber) {
(
dInS,
sInD,
_actualDestAmount,
_actualSrcAmount
) = __kyberTrade(
usdc,
totalFundsInUSDC.mul(investment.stake).div(
cToken.totalSupply()
),
ERC20Detailed(token)
);
} else {
// 1inch trading
(
dInS,
sInD,
_actualDestAmount,
_actualSrcAmount
) = __oneInchTrade(
usdc,
totalFundsInUSDC.mul(investment.stake).div(
cToken.totalSupply()
),
ERC20Detailed(token),
_calldata
);
}
require(_minPrice <= dInS && dInS <= _maxPrice);
investment.buyPrice = dInS;
investment.tokenAmount = _actualDestAmount;
investment.buyCostInUSDC = _actualSrcAmount;
} else {
if (_useKyber) {
(
dInS,
sInD,
_actualDestAmount,
_actualSrcAmount
) = __kyberTrade(
ERC20Detailed(token),
investment.tokenAmount,
usdc
);
} else {
(
dInS,
sInD,
_actualDestAmount,
_actualSrcAmount
) = __oneInchTrade(
ERC20Detailed(token),
investment.tokenAmount,
usdc,
_calldata
);
}
require(_minPrice <= sInD && sInD <= _maxPrice);
investment.sellPrice = sInD;
}
}
/**
* @notice Separated from createCompoundOrder() to avoid stack too deep error
*/
function __createCompoundOrder(
bool _orderType, // True for shorting, false for longing
address _tokenAddress,
uint256 _stake,
uint256 _collateralAmountInUSDC
) internal returns (CompoundOrder) {
CompoundOrderFactory factory = CompoundOrderFactory(
compoundFactoryAddr
);
uint256 loanAmountInUSDC = _collateralAmountInUSDC
.mul(COLLATERAL_RATIO_MODIFIER)
.div(PRECISION)
.mul(factory.getMarketCollateralFactor(_tokenAddress))
.div(PRECISION);
CompoundOrder order = factory.createOrder(
_tokenAddress,
cycleNumber,
_stake,
_collateralAmountInUSDC,
loanAmountInUSDC,
_orderType
);
return order;
}
/**
* @notice Returns stake to manager after investment is sold, including reward/penalty based on performance
*/
function __returnStake(uint256 _receiveRepTokenAmount, uint256 _stake)
internal
{
require(cToken.destroyTokens(address(this), _stake));
require(cToken.generateTokens(msg.sender, _receiveRepTokenAmount));
}
/**
* @notice Records risk taken in a trade based on stake and time of investment
*/
function __recordRisk(
address _sender,
uint256 _stake,
uint256 _buyTime
) internal {
_riskTakenInCycle[_sender][cycleNumber] = riskTakenInCycle(
_sender,
cycleNumber
)
.add(_stake.mul(now.sub(_buyTime)));
}
}
pragma solidity ^0.5.0;
/**
* @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations.
*
* These functions can be used to verify that a message was signed by the holder
* of the private keys of a given address.
*/
library ECDSA {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* NOTE: This call _does not revert_ if the signature is invalid, or
* if the signer is otherwise unable to be retrieved. In those scenarios,
* the zero address is returned.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
return (address(0));
}
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// ecrecover takes the signature parameters, and the only way to get them
// currently is to use assembly.
// solhint-disable-next-line no-inline-assembly
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := byte(0, mload(add(signature, 0x60)))
}
// EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature
// unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines
// the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most
// signatures from current libraries generate a unique signature with an s-value in the lower half order.
//
// If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value
// with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or
// vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept
// these malleable signatures as well.
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v != 27 && v != 28) {
return address(0);
}
// If the signature is valid (and not malleable), return the signer address
return ecrecover(hash, v, r, s);
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
pragma solidity 0.5.17;
import "./PeakDeFiStorage.sol";
import "./derivatives/CompoundOrderFactory.sol";
import "@nomiclabs/buidler/console.sol";
/**
* @title Part of the functions for PeakDeFiFund
* @author Zefram Lou (Zebang Liu)
*/
contract PeakDeFiLogic2 is
PeakDeFiStorage,
Utils(address(0), address(0), address(0))
{
/**
* @notice Passes if the fund has not finalized the next smart contract to upgrade to
*/
modifier notReadyForUpgrade {
require(hasFinalizedNextVersion == false);
_;
}
/**
* @notice Executes function only during the given cycle phase.
* @param phase the cycle phase during which the function may be called
*/
modifier during(CyclePhase phase) {
require(cyclePhase == phase);
if (cyclePhase == CyclePhase.Intermission) {
require(isInitialized);
}
_;
}
/**
* Deposit & Withdraw
*/
function depositEther(address _referrer) public payable {
bytes memory nil;
depositEtherAdvanced(true, nil, _referrer);
}
/**
* @notice Deposit Ether into the fund. Ether will be converted into USDC.
* @param _useKyber true for Kyber Network, false for 1inch
* @param _calldata calldata for 1inch trading
* @param _referrer the referrer's address
*/
function depositEtherAdvanced(
bool _useKyber,
bytes memory _calldata,
address _referrer
) public payable nonReentrant notReadyForUpgrade {
// Buy USDC with ETH
uint256 actualUSDCDeposited;
uint256 actualETHDeposited;
if (_useKyber) {
(, , actualUSDCDeposited, actualETHDeposited) = __kyberTrade(
ETH_TOKEN_ADDRESS,
msg.value,
usdc
);
} else {
(, , actualUSDCDeposited, actualETHDeposited) = __oneInchTrade(
ETH_TOKEN_ADDRESS,
msg.value,
usdc,
_calldata
);
}
// Send back leftover ETH
uint256 leftOverETH = msg.value.sub(actualETHDeposited);
if (leftOverETH > 0) {
msg.sender.transfer(leftOverETH);
}
// Register investment
__deposit(actualUSDCDeposited, _referrer);
// Emit event
emit Deposit(
cycleNumber,
msg.sender,
address(ETH_TOKEN_ADDRESS),
actualETHDeposited,
actualUSDCDeposited,
now
);
}
/**
* @notice Deposit USDC Stablecoin into the fund.
* @param _usdcAmount The amount of USDC to be deposited. May be different from actual deposited amount.
* @param _referrer the referrer's address
*/
function depositUSDC(uint256 _usdcAmount, address _referrer)
public
nonReentrant
notReadyForUpgrade
{
usdc.safeTransferFrom(msg.sender, address(this), _usdcAmount);
// Register investment
__deposit(_usdcAmount, _referrer);
// Emit event
emit Deposit(
cycleNumber,
msg.sender,
USDC_ADDR,
_usdcAmount,
_usdcAmount,
now
);
}
function depositToken(
address _tokenAddr,
uint256 _tokenAmount,
address _referrer
) public {
bytes memory nil;
depositTokenAdvanced(_tokenAddr, _tokenAmount, true, nil, _referrer);
}
/**
* @notice Deposit ERC20 tokens into the fund. Tokens will be converted into USDC.
* @param _tokenAddr the address of the token to be deposited
* @param _tokenAmount The amount of tokens to be deposited. May be different from actual deposited amount.
* @param _useKyber true for Kyber Network, false for 1inch
* @param _calldata calldata for 1inch trading
* @param _referrer the referrer's address
*/
function depositTokenAdvanced(
address _tokenAddr,
uint256 _tokenAmount,
bool _useKyber,
bytes memory _calldata,
address _referrer
) public nonReentrant notReadyForUpgrade isValidToken(_tokenAddr) {
require(
_tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS)
);
ERC20Detailed token = ERC20Detailed(_tokenAddr);
token.safeTransferFrom(msg.sender, address(this), _tokenAmount);
// Convert token into USDC
uint256 actualUSDCDeposited;
uint256 actualTokenDeposited;
if (_useKyber) {
(, , actualUSDCDeposited, actualTokenDeposited) = __kyberTrade(
token,
_tokenAmount,
usdc
);
} else {
(, , actualUSDCDeposited, actualTokenDeposited) = __oneInchTrade(
token,
_tokenAmount,
usdc,
_calldata
);
}
// Give back leftover tokens
uint256 leftOverTokens = _tokenAmount.sub(actualTokenDeposited);
if (leftOverTokens > 0) {
token.safeTransfer(msg.sender, leftOverTokens);
}
// Register investment
__deposit(actualUSDCDeposited, _referrer);
// Emit event
emit Deposit(
cycleNumber,
msg.sender,
_tokenAddr,
actualTokenDeposited,
actualUSDCDeposited,
now
);
}
function withdrawEther(uint256 _amountInUSDC) external {
bytes memory nil;
withdrawEtherAdvanced(_amountInUSDC, true, nil);
}
/**
* @notice Withdraws Ether by burning Shares.
* @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
* @param _useKyber true for Kyber Network, false for 1inch
* @param _calldata calldata for 1inch trading
*/
function withdrawEtherAdvanced(
uint256 _amountInUSDC,
bool _useKyber,
bytes memory _calldata
) public nonReentrant during(CyclePhase.Intermission) {
// Buy ETH
uint256 actualETHWithdrawn;
uint256 actualUSDCWithdrawn;
if (_useKyber) {
(, , actualETHWithdrawn, actualUSDCWithdrawn) = __kyberTrade(
usdc,
_amountInUSDC,
ETH_TOKEN_ADDRESS
);
} else {
(, , actualETHWithdrawn, actualUSDCWithdrawn) = __oneInchTrade(
usdc,
_amountInUSDC,
ETH_TOKEN_ADDRESS,
_calldata
);
}
__withdraw(actualUSDCWithdrawn);
// Transfer Ether to user
msg.sender.transfer(actualETHWithdrawn);
// Emit event
emit Withdraw(
cycleNumber,
msg.sender,
address(ETH_TOKEN_ADDRESS),
actualETHWithdrawn,
actualUSDCWithdrawn,
now
);
}
/**
* @notice Withdraws Ether by burning Shares.
* @param _amountInUSDC Amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
*/
function withdrawUSDC(uint256 _amountInUSDC)
external
nonReentrant
during(CyclePhase.Intermission)
{
__withdraw(_amountInUSDC);
// Transfer USDC to user
usdc.safeTransfer(msg.sender, _amountInUSDC);
// Emit event
emit Withdraw(
cycleNumber,
msg.sender,
USDC_ADDR,
_amountInUSDC,
_amountInUSDC,
now
);
}
function withdrawToken(address _tokenAddr, uint256 _amountInUSDC) external {
bytes memory nil;
withdrawTokenAdvanced(_tokenAddr, _amountInUSDC, true, nil);
}
/**
* @notice Withdraws funds by burning Shares, and converts the funds into the specified token using Kyber Network.
* @param _tokenAddr the address of the token to be withdrawn into the caller's account
* @param _amountInUSDC The amount of funds to be withdrawn expressed in USDC. Fixed-point decimal. May be different from actual amount.
* @param _useKyber true for Kyber Network, false for 1inch
* @param _calldata calldata for 1inch trading
*/
function withdrawTokenAdvanced(
address _tokenAddr,
uint256 _amountInUSDC,
bool _useKyber,
bytes memory _calldata
)
public
during(CyclePhase.Intermission)
nonReentrant
isValidToken(_tokenAddr)
{
require(
_tokenAddr != USDC_ADDR && _tokenAddr != address(ETH_TOKEN_ADDRESS)
);
ERC20Detailed token = ERC20Detailed(_tokenAddr);
// Convert USDC into desired tokens
uint256 actualTokenWithdrawn;
uint256 actualUSDCWithdrawn;
if (_useKyber) {
(, , actualTokenWithdrawn, actualUSDCWithdrawn) = __kyberTrade(
usdc,
_amountInUSDC,
token
);
} else {
(, , actualTokenWithdrawn, actualUSDCWithdrawn) = __oneInchTrade(
usdc,
_amountInUSDC,
token,
_calldata
);
}
__withdraw(actualUSDCWithdrawn);
// Transfer tokens to user
token.safeTransfer(msg.sender, actualTokenWithdrawn);
// Emit event
emit Withdraw(
cycleNumber,
msg.sender,
_tokenAddr,
actualTokenWithdrawn,
actualUSDCWithdrawn,
now
);
}
/**
* Manager registration
*/
/**
* @notice Registers `msg.sender` as a manager, using USDC as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
*/
function registerWithUSDC()
public
during(CyclePhase.Intermission)
nonReentrant
{
require(!isPermissioned);
require(managersOnboardedThisCycle < maxNewManagersPerCycle);
managersOnboardedThisCycle = managersOnboardedThisCycle.add(1);
uint256 peakStake = peakStaking.userStakeAmount(msg.sender);
require(peakStake >= peakManagerStakeRequired);
uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION);
usdc.safeTransferFrom(msg.sender, address(this), donationInUSDC);
__register(donationInUSDC);
}
/**
* @notice Registers `msg.sender` as a manager, using ETH as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
*/
function registerWithETH()
public
payable
during(CyclePhase.Intermission)
nonReentrant
{
require(!isPermissioned);
require(managersOnboardedThisCycle < maxNewManagersPerCycle);
managersOnboardedThisCycle = managersOnboardedThisCycle.add(1);
uint256 peakStake = peakStaking.userStakeAmount(msg.sender);
require(peakStake >= peakManagerStakeRequired);
uint256 receivedUSDC;
// trade ETH for USDC
(, , receivedUSDC, ) = __kyberTrade(ETH_TOKEN_ADDRESS, msg.value, usdc);
// if USDC value is greater than the amount required, return excess USDC to msg.sender
uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION);
if (receivedUSDC > donationInUSDC) {
usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC));
receivedUSDC = donationInUSDC;
}
// register new manager
__register(receivedUSDC);
}
/**
* @notice Registers `msg.sender` as a manager, using tokens as payment. The more one pays, the more RepToken one gets.
* There's a max RepToken amount that can be bought, and excess payment will be sent back to sender.
* @param _token the token to be used for payment
* @param _donationInTokens the amount of tokens to be used for registration, should use the token's native decimals
*/
function registerWithToken(address _token, uint256 _donationInTokens)
public
during(CyclePhase.Intermission)
nonReentrant
{
require(!isPermissioned);
require(managersOnboardedThisCycle < maxNewManagersPerCycle);
managersOnboardedThisCycle = managersOnboardedThisCycle.add(1);
uint256 peakStake = peakStaking.userStakeAmount(msg.sender);
require(peakStake >= peakManagerStakeRequired);
require(
_token != address(0) &&
_token != address(ETH_TOKEN_ADDRESS) &&
_token != USDC_ADDR
);
ERC20Detailed token = ERC20Detailed(_token);
require(token.totalSupply() > 0);
token.safeTransferFrom(msg.sender, address(this), _donationInTokens);
uint256 receivedUSDC;
(, , receivedUSDC, ) = __kyberTrade(token, _donationInTokens, usdc);
// if USDC value is greater than the amount required, return excess USDC to msg.sender
uint256 donationInUSDC = newManagerRepToken.mul(reptokenPrice).div(PRECISION);
if (receivedUSDC > donationInUSDC) {
usdc.safeTransfer(msg.sender, receivedUSDC.sub(donationInUSDC));
receivedUSDC = donationInUSDC;
}
// register new manager
__register(receivedUSDC);
}
function peakAdminRegisterManager(address _manager, uint256 _reptokenAmount)
public
during(CyclePhase.Intermission)
nonReentrant
onlyOwner
{
require(isPermissioned);
// mint REP for msg.sender
require(cToken.generateTokens(_manager, _reptokenAmount));
// Set risk fallback base stake
_baseRiskStakeFallback[_manager] = _baseRiskStakeFallback[_manager].add(
_reptokenAmount
);
// Set last active cycle for msg.sender to be the current cycle
_lastActiveCycle[_manager] = cycleNumber;
// emit events
emit Register(_manager, 0, _reptokenAmount);
}
/**
* @notice Sells tokens left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer.
* @param _tokenAddr address of the token to be sold
* @param _calldata the 1inch trade call data
*/
function sellLeftoverToken(address _tokenAddr, bytes calldata _calldata)
external
during(CyclePhase.Intermission)
nonReentrant
isValidToken(_tokenAddr)
{
ERC20Detailed token = ERC20Detailed(_tokenAddr);
(, , uint256 actualUSDCReceived, ) = __oneInchTrade(
token,
getBalance(token, address(this)),
usdc,
_calldata
);
totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived);
}
/**
* @notice Sells CompoundOrder left over due to manager not selling or KyberNetwork not having enough volume. Callable by anyone. Money goes to developer.
* @param _orderAddress address of the CompoundOrder to be sold
*/
function sellLeftoverCompoundOrder(address payable _orderAddress)
public
during(CyclePhase.Intermission)
nonReentrant
{
// Load order info
require(_orderAddress != address(0));
CompoundOrder order = CompoundOrder(_orderAddress);
require(order.isSold() == false && order.cycleNumber() < cycleNumber);
// Sell short order
// Not using outputAmount returned by order.sellOrder() because _orderAddress could point to a malicious contract
uint256 beforeUSDCBalance = usdc.balanceOf(address(this));
order.sellOrder(0, MAX_QTY);
uint256 actualUSDCReceived = usdc.balanceOf(address(this)).sub(
beforeUSDCBalance
);
totalFundsInUSDC = totalFundsInUSDC.add(actualUSDCReceived);
}
/**
* @notice Registers `msg.sender` as a manager.
* @param _donationInUSDC the amount of USDC to be used for registration
*/
function __register(uint256 _donationInUSDC) internal {
require(
cToken.balanceOf(msg.sender) == 0 &&
userInvestments[msg.sender].length == 0 &&
userCompoundOrders[msg.sender].length == 0
); // each address can only join once
// mint REP for msg.sender
uint256 repAmount = _donationInUSDC.mul(PRECISION).div(reptokenPrice);
require(cToken.generateTokens(msg.sender, repAmount));
// Set risk fallback base stake
_baseRiskStakeFallback[msg.sender] = repAmount;
// Set last active cycle for msg.sender to be the current cycle
_lastActiveCycle[msg.sender] = cycleNumber;
// keep USDC in the fund
totalFundsInUSDC = totalFundsInUSDC.add(_donationInUSDC);
// emit events
emit Register(msg.sender, _donationInUSDC, repAmount);
}
/**
* @notice Handles deposits by minting PeakDeFi Shares & updating total funds.
* @param _depositUSDCAmount The amount of the deposit in USDC
* @param _referrer The deposit referrer
*/
function __deposit(uint256 _depositUSDCAmount, address _referrer) internal {
// Register investment and give shares
uint256 shareAmount;
if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) {
uint256 usdcDecimals = getDecimals(usdc);
shareAmount = _depositUSDCAmount.mul(PRECISION).div(10**usdcDecimals);
} else {
shareAmount = _depositUSDCAmount.mul(sToken.totalSupply()).div(
totalFundsInUSDC
);
}
require(sToken.generateTokens(msg.sender, shareAmount));
totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount);
totalFundsAtManagePhaseStart = totalFundsAtManagePhaseStart.add(
_depositUSDCAmount
);
// Handle peakReferralToken
if (peakReward.canRefer(msg.sender, _referrer)) {
peakReward.refer(msg.sender, _referrer);
}
address actualReferrer = peakReward.referrerOf(msg.sender);
if (actualReferrer != address(0)) {
require(
peakReferralToken.generateTokens(actualReferrer, shareAmount)
);
}
}
/**
* @notice Handles deposits by burning PeakDeFi Shares & updating total funds.
* @param _withdrawUSDCAmount The amount of the withdrawal in USDC
*/
function __withdraw(uint256 _withdrawUSDCAmount) internal {
// Burn Shares
uint256 shareAmount = _withdrawUSDCAmount.mul(sToken.totalSupply()).div(
totalFundsInUSDC
);
require(sToken.destroyTokens(msg.sender, shareAmount));
totalFundsInUSDC = totalFundsInUSDC.sub(_withdrawUSDCAmount);
// Handle peakReferralToken
address actualReferrer = peakReward.referrerOf(msg.sender);
if (actualReferrer != address(0)) {
uint256 balance = peakReferralToken.balanceOf(actualReferrer);
uint256 burnReferralTokenAmount = shareAmount > balance
? balance
: shareAmount;
require(
peakReferralToken.destroyTokens(
actualReferrer,
burnReferralTokenAmount
)
);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >= 0.4.22 <0.8.0;
library console {
address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67);
function _sendLogPayload(bytes memory payload) private view {
uint256 payloadLength = payload.length;
address consoleAddress = CONSOLE_ADDRESS;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function log() internal view {
_sendLogPayload(abi.encodeWithSignature("log()"));
}
function logInt(int p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(int)", p0));
}
function logUint(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function logString(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function logBool(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function logAddress(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function logBytes(bytes memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes)", p0));
}
function logByte(byte p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(byte)", p0));
}
function logBytes1(bytes1 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0));
}
function logBytes2(bytes2 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0));
}
function logBytes3(bytes3 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0));
}
function logBytes4(bytes4 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0));
}
function logBytes5(bytes5 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0));
}
function logBytes6(bytes6 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0));
}
function logBytes7(bytes7 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0));
}
function logBytes8(bytes8 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0));
}
function logBytes9(bytes9 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0));
}
function logBytes10(bytes10 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0));
}
function logBytes11(bytes11 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0));
}
function logBytes12(bytes12 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0));
}
function logBytes13(bytes13 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0));
}
function logBytes14(bytes14 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0));
}
function logBytes15(bytes15 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0));
}
function logBytes16(bytes16 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0));
}
function logBytes17(bytes17 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0));
}
function logBytes18(bytes18 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0));
}
function logBytes19(bytes19 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0));
}
function logBytes20(bytes20 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0));
}
function logBytes21(bytes21 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0));
}
function logBytes22(bytes22 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0));
}
function logBytes23(bytes23 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0));
}
function logBytes24(bytes24 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0));
}
function logBytes25(bytes25 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0));
}
function logBytes26(bytes26 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0));
}
function logBytes27(bytes27 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0));
}
function logBytes28(bytes28 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0));
}
function logBytes29(bytes29 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0));
}
function logBytes30(bytes30 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0));
}
function logBytes31(bytes31 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0));
}
function logBytes32(bytes32 p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0));
}
function log(uint p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint)", p0));
}
function log(string memory p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string)", p0));
}
function log(bool p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool)", p0));
}
function log(address p0) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address)", p0));
}
function log(uint p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function log(uint p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function log(uint p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function log(uint p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function log(string memory p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function log(string memory p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function log(string memory p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function log(string memory p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function log(bool p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function log(bool p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function log(bool p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function log(bool p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function log(address p0, uint p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function log(address p0, string memory p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function log(address p0, bool p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function log(address p0, address p1) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function log(uint p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function log(uint p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function log(uint p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function log(uint p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function log(uint p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function log(uint p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function log(uint p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function log(uint p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function log(uint p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function log(uint p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function log(uint p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function log(uint p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function log(uint p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function log(uint p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function log(uint p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function log(uint p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function log(string memory p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function log(string memory p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function log(string memory p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function log(string memory p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function log(string memory p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function log(string memory p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function log(string memory p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function log(string memory p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function log(string memory p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function log(string memory p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function log(string memory p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function log(string memory p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function log(string memory p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function log(string memory p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function log(string memory p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function log(string memory p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function log(bool p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function log(bool p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function log(bool p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function log(bool p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function log(bool p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function log(bool p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function log(bool p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function log(bool p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function log(bool p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function log(bool p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function log(bool p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function log(bool p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function log(bool p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function log(bool p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function log(bool p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function log(bool p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function log(address p0, uint p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function log(address p0, uint p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function log(address p0, uint p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function log(address p0, uint p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function log(address p0, string memory p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function log(address p0, string memory p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function log(address p0, string memory p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function log(address p0, string memory p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function log(address p0, bool p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function log(address p0, bool p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function log(address p0, bool p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function log(address p0, bool p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function log(address p0, address p1, uint p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function log(address p0, address p1, string memory p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function log(address p0, address p1, bool p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function log(address p0, address p1, address p2) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function log(uint p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function log(uint p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function log(string memory p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function log(bool p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function log(address p0, uint p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function log(address p0, string memory p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function log(address p0, bool p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, uint p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, string memory p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, bool p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, uint p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, string memory p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, bool p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function log(address p0, address p1, address p2, address p3) internal view {
_sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
pragma solidity 0.5.17;
import "./PeakDeFiStorage.sol";
contract PeakDeFiLogic3 is
PeakDeFiStorage,
Utils(address(0), address(0), address(0))
{
/**
* @notice Passes if the fund has not finalized the next smart contract to upgrade to
*/
modifier notReadyForUpgrade {
require(hasFinalizedNextVersion == false);
_;
}
/**
* @notice Executes function only during the given cycle phase.
* @param phase the cycle phase during which the function may be called
*/
modifier during(CyclePhase phase) {
require(cyclePhase == phase);
if (cyclePhase == CyclePhase.Intermission) {
require(isInitialized);
}
_;
}
/**
* Next phase transition handler
* @notice Moves the fund to the next phase in the investment cycle.
*/
function nextPhase() public nonReentrant {
require(
now >= startTimeOfCyclePhase.add(phaseLengths[uint256(cyclePhase)])
);
if (isInitialized == false) {
// first cycle of this smart contract deployment
// check whether ready for starting cycle
isInitialized = true;
require(proxyAddr != address(0)); // has initialized proxy
require(proxy.peakdefiFundAddress() == address(this)); // upgrade complete
require(hasInitializedTokenListings); // has initialized token listings
// execute initialization function
__init();
require(
previousVersion == address(0) ||
(previousVersion != address(0) &&
getBalance(usdc, address(this)) > 0)
); // has transfered assets from previous version
} else {
// normal phase changing
if (cyclePhase == CyclePhase.Intermission) {
require(hasFinalizedNextVersion == false); // Shouldn't progress to next phase if upgrading
// Update total funds at management phase's beginning
totalFundsAtManagePhaseStart = totalFundsInUSDC;
// reset number of managers onboarded
managersOnboardedThisCycle = 0;
} else if (cyclePhase == CyclePhase.Manage) {
// Burn any RepToken left in PeakDeFiFund's account
require(
cToken.destroyTokens(
address(this),
cToken.balanceOf(address(this))
)
);
// Pay out commissions and fees
uint256 profit = 0;
uint256 usdcBalanceAtManagePhaseStart
= totalFundsAtManagePhaseStart.add(totalCommissionLeft);
if (
getBalance(usdc, address(this)) >
usdcBalanceAtManagePhaseStart
) {
profit = getBalance(usdc, address(this)).sub(
usdcBalanceAtManagePhaseStart
);
}
totalFundsInUSDC = getBalance(usdc, address(this))
.sub(totalCommissionLeft)
.sub(peakReferralTotalCommissionLeft);
// Calculate manager commissions
uint256 commissionThisCycle = COMMISSION_RATE
.mul(profit)
.add(ASSET_FEE_RATE.mul(totalFundsInUSDC))
.div(PRECISION);
_totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle(
cycleNumber
)
.add(commissionThisCycle); // account for penalties
totalCommissionLeft = totalCommissionLeft.add(
commissionThisCycle
);
// Calculate referrer commissions
uint256 peakReferralCommissionThisCycle = PEAK_COMMISSION_RATE
.mul(profit)
.mul(peakReferralToken.totalSupply())
.div(sToken.totalSupply())
.div(PRECISION);
_peakReferralTotalCommissionOfCycle[cycleNumber] = peakReferralTotalCommissionOfCycle(
cycleNumber
)
.add(peakReferralCommissionThisCycle);
peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft
.add(peakReferralCommissionThisCycle);
totalFundsInUSDC = getBalance(usdc, address(this))
.sub(totalCommissionLeft)
.sub(peakReferralTotalCommissionLeft);
// Give the developer PeakDeFi shares inflation funding
uint256 devFunding = devFundingRate
.mul(sToken.totalSupply())
.div(PRECISION);
require(sToken.generateTokens(devFundingAccount, devFunding));
// Emit event
emit TotalCommissionPaid(
cycleNumber,
totalCommissionOfCycle(cycleNumber)
);
emit PeakReferralTotalCommissionPaid(
cycleNumber,
peakReferralTotalCommissionOfCycle(cycleNumber)
);
_managePhaseEndBlock[cycleNumber] = block.number;
// Clear/update upgrade related data
if (nextVersion == address(this)) {
// The developer proposed a candidate, but the managers decide to not upgrade at all
// Reset upgrade process
delete nextVersion;
delete hasFinalizedNextVersion;
}
if (nextVersion != address(0)) {
hasFinalizedNextVersion = true;
emit FinalizedNextVersion(cycleNumber, nextVersion);
}
// Start new cycle
cycleNumber = cycleNumber.add(1);
}
cyclePhase = CyclePhase(addmod(uint256(cyclePhase), 1, 2));
}
startTimeOfCyclePhase = now;
// Reward caller if they're a manager
if (cToken.balanceOf(msg.sender) > 0) {
require(cToken.generateTokens(msg.sender, NEXT_PHASE_REWARD));
}
emit ChangedPhase(
cycleNumber,
uint256(cyclePhase),
now,
totalFundsInUSDC
);
}
/**
* @notice Initializes several important variables after smart contract upgrade
*/
function __init() internal {
_managePhaseEndBlock[cycleNumber.sub(1)] = block.number;
// load values from previous version
totalCommissionLeft = previousVersion == address(0)
? 0
: PeakDeFiStorage(previousVersion).totalCommissionLeft();
totalFundsInUSDC = getBalance(usdc, address(this)).sub(
totalCommissionLeft
);
}
/**
* Upgrading functions
*/
/**
* @notice Allows the developer to propose a candidate smart contract for the fund to upgrade to.
* The developer may change the candidate during the Intermission phase.
* @param _candidate the address of the candidate smart contract
* @return True if successfully changed candidate, false otherwise.
*/
function developerInitiateUpgrade(address payable _candidate)
public
onlyOwner
notReadyForUpgrade
during(CyclePhase.Intermission)
nonReentrant
returns (bool _success)
{
if (_candidate == address(0) || _candidate == address(this)) {
return false;
}
nextVersion = _candidate;
emit DeveloperInitiatedUpgrade(cycleNumber, _candidate);
return true;
}
/**
Commission functions
*/
/**
* @notice Returns the commission balance of `_manager`
* @return the commission balance and the received penalty, denoted in USDC
*/
function commissionBalanceOf(address _manager)
public
view
returns (uint256 _commission, uint256 _penalty)
{
if (lastCommissionRedemption(_manager) >= cycleNumber) {
return (0, 0);
}
uint256 cycle = lastCommissionRedemption(_manager) > 0
? lastCommissionRedemption(_manager)
: 1;
uint256 cycleCommission;
uint256 cyclePenalty;
for (; cycle < cycleNumber; cycle++) {
(cycleCommission, cyclePenalty) = commissionOfAt(_manager, cycle);
_commission = _commission.add(cycleCommission);
_penalty = _penalty.add(cyclePenalty);
}
}
/**
* @notice Returns the commission amount received by `_manager` in the `_cycle`th cycle
* @return the commission amount and the received penalty, denoted in USDC
*/
function commissionOfAt(address _manager, uint256 _cycle)
public
view
returns (uint256 _commission, uint256 _penalty)
{
if (hasRedeemedCommissionForCycle(_manager, _cycle)) {
return (0, 0);
}
// take risk into account
uint256 baseRepTokenBalance = cToken.balanceOfAt(
_manager,
managePhaseEndBlock(_cycle.sub(1))
);
uint256 baseStake = baseRepTokenBalance == 0
? baseRiskStakeFallback(_manager)
: baseRepTokenBalance;
if (baseRepTokenBalance == 0 && baseRiskStakeFallback(_manager) == 0) {
return (0, 0);
}
uint256 riskTakenProportion = riskTakenInCycle(_manager, _cycle)
.mul(PRECISION)
.div(baseStake.mul(MIN_RISK_TIME)); // risk / threshold
riskTakenProportion = riskTakenProportion > PRECISION
? PRECISION
: riskTakenProportion; // max proportion is 1
uint256 fullCommission = totalCommissionOfCycle(_cycle)
.mul(cToken.balanceOfAt(_manager, managePhaseEndBlock(_cycle)))
.div(cToken.totalSupplyAt(managePhaseEndBlock(_cycle)));
_commission = fullCommission.mul(riskTakenProportion).div(PRECISION);
_penalty = fullCommission.sub(_commission);
}
/**
* @notice Redeems commission.
*/
function redeemCommission(bool _inShares)
public
during(CyclePhase.Intermission)
nonReentrant
{
uint256 commission = __redeemCommission();
if (_inShares) {
// Deposit commission into fund
__deposit(commission);
// Emit deposit event
emit Deposit(
cycleNumber,
msg.sender,
USDC_ADDR,
commission,
commission,
now
);
} else {
// Transfer the commission in USDC
usdc.safeTransfer(msg.sender, commission);
}
}
/**
* @notice Redeems commission for a particular cycle.
* @param _inShares true to redeem in PeakDeFi Shares, false to redeem in USDC
* @param _cycle the cycle for which the commission will be redeemed.
* Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber.
*/
function redeemCommissionForCycle(bool _inShares, uint256 _cycle)
public
during(CyclePhase.Intermission)
nonReentrant
{
require(_cycle < cycleNumber);
uint256 commission = __redeemCommissionForCycle(_cycle);
if (_inShares) {
// Deposit commission into fund
__deposit(commission);
// Emit deposit event
emit Deposit(
cycleNumber,
msg.sender,
USDC_ADDR,
commission,
commission,
now
);
} else {
// Transfer the commission in USDC
usdc.safeTransfer(msg.sender, commission);
}
}
/**
* @notice Redeems the commission for all previous cycles. Updates the related variables.
* @return the amount of commission to be redeemed
*/
function __redeemCommission() internal returns (uint256 _commission) {
require(lastCommissionRedemption(msg.sender) < cycleNumber);
uint256 penalty; // penalty received for not taking enough risk
(_commission, penalty) = commissionBalanceOf(msg.sender);
// record the redemption to prevent double-redemption
for (
uint256 i = lastCommissionRedemption(msg.sender);
i < cycleNumber;
i++
) {
_hasRedeemedCommissionForCycle[msg.sender][i] = true;
}
_lastCommissionRedemption[msg.sender] = cycleNumber;
// record the decrease in commission pool
totalCommissionLeft = totalCommissionLeft.sub(_commission);
// include commission penalty to this cycle's total commission pool
_totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle(
cycleNumber
)
.add(penalty);
// clear investment arrays to save space
delete userInvestments[msg.sender];
delete userCompoundOrders[msg.sender];
emit CommissionPaid(cycleNumber, msg.sender, _commission);
}
/**
* @notice Redeems commission for a particular cycle. Updates the related variables.
* @param _cycle the cycle for which the commission will be redeemed
* @return the amount of commission to be redeemed
*/
function __redeemCommissionForCycle(uint256 _cycle)
internal
returns (uint256 _commission)
{
require(!hasRedeemedCommissionForCycle(msg.sender, _cycle));
uint256 penalty; // penalty received for not taking enough risk
(_commission, penalty) = commissionOfAt(msg.sender, _cycle);
_hasRedeemedCommissionForCycle[msg.sender][_cycle] = true;
// record the decrease in commission pool
totalCommissionLeft = totalCommissionLeft.sub(_commission);
// include commission penalty to this cycle's total commission pool
_totalCommissionOfCycle[cycleNumber] = totalCommissionOfCycle(
cycleNumber
)
.add(penalty);
// clear investment arrays to save space
delete userInvestments[msg.sender];
delete userCompoundOrders[msg.sender];
emit CommissionPaid(_cycle, msg.sender, _commission);
}
/**
* @notice Handles deposits by minting PeakDeFi Shares & updating total funds.
* @param _depositUSDCAmount The amount of the deposit in USDC
*/
function __deposit(uint256 _depositUSDCAmount) internal {
// Register investment and give shares
if (sToken.totalSupply() == 0 || totalFundsInUSDC == 0) {
require(sToken.generateTokens(msg.sender, _depositUSDCAmount));
} else {
require(
sToken.generateTokens(
msg.sender,
_depositUSDCAmount.mul(sToken.totalSupply()).div(
totalFundsInUSDC
)
)
);
}
totalFundsInUSDC = totalFundsInUSDC.add(_depositUSDCAmount);
}
/**
PeakDeFi
*/
/**
* @notice Returns the commission balance of `_referrer`
* @return the commission balance, denoted in USDC
*/
function peakReferralCommissionBalanceOf(address _referrer)
public
view
returns (uint256 _commission)
{
if (peakReferralLastCommissionRedemption(_referrer) >= cycleNumber) {
return (0);
}
uint256 cycle = peakReferralLastCommissionRedemption(_referrer) > 0
? peakReferralLastCommissionRedemption(_referrer)
: 1;
uint256 cycleCommission;
for (; cycle < cycleNumber; cycle++) {
(cycleCommission) = peakReferralCommissionOfAt(_referrer, cycle);
_commission = _commission.add(cycleCommission);
}
}
/**
* @notice Returns the commission amount received by `_referrer` in the `_cycle`th cycle
* @return the commission amount, denoted in USDC
*/
function peakReferralCommissionOfAt(address _referrer, uint256 _cycle)
public
view
returns (uint256 _commission)
{
_commission = peakReferralTotalCommissionOfCycle(_cycle)
.mul(
peakReferralToken.balanceOfAt(
_referrer,
managePhaseEndBlock(_cycle)
)
)
.div(peakReferralToken.totalSupplyAt(managePhaseEndBlock(_cycle)));
}
/**
* @notice Redeems commission.
*/
function peakReferralRedeemCommission()
public
during(CyclePhase.Intermission)
nonReentrant
{
uint256 commission = __peakReferralRedeemCommission();
// Transfer the commission in USDC
usdc.safeApprove(address(peakReward), commission);
peakReward.payCommission(msg.sender, address(usdc), commission, false);
}
/**
* @notice Redeems commission for a particular cycle.
* @param _cycle the cycle for which the commission will be redeemed.
* Commissions for a cycle will be redeemed during the Intermission phase of the next cycle, so _cycle must < cycleNumber.
*/
function peakReferralRedeemCommissionForCycle(uint256 _cycle)
public
during(CyclePhase.Intermission)
nonReentrant
{
require(_cycle < cycleNumber);
uint256 commission = __peakReferralRedeemCommissionForCycle(_cycle);
// Transfer the commission in USDC
usdc.safeApprove(address(peakReward), commission);
peakReward.payCommission(msg.sender, address(usdc), commission, false);
}
/**
* @notice Redeems the commission for all previous cycles. Updates the related variables.
* @return the amount of commission to be redeemed
*/
function __peakReferralRedeemCommission()
internal
returns (uint256 _commission)
{
require(peakReferralLastCommissionRedemption(msg.sender) < cycleNumber);
_commission = peakReferralCommissionBalanceOf(msg.sender);
// record the redemption to prevent double-redemption
for (
uint256 i = peakReferralLastCommissionRedemption(msg.sender);
i < cycleNumber;
i++
) {
_peakReferralHasRedeemedCommissionForCycle[msg.sender][i] = true;
}
_peakReferralLastCommissionRedemption[msg.sender] = cycleNumber;
// record the decrease in commission pool
peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub(
_commission
);
emit PeakReferralCommissionPaid(cycleNumber, msg.sender, _commission);
}
/**
* @notice Redeems commission for a particular cycle. Updates the related variables.
* @param _cycle the cycle for which the commission will be redeemed
* @return the amount of commission to be redeemed
*/
function __peakReferralRedeemCommissionForCycle(uint256 _cycle)
internal
returns (uint256 _commission)
{
require(!peakReferralHasRedeemedCommissionForCycle(msg.sender, _cycle));
_commission = peakReferralCommissionOfAt(msg.sender, _cycle);
_peakReferralHasRedeemedCommissionForCycle[msg.sender][_cycle] = true;
// record the decrease in commission pool
peakReferralTotalCommissionLeft = peakReferralTotalCommissionLeft.sub(
_commission
);
emit PeakReferralCommissionPaid(_cycle, msg.sender, _commission);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "../interfaces/CERC20.sol";
import "../interfaces/Comptroller.sol";
contract TestCERC20 is CERC20 {
using SafeMath for uint;
uint public constant PRECISION = 10 ** 18;
uint public constant MAX_UINT = 2 ** 256 - 1;
address public _underlying;
uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION;
mapping(address => uint) public _balanceOf;
mapping(address => uint) public _borrowBalanceCurrent;
Comptroller public COMPTROLLER;
constructor(address __underlying, address _comptrollerAddr) public {
_underlying = __underlying;
COMPTROLLER = Comptroller(_comptrollerAddr);
}
function mint(uint mintAmount) external returns (uint) {
ERC20Detailed token = ERC20Detailed(_underlying);
require(token.transferFrom(msg.sender, address(this), mintAmount));
_balanceOf[msg.sender] = _balanceOf[msg.sender].add(mintAmount.mul(10 ** this.decimals()).div(PRECISION));
return 0;
}
function redeemUnderlying(uint redeemAmount) external returns (uint) {
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION));
ERC20Detailed token = ERC20Detailed(_underlying);
require(token.transfer(msg.sender, redeemAmount));
return 0;
}
function borrow(uint amount) external returns (uint) {
// add to borrow balance
_borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount);
// transfer asset
ERC20Detailed token = ERC20Detailed(_underlying);
require(token.transfer(msg.sender, amount));
return 0;
}
function repayBorrow(uint amount) external returns (uint) {
// accept repayment
ERC20Detailed token = ERC20Detailed(_underlying);
uint256 repayAmount = amount == MAX_UINT ? _borrowBalanceCurrent[msg.sender] : amount;
require(token.transferFrom(msg.sender, address(this), repayAmount));
// subtract from borrow balance
_borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(repayAmount);
return 0;
}
function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; }
function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; }
function underlying() external view returns (address) { return _underlying; }
function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; }
function decimals() external view returns (uint) { return 8; }
}
pragma solidity 0.5.17;
import "./TestCERC20.sol";
contract TestCERC20Factory {
mapping(address => address) public createdTokens;
event CreatedToken(address underlying, address cToken);
function newToken(address underlying, address comptroller) public returns(address) {
require(createdTokens[underlying] == address(0));
TestCERC20 token = new TestCERC20(underlying, comptroller);
createdTokens[underlying] = address(token);
emit CreatedToken(underlying, address(token));
return address(token);
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/CEther.sol";
import "../interfaces/Comptroller.sol";
contract TestCEther is CEther {
using SafeMath for uint;
uint public constant PRECISION = 10 ** 18;
uint public _exchangeRateCurrent = 10 ** (18 - 8) * PRECISION;
mapping(address => uint) public _balanceOf;
mapping(address => uint) public _borrowBalanceCurrent;
Comptroller public COMPTROLLER;
constructor(address _comptrollerAddr) public {
COMPTROLLER = Comptroller(_comptrollerAddr);
}
function mint() external payable {
_balanceOf[msg.sender] = _balanceOf[msg.sender].add(msg.value.mul(10 ** this.decimals()).div(PRECISION));
}
function redeemUnderlying(uint redeemAmount) external returns (uint) {
_balanceOf[msg.sender] = _balanceOf[msg.sender].sub(redeemAmount.mul(10 ** this.decimals()).div(PRECISION));
msg.sender.transfer(redeemAmount);
return 0;
}
function borrow(uint amount) external returns (uint) {
// add to borrow balance
_borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].add(amount);
// transfer asset
msg.sender.transfer(amount);
return 0;
}
function repayBorrow() external payable {
_borrowBalanceCurrent[msg.sender] = _borrowBalanceCurrent[msg.sender].sub(msg.value);
}
function balanceOf(address account) external view returns (uint) { return _balanceOf[account]; }
function borrowBalanceCurrent(address account) external returns (uint) { return _borrowBalanceCurrent[account]; }
function exchangeRateCurrent() external returns (uint) { return _exchangeRateCurrent; }
function decimals() external view returns (uint) { return 8; }
function() external payable {}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "../interfaces/Comptroller.sol";
import "../interfaces/PriceOracle.sol";
import "../interfaces/CERC20.sol";
contract TestComptroller is Comptroller {
using SafeMath for uint;
uint256 internal constant PRECISION = 10 ** 18;
mapping(address => address[]) public getAssetsIn;
uint256 internal collateralFactor = 2 * PRECISION / 3;
constructor() public {}
function enterMarkets(address[] calldata cTokens) external returns (uint[] memory) {
uint[] memory errors = new uint[](cTokens.length);
for (uint256 i = 0; i < cTokens.length; i = i.add(1)) {
getAssetsIn[msg.sender].push(cTokens[i]);
errors[i] = 0;
}
return errors;
}
function markets(address /*cToken*/) external view returns (bool isListed, uint256 collateralFactorMantissa) {
return (true, collateralFactor);
}
}
pragma solidity 0.5.17;
import "../interfaces/KyberNetwork.sol";
import "../Utils.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
contract TestKyberNetwork is KyberNetwork, Utils(address(0), address(0), address(0)), Ownable {
mapping(address => uint256) public priceInUSDC;
constructor(address[] memory _tokens, uint256[] memory _pricesInUSDC) public {
for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
priceInUSDC[_tokens[i]] = _pricesInUSDC[i];
}
}
function setTokenPrice(address _token, uint256 _priceInUSDC) public onlyOwner {
priceInUSDC[_token] = _priceInUSDC;
}
function setAllTokenPrices(address[] memory _tokens, uint256[] memory _pricesInUSDC) public onlyOwner {
for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
priceInUSDC[_tokens[i]] = _pricesInUSDC[i];
}
}
function getExpectedRate(ERC20Detailed src, ERC20Detailed dest, uint /*srcQty*/) external view returns (uint expectedRate, uint slippageRate)
{
uint256 result = priceInUSDC[address(src)].mul(10**getDecimals(dest)).mul(PRECISION).div(priceInUSDC[address(dest)].mul(10**getDecimals(src)));
return (result, result);
}
function tradeWithHint(
ERC20Detailed src,
uint srcAmount,
ERC20Detailed dest,
address payable destAddress,
uint maxDestAmount,
uint /*minConversionRate*/,
address /*walletId*/,
bytes calldata /*hint*/
)
external
payable
returns(uint)
{
require(calcDestAmount(src, srcAmount, dest) <= maxDestAmount);
if (address(src) == address(ETH_TOKEN_ADDRESS)) {
require(srcAmount == msg.value);
} else {
require(src.transferFrom(msg.sender, address(this), srcAmount));
}
if (address(dest) == address(ETH_TOKEN_ADDRESS)) {
destAddress.transfer(calcDestAmount(src, srcAmount, dest));
} else {
require(dest.transfer(destAddress, calcDestAmount(src, srcAmount, dest)));
}
return calcDestAmount(src, srcAmount, dest);
}
function calcDestAmount(
ERC20Detailed src,
uint srcAmount,
ERC20Detailed dest
) internal view returns (uint destAmount) {
return srcAmount.mul(priceInUSDC[address(src)]).mul(10**getDecimals(dest)).div(priceInUSDC[address(dest)].mul(10**getDecimals(src)));
}
function() external payable {}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "../interfaces/PriceOracle.sol";
import "../interfaces/CERC20.sol";
contract TestPriceOracle is PriceOracle, Ownable {
using SafeMath for uint;
uint public constant PRECISION = 10 ** 18;
address public CETH_ADDR;
mapping(address => uint256) public priceInUSD;
constructor(address[] memory _tokens, uint256[] memory _pricesInUSD, address _cETH) public {
for (uint256 i = 0; i < _tokens.length; i = i.add(1)) {
priceInUSD[_tokens[i]] = _pricesInUSD[i];
}
CETH_ADDR = _cETH;
}
function setTokenPrice(address _token, uint256 _priceInUSD) public onlyOwner {
priceInUSD[_token] = _priceInUSD;
}
function getUnderlyingPrice(address _cToken) external view returns (uint) {
if (_cToken == CETH_ADDR) {
return priceInUSD[_cToken];
}
CERC20 cToken = CERC20(_cToken);
ERC20Detailed underlying = ERC20Detailed(cToken.underlying());
return priceInUSD[_cToken].mul(PRECISION).div(10 ** uint256(underlying.decimals()));
}
}
pragma solidity 0.5.17;
import "@openzeppelin/contracts/token/ERC20/ERC20Mintable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
/**
* @title An ERC20 token used for testing.
* @author Zefram Lou (Zebang Liu)
*/
contract TestToken is ERC20Mintable, ERC20Burnable, ERC20Detailed {
constructor(string memory name, string memory symbol, uint8 decimals)
public
ERC20Detailed(name, symbol, decimals)
{}
}
pragma solidity 0.5.17;
import "./TestToken.sol";
contract TestTokenFactory {
mapping(bytes32 => address) public createdTokens;
event CreatedToken(string symbol, address addr);
function newToken(string memory name, string memory symbol, uint8 decimals) public returns(address) {
bytes32 symbolHash = keccak256(abi.encodePacked(symbol));
require(createdTokens[symbolHash] == address(0));
TestToken token = new TestToken(name, symbol, decimals);
token.addMinter(msg.sender);
token.renounceMinter();
createdTokens[symbolHash] = address(token);
emit CreatedToken(symbol, address(token));
return address(token);
}
function getToken(string memory symbol) public view returns(address) {
return createdTokens[keccak256(abi.encodePacked(symbol))];
}
}
pragma solidity 0.5.17;
contract TestUniswapOracle {
function update() external returns (bool success) {
return true;
}
function consult(address token, uint256 amountIn)
external
view
returns (uint256 amountOut)
{
return 3 * 10**5; // 1 PEAK = 0.30 USDC
}
}
|
Checks if an Ethereum account is a smart contract _addr the account to be checked return True if the account is a smart contract, false otherwise/
|
function isContract(address _addr) internal view returns(bool) {
uint256 size;
if (_addr == address(0)) return false;
assembly {
size := extcodesize(_addr)
}
return size>0;
}
| 15,851,496
|
./partial_match/1/0x65D1121cf02007A7ae46C783824272C3aBC791F6/sources/PublishedToken.sol
|
Setter for bonus of tokens user get for 1 ETH sending to contract/
|
function setBonus(uint256 bonus)onlyOwner public returns (bool success){
bonusinpercent = bonus;
return true;
}
| 15,900,502
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev 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 "./IERC721.sol";
import "./IERC721Receiver.sol";
import "./extensions/IERC721Metadata.sol";
import "../../utils/Address.sol";
import "../../utils/Context.sol";
import "../../utils/Strings.sol";
import "../../utils/introspection/ERC165.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../ERC721.sol";
import "./IERC721Enumerable.sol";
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/utils/Address.sol";
import "@openzeppelin/contracts/utils/Counters.sol";
import "./ERC721Tradable.sol";
/**
* @title ARA NFTs
* Base contract to create and distribute rewards to the ARA community
*/
contract ARA is ERC721Tradable {
using Address for address;
using Counters for Counters.Counter;
// ============================== Variables ===================================
address ownerAddress;
// Count of tokenID
Counters.Counter private tokenIdCount;
Counters.Counter private giveAwayIdCount;
// Metadata setter and locker
string private metadataTokenURI;
uint256 immutable mvpMintStartDate;
uint256 immutable giveAwayIndexStart;
uint256 immutable mvpPassword;
bool private lock;
// ============================== Constants ===================================
/// @notice Price to mint the NFTs
uint256 public constant price = 1e17;
/// @notice Max tokens supply for this contract
uint256 public constant maxSupply = 10000;
/// @notice Max tokens per transactions
uint256 public constant maxPerTx = 20;
/// @notice Max number of tokens available during first round
uint256 public constant roundOneSupply = 1000;
/// @notice Max number of tokens available during second round
uint256 public constant roundTwoSupply = 4000;
/// @notice Start of the early sale period (in Unix second)
uint256 public constant mintStartDate = 1642784400;
// ============================== Constructor ===================================
/// @notice Constructor of the NFT contract
/// Takes as argument the OpenSea contract to manage sells
constructor(address _proxyRegistryAddress, uint256 mvpMintStart, uint256 giveAwayIndex, uint256 mvpPasswordInsert)
ERC721Tradable("ApeRacingAcademy", "ARA", _proxyRegistryAddress) {
giveAwayIndexStart = giveAwayIndex;
giveAwayIdCount._value = giveAwayIndex;
metadataTokenURI = "https://aperacingacademy-metadata.herokuapp.com/metadata/";
mvpMintStartDate = mvpMintStart;
mvpPassword = mvpPasswordInsert;
lock = false;
}
// ============================== Functions ===================================
/// @notice Returns the url of the servor handling token metadata
/// @dev Can be changed until the boolean `lock` is set to true
function baseTokenURI() public view override returns (string memory) {
return metadataTokenURI;
}
// ============================== Public functions ===================================
/// Return the amount of token minted, taking into account for the boost
/// @param amount of token the msg.sender paid for
function nitroBoost(uint256 amount) internal view returns (uint256) {
uint256 globalAmount = amount;
if (tokenIdCount._value < roundOneSupply) {
globalAmount = uint256((globalAmount * 150) / 100);
} else if (tokenIdCount._value < roundTwoSupply) {
globalAmount = uint256((globalAmount * 125) / 100);
}
return globalAmount;
}
/// @notice Mints `tokenId` and transfers it to message sender
/// @param amount Number tokens to mint
function mint(uint256 amount) external payable {
require(msg.value >= price * amount, "Incorrect amount sent");
require(block.timestamp > mintStartDate, "Public Minting not opened yet");
require(amount <= maxPerTx, "Limit to 20 tokens per transactions");
uint256 boostedAmount = nitroBoost(amount);
for (uint256 i = 0; i < boostedAmount; i++) {
if (tokenIdCount._value < giveAwayIndexStart) {
tokenIdCount.increment();
_mint(msg.sender, tokenIdCount.current());
}
}
}
/// @notice Mints `tokenId` and transfers it to message sender
/// @param amount Number tokens to mint
function mvpMint(uint256 password, uint256 amount) external payable {
require(msg.value >= price * amount, "Incorrect amount sent");
require(block.timestamp > mvpMintStartDate, "MVP Minting not opened yet");
require(amount <= maxPerTx, "Limit to 20 tokens per transactions");
require(password == mvpPassword, "Wrong Password !");
uint256 boostedAmount = nitroBoost(amount);
for (uint256 i = 0; i < boostedAmount; i++) {
if (tokenIdCount._value < giveAwayIndexStart) {
tokenIdCount.increment();
_mint(msg.sender, tokenIdCount.current());
}
}
}
// ============================== Governor ===================================
/// @notice Change the metadata server endpoint to final ipfs server
/// @param ipfsTokenURI url pointing to ipfs server
function serve_IPFS_URI(string memory ipfsTokenURI) external onlyOwner {
require(!lock, "Metadata has been locked and cannot be changed anymore");
metadataTokenURI = ipfsTokenURI;
}
/// @notice Lock the token URI, no one can change it anymore
function lock_URI() external onlyOwner {
lock = true;
}
/// @notice Mints several tokens for various addresses.
/// @param to Array of addresses of token future owners
function giveAway(address[] memory to) external onlyOwner {
for (uint256 i = 0; i < to.length; i++) {
giveAwayIdCount.increment();
_mint(to[i], giveAwayIdCount.current());
}
}
/// @notice Recovers any ERC20 token (wETH, USDC) that could accrue on this contract
/// @param tokenAddress Address of the token to recover
/// @param to Address to send the ERC20 to
/// @param amountToRecover Amount of ERC20 to recover
function withdrawERC20(
address tokenAddress,
address to,
uint256 amountToRecover
) external onlyOwner {
IERC20(tokenAddress).transfer(to, amountToRecover);
}
/// @notice Recovers any ETH that could accrue on this contract
/// @param to Address to send the ETH to
function withdraw(address payable to) external onlyOwner {
address investor = 0x59f1AFBD895eFF95d0D61824C16287597AF2D0E7;
uint256 shareInvestor;
uint256 threshold = 30 ether;
if (address(this).balance > threshold){
shareInvestor = (5 * (address(this).balance - threshold)) / 100;
payable(investor).transfer(shareInvestor);
}
to.transfer(address(this).balance);
}
/// @notice Makes this contract payable
receive() external payable {}
// ============================== Internal Functions ===================================
/// @notice Mints a new token
/// @param to Address of the future owner of the token
/// @param tokenId Id of the token to mint
/// @dev Checks that the totalSupply is respected, that
function _mint(address to, uint256 tokenId) internal override {
require(tokenId < maxSupply, "Reached minting limit");
super._mint(to, tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
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/ContextMixin.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.
*/
abstract contract ERC721Tradable is Ownable, ContextMixin, ERC721Enumerable, NativeMetaTransaction {
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);
}
function baseTokenURI() public view virtual returns (string memory);
function tokenURI(uint256 _tokenId) public view override 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) public view override 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 view override returns (address sender) {
return ContextMixin.msgSender();
}
}
// 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 { Initializable } from "./Initializable.sol";
contract EIP712Base is Initializable {
struct EIP712Domain {
string name;
string version;
address verifyingContract;
bytes32 salt;
}
string public constant 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;
contract Initializable {
bool inited = false;
modifier initializer() {
require(!inited, "already inited");
_;
inited = true;
}
}
// 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);
}
}
|
Lock the token URI, no one can change it anymore
|
function lock_URI() external onlyOwner {
lock = true;
}
| 1,677,786
|
./full_match/1/0x0EBB2B76FBdcc3a636b652fd3769154b5C196249/sources/contracts2/CSPLGuildPoolV2.sol
|
poolに追加 execute from buySPL
|
function addEthToGuildPool(uint16 _guildType, address _purchaseBy) external payable whenNotPaused() nonReentrant() {
require(guildAsset.getTotalVolume(_guildType) > 0);
require(allowedAddresses[msg.sender]);
guildTypeToTotalAmount[_guildType] += msg.value;
emit EthAddedToPool(
_guildType,
msg.sender,
_purchaseBy,
msg.value,
block.timestamp
);
}
| 8,294,343
|
./full_match/3/0xA2656476F64F5f102a996d8BF87Fd6ea1342aad4/sources/contracts/wakeup.sol
|
Confirm whether the user is in the contract as joined or not.
|
function verifyJoined(address _participant) public view returns (bool) {
return participantExists[_participant];
}
| 8,282,126
|
/**
*Submitted for verification at Etherscan.io on 2021-08-23
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.8.4;
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;
}
}
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
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);
}
}
contract Gen0DistributorMarker is Ownable {
using SafeMath for uint256;
uint256 private claimingFee;
mapping(address => bool) public claimers;
event Claimed(address indexed _from);
constructor()
{
claimingFee = 0.004 * 10 ** 18; // (Varies by network)
}
function changeClaimingFees(uint256 _claimingFee) onlyOwner public {
claimingFee = _claimingFee;
}
function claim() payable public {
require (msg.value >= claimingFee, "E01");
require (claimers[msg.sender] == false, "E02");
claimers[msg.sender] = true;
emit Claimed(msg.sender);
}
function getClaimer(address _user) public view returns (bool) {
return claimers[_user];
}
function withdrawFees() onlyOwner external {
require(payable(msg.sender).send(address(this).balance));
}
}
|
Multiplies two unsigned integers, reverts on overflow./ 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
|
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath#mul: OVERFLOW");
return c;
}
| 2,332,198
|
./partial_match/1/0x2F66C5aAF006Bd9c51615D617589C16c0ed35fD3/sources/contracts/DODOV3MM/D3Vault/periphery/D3PoolQuota.sol
|
Enable default quota for a token
|
function enableDefaultQuota(address token, bool status) external onlyOwner {
hasDefaultQuota[token] = status;
}
| 4,285,681
|
/**
*Submitted for verification at Etherscan.io on 2018-03-26
*/
pragma solidity ^0.4.19;
/// @title Contract Resolver Interface
/// @author Digix Holdings Pte Ltd
contract ResolverClient {
/// The address of the resolver contract for this project
address public resolver;
/// The key to identify this contract
bytes32 public key;
/// Make our own address available to us as a constant
address public CONTRACT_ADDRESS;
/// Function modifier to check if msg.sender corresponds to the resolved address of a given key
/// @param _contract The resolver key
modifier if_sender_is(bytes32 _contract) {
require(
msg.sender == ContractResolver(resolver).get_contract(_contract)
);
_;
}
/// Function modifier to check resolver's locking status.
modifier unless_resolver_is_locked() {
require(is_locked() == false);
_;
}
/// @dev Initialize new contract
/// @param _key the resolver key for this contract
/// @return _success if the initialization is successful
function init(bytes32 _key, address _resolver)
internal
returns (bool _success)
{
bool _is_locked = ContractResolver(_resolver).locked();
if (_is_locked == false) {
CONTRACT_ADDRESS = address(this);
resolver = _resolver;
key = _key;
require(
ContractResolver(resolver).init_register_contract(
key,
CONTRACT_ADDRESS
)
);
_success = true;
} else {
_success = false;
}
}
/// @dev Destroy the contract and unregister self from the ContractResolver
/// @dev Can only be called by the owner of ContractResolver
function destroy() public returns (bool _success) {
bool _is_locked = ContractResolver(resolver).locked();
require(!_is_locked);
address _owner_of_contract_resolver = ContractResolver(resolver)
.owner();
require(msg.sender == _owner_of_contract_resolver);
_success = ContractResolver(resolver).unregister_contract(key);
require(_success);
selfdestruct(_owner_of_contract_resolver);
}
/// @dev Check if resolver is locked
/// @return _locked if the resolver is currently locked
function is_locked() private constant returns (bool _locked) {
_locked = ContractResolver(resolver).locked();
}
/// @dev Get the address of a contract
/// @param _key the resolver key to look up
/// @return _contract the address of the contract
function get_contract(bytes32 _key)
public
constant
returns (address _contract)
{
_contract = ContractResolver(resolver).get_contract(_key);
}
}
contract ContractResolver {
address public owner;
bool public locked;
function init_register_contract(bytes32 _key, address _contract_address)
public
returns (bool _success)
{}
/// @dev Unregister a contract. This can only be called from the contract with the key itself
/// @param _key the bytestring of the contract name
/// @return _success if the operation is successful
function unregister_contract(bytes32 _key) public returns (bool _success) {}
/// @dev Get address of a contract
/// @param _key the bytestring name of the contract to look up
/// @return _contract the address of the contract
function get_contract(bytes32 _key)
public
constant
returns (address _contract)
{}
}
contract DigixConstants {
/// general constants
uint256 constant SECONDS_IN_A_DAY = 24 * 60 * 60;
/// asset events
uint256 constant ASSET_EVENT_CREATED_VENDOR_ORDER = 1;
uint256 constant ASSET_EVENT_CREATED_TRANSFER_ORDER = 2;
uint256 constant ASSET_EVENT_CREATED_REPLACEMENT_ORDER = 3;
uint256 constant ASSET_EVENT_FULFILLED_VENDOR_ORDER = 4;
uint256 constant ASSET_EVENT_FULFILLED_TRANSFER_ORDER = 5;
uint256 constant ASSET_EVENT_FULFILLED_REPLACEMENT_ORDER = 6;
uint256 constant ASSET_EVENT_MINTED = 7;
uint256 constant ASSET_EVENT_MINTED_REPLACEMENT = 8;
uint256 constant ASSET_EVENT_RECASTED = 9;
uint256 constant ASSET_EVENT_REDEEMED = 10;
uint256 constant ASSET_EVENT_FAILED_AUDIT = 11;
uint256 constant ASSET_EVENT_ADMIN_FAILED = 12;
uint256 constant ASSET_EVENT_REMINTED = 13;
/// roles
uint256 constant ROLE_ZERO_ANYONE = 0;
uint256 constant ROLE_ROOT = 1;
uint256 constant ROLE_VENDOR = 2;
uint256 constant ROLE_XFERAUTH = 3;
uint256 constant ROLE_POPADMIN = 4;
uint256 constant ROLE_CUSTODIAN = 5;
uint256 constant ROLE_AUDITOR = 6;
uint256 constant ROLE_MARKETPLACE_ADMIN = 7;
uint256 constant ROLE_KYC_ADMIN = 8;
uint256 constant ROLE_FEES_ADMIN = 9;
uint256 constant ROLE_DOCS_UPLOADER = 10;
uint256 constant ROLE_KYC_RECASTER = 11;
uint256 constant ROLE_FEES_DISTRIBUTION_ADMIN = 12;
/// states
uint256 constant STATE_ZERO_UNDEFINED = 0;
uint256 constant STATE_CREATED = 1;
uint256 constant STATE_VENDOR_ORDER = 2;
uint256 constant STATE_TRANSFER = 3;
uint256 constant STATE_CUSTODIAN_DELIVERY = 4;
uint256 constant STATE_MINTED = 5;
uint256 constant STATE_AUDIT_FAILURE = 6;
uint256 constant STATE_REPLACEMENT_ORDER = 7;
uint256 constant STATE_REPLACEMENT_DELIVERY = 8;
uint256 constant STATE_RECASTED = 9;
uint256 constant STATE_REDEEMED = 10;
uint256 constant STATE_ADMIN_FAILURE = 11;
/// interactive contracts
bytes32 constant CONTRACT_INTERACTIVE_ASSETS_EXPLORER = "i:asset:explorer";
bytes32 constant CONTRACT_INTERACTIVE_DIGIX_DIRECTORY = "i:directory";
bytes32 constant CONTRACT_INTERACTIVE_MARKETPLACE = "i:mp";
bytes32 constant CONTRACT_INTERACTIVE_MARKETPLACE_ADMIN = "i:mpadmin";
bytes32 constant CONTRACT_INTERACTIVE_POPADMIN = "i:popadmin";
bytes32 constant CONTRACT_INTERACTIVE_PRODUCTS_LIST = "i:products";
bytes32 constant CONTRACT_INTERACTIVE_TOKEN = "i:token";
bytes32 constant CONTRACT_INTERACTIVE_BULK_WRAPPER = "i:bulk-wrapper";
bytes32 constant CONTRACT_INTERACTIVE_TOKEN_CONFIG = "i:token:config";
bytes32 constant CONTRACT_INTERACTIVE_TOKEN_INFORMATION = "i:token:information";
bytes32 constant CONTRACT_INTERACTIVE_MARKETPLACE_INFORMATION = "i:mp:information";
bytes32 constant CONTRACT_INTERACTIVE_IDENTITY = "i:identity";
/// controller contracts
bytes32 constant CONTRACT_CONTROLLER_ASSETS = "c:asset";
bytes32 constant CONTRACT_CONTROLLER_ASSETS_RECAST = "c:asset:recast";
bytes32 constant CONTRACT_CONTROLLER_ASSETS_EXPLORER = "c:explorer";
bytes32 constant CONTRACT_CONTROLLER_DIGIX_DIRECTORY = "c:directory";
bytes32 constant CONTRACT_CONTROLLER_MARKETPLACE = "c:mp";
bytes32 constant CONTRACT_CONTROLLER_MARKETPLACE_ADMIN = "c:mpadmin";
bytes32 constant CONTRACT_CONTROLLER_PRODUCTS_LIST = "c:products";
bytes32 constant CONTRACT_CONTROLLER_TOKEN_APPROVAL = "c:token:approval";
bytes32 constant CONTRACT_CONTROLLER_TOKEN_CONFIG = "c:token:config";
bytes32 constant CONTRACT_CONTROLLER_TOKEN_INFO = "c:token:info";
bytes32 constant CONTRACT_CONTROLLER_TOKEN_TRANSFER = "c:token:transfer";
bytes32 constant CONTRACT_CONTROLLER_JOB_ID = "c:jobid";
bytes32 constant CONTRACT_CONTROLLER_IDENTITY = "c:identity";
/// storage contracts
bytes32 constant CONTRACT_STORAGE_ASSETS = "s:asset";
bytes32 constant CONTRACT_STORAGE_ASSET_EVENTS = "s:asset:events";
bytes32 constant CONTRACT_STORAGE_DIGIX_DIRECTORY = "s:directory";
bytes32 constant CONTRACT_STORAGE_MARKETPLACE = "s:mp";
bytes32 constant CONTRACT_STORAGE_PRODUCTS_LIST = "s:products";
bytes32 constant CONTRACT_STORAGE_GOLD_TOKEN = "s:goldtoken";
bytes32 constant CONTRACT_STORAGE_JOB_ID = "s:jobid";
bytes32 constant CONTRACT_STORAGE_IDENTITY = "s:identity";
/// service contracts
bytes32 constant CONTRACT_SERVICE_TOKEN_DEMURRAGE = "sv:tdemurrage";
bytes32 constant CONTRACT_SERVICE_MARKETPLACE = "sv:mp";
bytes32 constant CONTRACT_SERVICE_DIRECTORY = "sv:directory";
/// fees distributors
bytes32 constant CONTRACT_DEMURRAGE_FEES_DISTRIBUTOR = "fees:distributor:demurrage";
bytes32 constant CONTRACT_RECAST_FEES_DISTRIBUTOR = "fees:distributor:recast";
bytes32 constant CONTRACT_TRANSFER_FEES_DISTRIBUTOR = "fees:distributor:transfer";
}
contract TokenLoggerCallback is ResolverClient, DigixConstants {
// event Transfer(address indexed _from, address indexed _to, uint256 _value);
// event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function log_mint(address _to, uint256 _value)
public
if_sender_is(CONTRACT_CONTROLLER_ASSETS)
{
// Transfer(address(0x0), _to, _value);
}
function log_recast_fees(address _from, address _to, uint256 _value)
public
if_sender_is(CONTRACT_CONTROLLER_ASSETS_RECAST)
{
// Transfer(_from, _to, _value);
}
function log_recast(address _from, uint256 _value)
public
if_sender_is(CONTRACT_CONTROLLER_ASSETS_RECAST)
{
// Transfer(_from, address(0x0), _value);
}
function log_demurrage_fees(address _from, address _to, uint256 _value)
public
if_sender_is(CONTRACT_SERVICE_TOKEN_DEMURRAGE)
{
// Transfer(_from, _to, _value);
}
function log_move_fees(address _from, address _to, uint256 _value)
public
if_sender_is(CONTRACT_CONTROLLER_TOKEN_CONFIG)
{
// Transfer(_from, _to, _value);
}
function log_transfer(address _from, address _to, uint256 _value)
public
if_sender_is(CONTRACT_CONTROLLER_TOKEN_TRANSFER)
{
// Transfer(_from, _to, _value);
}
function log_approve(address _owner, address _spender, uint256 _value)
public
if_sender_is(CONTRACT_CONTROLLER_TOKEN_APPROVAL)
{
// Approval(_owner, _spender, _value);
}
}
contract TokenInfoController {
function get_total_supply()
public
constant
returns (uint256 _total_supply)
{}
function get_allowance(address _account, address _spender)
public
constant
returns (uint256 _allowance)
{}
function get_balance(address _user)
public
constant
returns (uint256 _actual_balance)
{}
}
contract TokenTransferController {
function put_transfer(
address _sender,
address _recipient,
address _spender,
uint256 _amount,
bool _transfer_from
) public returns (bool _success) {}
}
contract TokenApprovalController {
function approve(address _account, address _spender, uint256 _amount)
public
returns (bool _success)
{}
}
/// The interface of a contract that can receive tokens from transferAndCall()
contract TokenReceiver {
function tokenFallback(address from, uint256 amount, bytes32 data)
public
returns (bool success);
}
/// @title DGX2.0 ERC-20 Token. ERC-677 is also implemented https://github.com/ethereum/EIPs/issues/677
/// @author Digix Holdings Pte Ltd
contract Token is TokenLoggerCallback {
string public constant name = "Digix Gold Token";
string public constant symbol = "DGX";
uint8 public constant decimals = 9;
function Token(address _resolver) public {
require(init(CONTRACT_INTERACTIVE_TOKEN, _resolver));
}
/// @notice show the total supply of gold tokens
/// @return {
/// "totalSupply": "total number of tokens"
/// }
function totalSupply() public constant returns (uint256 _total_supply) {
_total_supply = TokenInfoController(
get_contract(CONTRACT_CONTROLLER_TOKEN_INFO)
)
.get_total_supply();
}
/// @notice display balance of given account
/// @param _owner the account to query
/// @return {
/// "balance": "balance of the given account in nanograms"
/// }
function balanceOf(address _owner)
public
constant
returns (uint256 balance)
{
balance = TokenInfoController(
get_contract(CONTRACT_CONTROLLER_TOKEN_INFO)
)
.get_balance(_owner);
}
/// @notice transfer amount to account
/// @param _to account to send to
/// @param _value the amount in nanograms to send
/// @return {
/// "success": "returns true if successful"
/// }
function transfer(address _to, uint256 _value)
public
returns (bool success)
{
success = TokenTransferController(
get_contract(CONTRACT_CONTROLLER_TOKEN_TRANSFER)
)
.put_transfer(msg.sender, _to, 0x0, _value, false);
}
/// @notice transfer amount to account from account deducting from spender allowance
/// @param _to account to send to
/// @param _from account to send from
/// @param _value the amount in nanograms to send
/// @return {
/// "success": "returns true if successful"
/// }
function transferFrom(address _from, address _to, uint256 _value)
public
returns (bool success)
{
success = TokenTransferController(
get_contract(CONTRACT_CONTROLLER_TOKEN_TRANSFER)
)
.put_transfer(_from, _to, msg.sender, _value, true);
}
/// @notice implements transferAndCall() of ERC677
/// @param _receiver the contract to receive the token
/// @param _amount the amount of tokens to be transfered
/// @param _data the data to be passed to the tokenFallback function of the receiving contract
/// @return {
/// "success": "returns true if successful"
/// }
function transferAndCall(address _receiver, uint256 _amount, bytes32 _data)
public
returns (bool success)
{
transfer(_receiver, _amount);
success = TokenReceiver(_receiver).tokenFallback(
msg.sender,
_amount,
_data
);
require(success);
}
/// @notice approve given spender to transfer given amount this will set allowance to 0 if current value is non-zero
/// @param _spender the account that is given an allowance
/// @param _value the amount in nanograms to approve
/// @return {
/// "success": "returns true if successful"
/// }
function approve(address _spender, uint256 _value)
public
returns (bool success)
{
success = TokenApprovalController(
get_contract(CONTRACT_CONTROLLER_TOKEN_APPROVAL)
)
.approve(msg.sender, _spender, _value);
}
/// @notice check the spending allowance of a given user from a given account
/// @param _owner the account to spend from
/// @param _spender the spender
/// @return {
/// "remaining": "the remaining allowance in nanograms"
/// }
function allowance(address _owner, address _spender)
public
constant
returns (uint256 remaining)
{
remaining = TokenInfoController(
get_contract(CONTRACT_CONTROLLER_TOKEN_INFO)
)
.get_allowance(_owner, _spender);
}
}
|
Transfer(_from, _to, _value);
|
function log_demurrage_fees(address _from, address _to, uint256 _value)
public
if_sender_is(CONTRACT_SERVICE_TOKEN_DEMURRAGE)
{
}
| 13,046,814
|
// SPDX-License-Identifier: MIT
pragma solidity =0.7.6;
pragma abicoder v2;
import "./interfaces.sol";
import "./helpers.sol";
contract Resolver is Helpers {
/**
* @dev Sort token address
* @param _token0: token0 Address
* @param _token1: token1 Address
*/
function sort(address _token0, address _token1) external view returns (address token0, address token1) {
if (_token0 < _token1) {
token0 = _token1;
token1 = _token0;
} else {
token0 = _token0;
token1 = _token1;
}
}
function getPositionInfoByTokenId(uint256 tokenId) public view returns (PositionInfo memory pInfo) {
(pInfo) = positions(tokenId);
}
function getPositionsInfo(address user)
public
view
returns (uint256[] memory tokenIds, PositionInfo[] memory positionsInfo)
{
tokenIds = userNfts(user);
for (uint256 i = 0; i < tokenIds.length; i++) {
uint256 tokenId = tokenIds[i];
(positionsInfo[i]) = positions(tokenId);
}
}
function getDepositAmount(
uint256 tokenId,
uint256 amountA,
uint256 amountB
)
public
view
returns (
uint256 liquidity,
uint256 amount0,
uint256 amount1
)
{
(liquidity, amount0, amount1) = depositAmount(tokenId, amountA, amountB);
}
function getSigleDepositAmount(
uint256 tokenId,
address tokenA,
uint256 amountA
)
public
view
returns (
address,
uint256,
address,
uint256
)
{
(address tokenB, uint256 amountB) = singleDepositAmount(tokenId, tokenA, amountA);
return (tokenA, amountA, tokenB, amountB);
}
function getWithdrawAmount(uint256 tokenId, uint128 liquidity)
public
view
returns (uint256 amountA, uint256 amountB)
{
(amountA, amountB) = withdrawAmount(tokenId, liquidity);
}
function getCollectAmount(uint256 tokenId) public view returns (uint256 amountA, uint256 amountB) {
(amountA, amountB) = collectInfo(tokenId);
}
function getUserNFTs(address user) public view returns (uint256[] memory tokenIds) {
tokenIds = userNfts(user);
}
}
contract InstaUniswapV3Resolver is Resolver {
string public constant name = "UniswapV3-Resolver-v1";
}
pragma solidity =0.7.6;
pragma abicoder v2;
import "@openzeppelin/contracts/token/ERC721/IERC721.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Metadata.sol";
import "@openzeppelin/contracts/token/ERC721/IERC721Enumerable.sol";
interface TokenInterface {
function approve(address, uint256) external;
function transfer(address, uint256) external;
function transferFrom(
address,
address,
uint256
) external;
function deposit() external payable;
function withdraw(uint256) external;
function balanceOf(address) external view returns (uint256);
function decimals() external view returns (uint256);
function totalSupply() external view returns (uint256);
}
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
interface ISwapRouter is IUniswapV3SwapCallback {
struct ExactInputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another token
/// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata
/// @return amountOut The amount of the received token
function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut);
struct ExactInputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountIn;
uint256 amountOutMinimum;
}
/// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata
/// @return amountOut The amount of the received token
function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut);
struct ExactOutputSingleParams {
address tokenIn;
address tokenOut;
uint24 fee;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
uint160 sqrtPriceLimitX96;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another token
/// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata
/// @return amountIn The amount of the input token
function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn);
struct ExactOutputParams {
bytes path;
address recipient;
uint256 deadline;
uint256 amountOut;
uint256 amountInMaximum;
}
/// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed)
/// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata
/// @return amountIn The amount of the input token
function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn);
}
/// @title Creates and initializes V3 Pools
/// @notice Provides a method for creating and initializing a pool, if necessary, for bundling with other methods that
/// require the pool to exist.
interface IPoolInitializer {
/// @notice Creates a new pool if it does not exist, then initializes if not initialized
/// @dev This method can be bundled with others via IMulticall for the first action (e.g. mint) performed against a pool
/// @param token0 The contract address of token0 of the pool
/// @param token1 The contract address of token1 of the pool
/// @param fee The fee amount of the v3 pool for the specified token pair
/// @param sqrtPriceX96 The initial square root price of the pool as a Q64.96 value
/// @return pool Returns the pool address based on the pair of tokens and fee, will return the newly created pool address if necessary
function createAndInitializePoolIfNecessary(
address token0,
address token1,
uint24 fee,
uint160 sqrtPriceX96
) external payable returns (address pool);
}
/// @title Immutable state
/// @notice Functions that return immutable state of the router
interface IPeripheryImmutableState {
/// @return Returns the address of the Uniswap V3 factory
function factory() external view returns (address);
/// @return Returns the address of WETH9
function WETH9() external view returns (address);
}
/// @title Periphery Payments
/// @notice Functions to ease deposits and withdrawals of ETH
interface IPeripheryPayments {
/// @notice Unwraps the contract's WETH9 balance and sends it to recipient as ETH.
/// @dev The amountMinimum parameter prevents malicious contracts from stealing WETH9 from users.
/// @param amountMinimum The minimum amount of WETH9 to unwrap
/// @param recipient The address receiving ETH
function unwrapWETH9(uint256 amountMinimum, address recipient) external payable;
/// @notice Refunds any ETH balance held by this contract to the `msg.sender`
/// @dev Useful for bundling with mint or increase liquidity that uses ether, or exact output swaps
/// that use ether for the input amount
function refundETH() external payable;
/// @notice Transfers the full amount of a token held by this contract to recipient
/// @dev The amountMinimum parameter prevents malicious contracts from stealing the token from users
/// @param token The contract address of the token which will be transferred to `recipient`
/// @param amountMinimum The minimum amount of token required for a transfer
/// @param recipient The destination address of the token
function sweepToken(
address token,
uint256 amountMinimum,
address recipient
) external payable;
}
/// @title ERC721 with permit
/// @notice Extension to ERC721 that includes a permit function for signature based approvals
interface IERC721Permit is IERC721 {
/// @notice The permit typehash used in the permit signature
/// @return The typehash for the permit
function PERMIT_TYPEHASH() external pure returns (bytes32);
/// @notice The domain separator used in the permit signature
/// @return The domain seperator used in encoding of permit signature
function DOMAIN_SEPARATOR() external view returns (bytes32);
/// @notice Approve of a specific token ID for spending by spender via signature
/// @param spender The account that is being approved
/// @param tokenId The ID of the token that is being approved for spending
/// @param deadline The deadline timestamp by which the call must be mined for the approve to work
/// @param v Must produce valid secp256k1 signature from the holder along with `r` and `s`
/// @param r Must produce valid secp256k1 signature from the holder along with `v` and `s`
/// @param s Must produce valid secp256k1 signature from the holder along with `r` and `v`
function permit(
address spender,
uint256 tokenId,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external payable;
}
/// @title Non-fungible token for positions
/// @notice Wraps Uniswap V3 positions in a non-fungible token interface which allows for them to be transferred
/// and authorized.
interface INonfungiblePositionManager is
IPoolInitializer,
IPeripheryPayments,
IPeripheryImmutableState,
IERC721Metadata,
IERC721Enumerable,
IERC721Permit
{
/// @notice Emitted when liquidity is increased for a position NFT
/// @dev Also emitted when a token is minted
/// @param tokenId The ID of the token for which liquidity was increased
/// @param liquidity The amount by which liquidity for the NFT position was increased
/// @param amount0 The amount of token0 that was paid for the increase in liquidity
/// @param amount1 The amount of token1 that was paid for the increase in liquidity
event IncreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when liquidity is decreased for a position NFT
/// @param tokenId The ID of the token for which liquidity was decreased
/// @param liquidity The amount by which liquidity for the NFT position was decreased
/// @param amount0 The amount of token0 that was accounted for the decrease in liquidity
/// @param amount1 The amount of token1 that was accounted for the decrease in liquidity
event DecreaseLiquidity(uint256 indexed tokenId, uint128 liquidity, uint256 amount0, uint256 amount1);
/// @notice Emitted when tokens are collected for a position NFT
/// @dev The amounts reported may not be exactly equivalent to the amounts transferred, due to rounding behavior
/// @param tokenId The ID of the token for which underlying tokens were collected
/// @param recipient The address of the account that received the collected tokens
/// @param amount0 The amount of token0 owed to the position that was collected
/// @param amount1 The amount of token1 owed to the position that was collected
event Collect(uint256 indexed tokenId, address recipient, uint256 amount0, uint256 amount1);
/// @notice Returns the position information associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the position
/// @return nonce The nonce for permits
/// @return operator The address that is approved for spending
/// @return token0 The address of the token0 for a specific pool
/// @return token1 The address of the token1 for a specific pool
/// @return fee The fee associated with the pool
/// @return tickLower The lower end of the tick range for the position
/// @return tickUpper The higher end of the tick range for the position
/// @return liquidity The liquidity of the position
/// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position
/// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position
/// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation
/// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation
function positions(uint256 tokenId)
external
view
returns (
uint96 nonce,
address operator,
address token0,
address token1,
uint24 fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
struct MintParams {
address token0;
address token1;
uint24 fee;
int24 tickLower;
int24 tickUpper;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
address recipient;
uint256 deadline;
}
/// @notice Creates a new position wrapped in a NFT
/// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized
/// a method does not exist, i.e. the pool is assumed to be initialized.
/// @param params The params necessary to mint a position, encoded as `MintParams` in calldata
/// @return tokenId The ID of the token that represents the minted position
/// @return liquidity The amount of liquidity for this position
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function mint(MintParams calldata params)
external
payable
returns (
uint256 tokenId,
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct IncreaseLiquidityParams {
uint256 tokenId;
uint256 amount0Desired;
uint256 amount1Desired;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender`
/// @param params tokenId The ID of the token for which liquidity is being increased,
/// amount0Desired The desired amount of token0 to be spent,
/// amount1Desired The desired amount of token1 to be spent,
/// amount0Min The minimum amount of token0 to spend, which serves as a slippage check,
/// amount1Min The minimum amount of token1 to spend, which serves as a slippage check,
/// deadline The time by which the transaction must be included to effect the change
/// @return liquidity The new liquidity amount as a result of the increase
/// @return amount0 The amount of token0 to acheive resulting liquidity
/// @return amount1 The amount of token1 to acheive resulting liquidity
function increaseLiquidity(IncreaseLiquidityParams calldata params)
external
payable
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
);
struct DecreaseLiquidityParams {
uint256 tokenId;
uint128 liquidity;
uint256 amount0Min;
uint256 amount1Min;
uint256 deadline;
}
/// @notice Decreases the amount of liquidity in a position and accounts it to the position
/// @param params tokenId The ID of the token for which liquidity is being decreased,
/// amount The amount by which liquidity will be decreased,
/// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity,
/// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity,
/// deadline The time by which the transaction must be included to effect the change
/// @return amount0 The amount of token0 accounted to the position's tokens owed
/// @return amount1 The amount of token1 accounted to the position's tokens owed
function decreaseLiquidity(DecreaseLiquidityParams calldata params)
external
payable
returns (uint256 amount0, uint256 amount1);
struct CollectParams {
uint256 tokenId;
address recipient;
uint128 amount0Max;
uint128 amount1Max;
}
/// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient
/// @param params tokenId The ID of the NFT for which tokens are being collected,
/// recipient The account that should receive the tokens,
/// amount0Max The maximum amount of token0 to collect,
/// amount1Max The maximum amount of token1 to collect
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1);
/// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens
/// must be collected first.
/// @param tokenId The ID of the token that is being burned
function burn(uint256 tokenId) external payable;
}
pragma solidity 0.7.6;
pragma abicoder v2;
import { DSMath } from "../../utils/dsmath.sol";
import "./contracts/interfaces/IUniswapV3Pool.sol";
import "./contracts/libraries/TickMath.sol";
import "./contracts/libraries/FullMath.sol";
import "./contracts/libraries/FixedPoint128.sol";
import "./contracts/libraries/LiquidityAmounts.sol";
import "./contracts/libraries/PositionKey.sol";
import "./contracts/libraries/PoolAddress.sol";
import "./interfaces.sol";
abstract contract Helpers is DSMath {
/**
* @dev Return ethereum address
*/
address internal constant ethAddr = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/**
* @dev Return Wrapped ETH address
*/
address internal constant wethAddr = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
INonfungiblePositionManager private nftManager = INonfungiblePositionManager(getUniswapNftManagerAddr());
/**
* @dev Return uniswap v3 NFT Manager Address
*/
function getUniswapNftManagerAddr() internal pure returns (address) {
return 0xC36442b4a4522E871399CD717aBDD847Ab11FE88;
}
function convert18ToDec(uint256 _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = (_amt / 10**(18 - _dec));
}
function convertTo18(uint256 _dec, uint256 _amt) internal pure returns (uint256 amt) {
amt = mul(_amt, 10**(18 - _dec));
}
function changeEthAddress(address buy, address sell)
internal
pure
returns (TokenInterface _buy, TokenInterface _sell)
{
_buy = buy == ethAddr ? TokenInterface(wethAddr) : TokenInterface(buy);
_sell = sell == ethAddr ? TokenInterface(wethAddr) : TokenInterface(sell);
}
/**
* @dev Return uniswap v3 Swap Router Address
*/
function getUniswapRouterAddr() internal pure returns (address) {
return 0xE592427A0AEce92De3Edee1F18E0157C05861564;
}
/**
* @dev Get Last NFT Index
* @param user: User address
*/
function getLastNftId(address user) internal view returns (uint256 tokenId) {
uint256 len = nftManager.balanceOf(user);
tokenId = nftManager.tokenOfOwnerByIndex(user, len - 1);
}
function userNfts(address user) internal view returns (uint256[] memory tokenIds) {
uint256 len = nftManager.balanceOf(user);
tokenIds = new uint256[](len);
for (uint256 i = 0; i < len; i++) {
uint256 tokenId = nftManager.tokenOfOwnerByIndex(user, i);
tokenIds[i] = tokenId;
}
}
function getMinAmount(
TokenInterface token,
uint256 amt,
uint256 slippage
) internal view returns (uint256 minAmt) {
uint256 _amt18 = convertTo18(token.decimals(), amt);
minAmt = wmul(_amt18, sub(WAD, slippage));
minAmt = convert18ToDec(token.decimals(), minAmt);
}
struct PositionInfo {
address token0;
address token1;
address pool;
uint24 fee;
int24 tickLower;
int24 tickUpper;
int24 currentTick;
uint128 liquidity;
uint128 tokenOwed0;
uint128 tokenOwed1;
uint256 amount0;
uint256 amount1;
uint256 collectAmount0;
uint256 collectAmount1;
}
function positions(uint256 tokenId) internal view returns (PositionInfo memory pInfo) {
(
,
,
pInfo.token0,
pInfo.token1,
pInfo.fee,
pInfo.tickLower,
pInfo.tickUpper,
pInfo.liquidity,
,
,
,
) = nftManager.positions(tokenId);
(, , , , , , , , , , pInfo.tokenOwed0, pInfo.tokenOwed1) = nftManager.positions(tokenId);
pInfo.pool = getPoolAddress(pInfo.token0, pInfo.token1, pInfo.fee);
IUniswapV3Pool pool = IUniswapV3Pool(pInfo.pool);
(, pInfo.currentTick, , , , , ) = pool.slot0();
(pInfo.amount0, pInfo.amount1) = withdrawAmount(tokenId, pInfo.liquidity);
(pInfo.collectAmount0, pInfo.collectAmount1) = collectInfo(tokenId);
}
function getPoolAddress(
address token0,
address token1,
uint24 fee
) internal view returns (address poolAddr) {
poolAddr = PoolAddress.computeAddress(
nftManager.factory(),
PoolAddress.PoolKey({ token0: token0, token1: token1, fee: fee })
);
}
function depositAmount(
uint256 tokenId,
uint256 amountA,
uint256 amountB
)
internal
view
returns (
uint128 liquidity,
uint256 amount0,
uint256 amount1
)
{
(, , address _token0, address _token1, uint24 _fee, int24 tickLower, int24 tickUpper, , , , , ) = nftManager
.positions(tokenId);
IUniswapV3Pool pool = IUniswapV3Pool(getPoolAddress(_token0, _token1, _fee));
// compute the liquidity amount
{
(uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
liquidity = LiquidityAmounts.getLiquidityForAmounts(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amountA,
amountB
);
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
// amount0 = sub(amountA, amount0);
// amount1 = sub(amountB, amount1);
}
}
function singleDepositAmount(
uint256 tokenId,
address tokenA,
uint256 amountA
) internal view returns (address tokenB, uint256 amountB) {
(, , address _token0, address _token1, uint24 _fee, int24 tickLower, int24 tickUpper, , , , , ) = nftManager
.positions(tokenId);
bool reverseFlag = false;
if (tokenA != _token0) {
(tokenA, tokenB) = (_token0, _token1);
reverseFlag = true;
} else {
tokenB = _token1;
}
if (!reverseFlag) {
uint128 liquidity = LiquidityAmounts.getLiquidityForAmount0(
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amountA
);
amountB = LiquidityAmounts.getAmount1ForLiquidity(
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
} else {
uint128 liquidity = LiquidityAmounts.getLiquidityForAmount1(
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amountA
);
amountB = LiquidityAmounts.getAmount0ForLiquidity(
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
}
function withdrawAmount(uint256 tokenId, uint128 liquidity)
internal
view
returns (uint256 amount0, uint256 amount1)
{
require(liquidity > 0, "liquidity should greater than 0");
(
,
,
address _token0,
address _token1,
uint24 _fee,
int24 tickLower,
int24 tickUpper,
uint128 positionLiquidity,
,
,
,
) = nftManager.positions(tokenId);
require(positionLiquidity >= liquidity, "Liquidity amount is over than position liquidity amount");
IUniswapV3Pool pool = IUniswapV3Pool(getPoolAddress(_token0, _token1, _fee));
(uint160 sqrtPriceX96, , , , , , ) = pool.slot0();
(amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
function collectInfo(uint256 tokenId) internal view returns (uint256 amount0, uint256 amount1) {
(
,
,
address _token0,
address _token1,
uint24 _fee,
int24 tickLower,
int24 tickUpper,
uint128 liquidity,
uint256 _feeGrowthInside0LastX128,
uint256 _feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
) = nftManager.positions(tokenId);
IUniswapV3Pool pool = IUniswapV3Pool(getPoolAddress(_token0, _token1, _fee));
(, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, , ) = pool.positions(
PositionKey.compute(getUniswapNftManagerAddr(), tickLower, tickUpper)
);
tokensOwed0 += uint128(
FullMath.mulDiv(feeGrowthInside0LastX128 - _feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128)
);
tokensOwed1 += uint128(
FullMath.mulDiv(feeGrowthInside1LastX128 - _feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128)
);
amount0 = tokensOwed0;
amount1 = tokensOwed1;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Enumerable is IERC721 {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.7.0;
contract DSMath {
function add(uint256 x, uint256 y) internal pure returns (uint256 z) {
require((z = x + y) >= x, "math-not-safe");
}
function sub(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = x - y <= x ? x - y : 0;
}
function mul(uint256 x, uint256 y) internal pure returns (uint256 z) {
require(y == 0 || (z = x * y) / y == x, "math-not-safe");
}
function sqrt(uint256 y) internal pure returns (uint256 z) {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
uint256 internal constant WAD = 10**18;
uint256 internal constant RAY = 10**27;
function rmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), RAY / 2) / RAY;
}
function wmul(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, y), WAD / 2) / WAD;
}
function rdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, RAY), y / 2) / y;
}
function wdiv(uint256 x, uint256 y) internal pure returns (uint256 z) {
z = add(mul(x, WAD), y / 2) / y;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "./pool/IUniswapV3PoolImmutables.sol";
import "./pool/IUniswapV3PoolState.sol";
import "./pool/IUniswapV3PoolDerivedState.sol";
import "./pool/IUniswapV3PoolActions.sol";
import "./pool/IUniswapV3PoolOwnerActions.sol";
import "./pool/IUniswapV3PoolEvents.sol";
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.7.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(MAX_TICK), "T");
uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000;
if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128;
if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128;
if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128;
if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128;
if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128;
if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128;
if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128;
if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128;
if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128;
if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128;
if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128;
if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128;
if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128;
if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128;
if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128;
if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128;
if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128;
if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128;
if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128;
if (tick > 0) ratio = type(uint256).max / ratio;
// this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96.
// we then downcast because we know the result always fits within 160 bits due to our tick input constraint
// we round up in the division so getTickAtSqrtRatio of the output price is always consistent
sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1));
}
/// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio
/// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may
/// ever return.
/// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96
/// @return tick The greatest tick for which the ratio is less than or equal to the input ratio
function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) {
// second inequality must be < because the price can never reach the price at the max tick
require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, "R");
uint256 ratio = uint256(sqrtPriceX96) << 32;
uint256 r = ratio;
uint256 msb = 0;
assembly {
let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(5, gt(r, 0xFFFFFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(4, gt(r, 0xFFFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(3, gt(r, 0xFF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(2, gt(r, 0xF))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := shl(1, gt(r, 0x3))
msb := or(msb, f)
r := shr(f, r)
}
assembly {
let f := gt(r, 0x1)
msb := or(msb, f)
}
if (msb >= 128) r = ratio >> (msb - 127);
else r = ratio << (127 - msb);
int256 log_2 = (int256(msb) - 128) << 64;
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(63, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(62, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(61, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(60, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(59, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(58, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(57, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(56, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(55, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(54, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(53, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(52, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(51, f))
r := shr(f, r)
}
assembly {
r := shr(127, mul(r, r))
let f := shr(128, r)
log_2 := or(log_2, shl(50, f))
}
int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number
int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128);
int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128);
tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = (type(uint256).max - denominator + 1) & denominator;
// Divide denominator by power of two
assembly {
denominator := div(denominator, twos)
}
// Divide [prod1 prod0] by the factors of two
assembly {
prod0 := div(prod0, twos)
}
// Shift in bits from prod1 into prod0. For this we need
// to flip `twos` such that it is 2**256 / twos.
// If twos is zero, then it becomes one
assembly {
twos := add(div(sub(0, twos), twos), 1)
}
prod0 |= prod1 * twos;
// Invert denominator mod 2**256
// Now that denominator is an odd number, it has an inverse
// modulo 2**256 such that denominator * inv = 1 mod 2**256.
// Compute the inverse by starting with a seed that is correct
// correct for four bits. That is, denominator * inv = 1 mod 2**4
uint256 inv = (3 * denominator) ^ 2;
// Now use Newton-Raphson iteration to improve the precision.
// Thanks to Hensel's lifting lemma, this also works in modular
// arithmetic, doubling the correct bits in each step.
inv *= 2 - denominator * inv; // inverse mod 2**8
inv *= 2 - denominator * inv; // inverse mod 2**16
inv *= 2 - denominator * inv; // inverse mod 2**32
inv *= 2 - denominator * inv; // inverse mod 2**64
inv *= 2 - denominator * inv; // inverse mod 2**128
inv *= 2 - denominator * inv; // inverse mod 2**256
// Because the division is now exact we can divide by multiplying
// with the modular inverse of denominator. This will give us the
// correct result modulo 2**256. Since the precoditions guarantee
// that the outcome is less than 2**256, this is the final result.
// We don't need to compute the high bits of the result and prod1
// is no longer required.
result = prod0 * inv;
return result;
}
/// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
function mulDivRoundingUp(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
result = mulDiv(a, b, denominator);
if (mulmod(a, b, denominator) > 0) {
require(result < type(uint256).max);
result++;
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint128
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
library FixedPoint128 {
uint256 internal constant Q128 = 0x100000000000000000000000000000000;
}
pragma solidity >=0.5.0;
import "./FullMath.sol";
import "./FixedPoint96.sol";
library LiquidityAmounts {
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
pragma solidity >=0.5.0;
library PositionKey {
function compute(
address owner,
int24 tickLower,
int24 tickUpper
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
}
}
pragma solidity >=0.5.0;
library PoolAddress {
bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54;
struct PoolKey {
address token0;
address token1;
uint24 fee;
}
function getPoolKey(
address tokenA,
address tokenB,
uint24 fee
) internal pure returns (PoolKey memory) {
if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA);
return PoolKey({ token0: tokenA, token1: tokenB, fee: fee });
}
function computeAddress(address factory, PoolKey memory key) internal pure returns (address pool) {
require(key.token0 < key.token1);
pool = address(
uint160(
uint256(
keccak256(
abi.encodePacked(
hex"ff",
factory,
keccak256(abi.encode(key.token0, key.token1, key.fee)),
POOL_INIT_CODE_HASH
)
)
)
)
);
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
|
Sort token address _token0: token0 Address _token1: token1 Address/
|
function sort(address _token0, address _token1) external view returns (address token0, address token1) {
if (_token0 < _token1) {
token0 = _token1;
token1 = _token0;
token0 = _token0;
token1 = _token1;
}
}
| 480,230
|
./partial_match/56/0x472F647Df948a00534098E4d564cd8A145d6e9f7/sources/EggChef.sol
|
Withdraw without caring about rewards. EMERGENCY ONLY.
|
function emergencyWithdraw() public {
UserInfo storage user = userInfo[msg.sender];
egg.safeTransfer(address(msg.sender), user.amount);
emit EmergencyWithdraw(msg.sender, user.amount);
user.amount = 0;
user.rewardDebt = 0;
user.rewardPending = 0;
}
| 11,092,731
|
pragma solidity ^0.4.24;
contract Ownable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @return the address of the owner.
*/
function owner() public view returns(address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner());
_;
}
/**
* @return true if `msg.sender` is the owner of the contract.
*/
function isOwner() public view returns(bool) {
return msg.sender == _owner;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
* @notice Renouncing to ownership will leave the contract without an owner.
* It will not be possible to call the functions with the `onlyOwner`
* modifier anymore.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
library SafeMath {
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0); // Solidity only automatically asserts when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a);
uint256 c = a - b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
return a % b;
}
}
contract 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);
}
}
contract Presale is Ownable, ReentrancyGuard {
using SafeMath for uint256;
struct ReferralData {
uint256 referrals; // number of referrals
uint256 bonusSum; // sum of all bonuses - this is just for showing the total amount - for payouts the referralBonuses mapping will be used
address[] children; // child referrals
}
uint256 public currentPrice = 0;
bool public isActive = false;
uint256 public currentDiscountSum = 0; // current sum of all discounts (have to stay in the contract for payout)
uint256 public overallDiscountSum = 0; // sum of all discounts given since beginning
bool public referralsEnabled = true; // are referrals enabled in general
mapping(address => uint) private referralBonuses;
uint256 public referralBonusMaxDepth = 3; // used to ensure the max depth
mapping(uint256 => uint) public currentReferralCommissionPercentages; // commission levels
uint256 public currentReferralBuyerDiscountPercentage = 5; // discount percentage if a buyer uses a valid affiliate link
mapping(address => address) private parentReferrals; // parent relationship
mapping(address => ReferralData) private referralData; // referral data for this address
mapping(address => uint) private nodesBought; // number of bought nodes
event MasternodeSold(address buyer, uint256 price, string coinsTargetAddress, bool referral);
event MasternodePriceChanged(uint256 price);
event ReferralAdded(address buyer, address parent);
constructor() public {
currentReferralCommissionPercentages[0] = 10;
currentReferralCommissionPercentages[1] = 5;
currentReferralCommissionPercentages[2] = 3;
}
function () external payable {
// nothing to do
}
function buyMasternode(string memory coinsTargetAddress) public nonReentrant payable {
_buyMasternode(coinsTargetAddress, false, owner());
}
function buyMasternodeReferral(string memory coinsTargetAddress, address referral) public nonReentrant payable {
_buyMasternode(coinsTargetAddress, referralsEnabled, referral);
}
function _buyMasternode(string memory coinsTargetAddress, bool useReferral, address referral) internal {
require(isActive, "Buying is currently deactivated.");
require(currentPrice > 0, "There was no MN price set so far.");
uint256 nodePrice = currentPrice;
// nodes can be bought cheaper if the user uses a valid referral address
if (useReferral && isValidReferralAddress(referral)) {
nodePrice = getDiscountedNodePrice();
}
require(msg.value >= nodePrice, "Sent amount of ETH was too low.");
// check target address
uint256 length = bytes(coinsTargetAddress).length;
require(length >= 30 && length <= 42 , "Coins target address invalid");
if (useReferral && isValidReferralAddress(referral)) {
require(msg.sender != referral, "You can't be your own referral.");
// set parent/child relations (only if there is no connection/parent yet available)
// --> this also means that a referral structure can't be changed
address parent = parentReferrals[msg.sender];
if (referralData[parent].referrals == 0) {
referralData[referral].referrals = referralData[referral].referrals.add(1);
referralData[referral].children.push(msg.sender);
parentReferrals[msg.sender] = referral;
}
// iterate over commissionLevels and calculate commissions
uint256 discountSumForThisPayment = 0;
address currentReferral = referral;
for (uint256 level=0; level < referralBonusMaxDepth; level++) {
// only apply discount if referral address is valid (or as long we can step up the hierarchy)
if(isValidReferralAddress(currentReferral)) {
require(msg.sender != currentReferral, "Invalid referral structure (you can't be in your own tree)");
// do not take node price here since it could be already dicounted
uint256 referralBonus = currentPrice.div(100).mul(currentReferralCommissionPercentages[level]);
// set payout bonus
referralBonuses[currentReferral] = referralBonuses[currentReferral].add(referralBonus);
// set stats/counters
referralData[currentReferral].bonusSum = referralData[currentReferral].bonusSum.add(referralBonus);
discountSumForThisPayment = discountSumForThisPayment.add(referralBonus);
// step up one hierarchy level
currentReferral = parentReferrals[currentReferral];
} else {
// we can't find any parent - stop hierarchy calculation
break;
}
}
require(discountSumForThisPayment < nodePrice, "Wrong calculation of bonuses/discounts - would be higher than the price itself");
currentDiscountSum = currentDiscountSum.add(discountSumForThisPayment);
overallDiscountSum = overallDiscountSum.add(discountSumForThisPayment);
}
// set the node bought counter
nodesBought[msg.sender] = nodesBought[msg.sender].add(1);
emit MasternodeSold(msg.sender, currentPrice, coinsTargetAddress, useReferral);
}
function setActiveState(bool active) public onlyOwner {
isActive = active;
}
function setPrice(uint256 price) public onlyOwner {
require(price > 0, "Price has to be greater than zero.");
currentPrice = price;
emit MasternodePriceChanged(price);
}
function setReferralsEnabledState(bool _referralsEnabled) public onlyOwner {
referralsEnabled = _referralsEnabled;
}
function setReferralCommissionPercentageLevel(uint256 level, uint256 percentage) public onlyOwner {
require(percentage >= 0 && percentage <= 20, "Percentage has to be between 0 and 20.");
require(level >= 0 && level < referralBonusMaxDepth, "Invalid depth level");
currentReferralCommissionPercentages[level] = percentage;
}
function setReferralBonusMaxDepth(uint256 depth) public onlyOwner {
require(depth >= 0 && depth <= 10, "Referral bonus depth too high.");
referralBonusMaxDepth = depth;
}
function setReferralBuyerDiscountPercentage(uint256 percentage) public onlyOwner {
require(percentage >= 0 && percentage <= 20, "Percentage has to be between 0 and 20.");
currentReferralBuyerDiscountPercentage = percentage;
}
function withdraw(uint256 amount) public onlyOwner {
owner().transfer(amount);
}
function withdrawReferralBonus() public nonReentrant returns (bool) {
uint256 amount = referralBonuses[msg.sender];
if (amount > 0) {
referralBonuses[msg.sender] = 0;
currentDiscountSum = currentDiscountSum.sub(amount);
if (!msg.sender.send(amount)) {
referralBonuses[msg.sender] = amount;
currentDiscountSum = currentDiscountSum.add(amount);
return false;
}
}
return true;
}
function checkReferralBonusHeight(address addr) public view returns (uint) {
return referralBonuses[addr];
}
function getNrOfReferrals(address addr) public view returns (uint) {
return referralData[addr].referrals;
}
function getReferralBonusSum(address addr) public view returns (uint) {
return referralData[addr].bonusSum;
}
function getReferralChildren(address addr) public view returns (address[] memory) {
return referralData[addr].children;
}
function getReferralChild(address addr, uint256 idx) public view returns (address) {
return referralData[addr].children[idx];
}
function isValidReferralAddress(address addr) public view returns (bool) {
return nodesBought[addr] > 0;
}
function getNodesBoughtCountForAddress(address addr) public view returns (uint256) {
return nodesBought[addr];
}
function getDiscountedNodePrice() public view returns (uint256) {
return currentPrice.sub(currentPrice.div(100).mul(currentReferralBuyerDiscountPercentage));
}
}
|
nodes can be bought cheaper if the user uses a valid referral address set parent/child relations (only if there is no connection/parent yet available) --> this also means that a referral structure can't be changed only apply discount if referral address is valid (or as long we can step up the hierarchy) do not take node price here since it could be already dicounted set payout bonus set stats/counters step up one hierarchy level we can't find any parent - stop hierarchy calculation
|
function _buyMasternode(string memory coinsTargetAddress, bool useReferral, address referral) internal {
require(isActive, "Buying is currently deactivated.");
require(currentPrice > 0, "There was no MN price set so far.");
uint256 nodePrice = currentPrice;
if (useReferral && isValidReferralAddress(referral)) {
nodePrice = getDiscountedNodePrice();
}
require(msg.value >= nodePrice, "Sent amount of ETH was too low.");
require(length >= 30 && length <= 42 , "Coins target address invalid");
if (useReferral && isValidReferralAddress(referral)) {
require(msg.sender != referral, "You can't be your own referral.");
address parent = parentReferrals[msg.sender];
if (referralData[parent].referrals == 0) {
referralData[referral].referrals = referralData[referral].referrals.add(1);
referralData[referral].children.push(msg.sender);
parentReferrals[msg.sender] = referral;
}
address currentReferral = referral;
for (uint256 level=0; level < referralBonusMaxDepth; level++) {
if(isValidReferralAddress(currentReferral)) {
require(msg.sender != currentReferral, "Invalid referral structure (you can't be in your own tree)");
uint256 referralBonus = currentPrice.div(100).mul(currentReferralCommissionPercentages[level]);
referralBonuses[currentReferral] = referralBonuses[currentReferral].add(referralBonus);
referralData[currentReferral].bonusSum = referralData[currentReferral].bonusSum.add(referralBonus);
discountSumForThisPayment = discountSumForThisPayment.add(referralBonus);
currentReferral = parentReferrals[currentReferral];
break;
}
}
require(discountSumForThisPayment < nodePrice, "Wrong calculation of bonuses/discounts - would be higher than the price itself");
currentDiscountSum = currentDiscountSum.add(discountSumForThisPayment);
overallDiscountSum = overallDiscountSum.add(discountSumForThisPayment);
}
emit MasternodeSold(msg.sender, currentPrice, coinsTargetAddress, useReferral);
}
| 12,878,880
|
./full_match/1/0x467439207d53530505E5Eb40eDD6deBBAfF3e063/sources/Users/mario/Development/MarsGenesis/Contract/contracts/MarsGenesisAuction.sol
|
Sends donation balance to the npo addresses Only callable by the deployer
|
function sendDonations() external {
require(msg.sender == _deployerAddress, "INVALID_ROLE");
require(npoBalance > 0, "No Balance to send");
uint amount = npoBalance;
npoBalance = 0;
uint donation1 = amount / 2;
require(success1);
uint donation2 = amount - donation1;
require(success2);
}
| 2,992,103
|
pragma solidity 0.4.26;
import './IBancorNetwork.sol';
import './ContractIds.sol';
import './FeatureIds.sol';
import './converter/interfaces/IBancorConverter.sol';
import './converter/interfaces/IBancorFormula.sol';
import './converter/interfaces/IBancorGasPriceLimit.sol';
import './utility/TokenHolder.sol';
import './utility/SafeMath.sol';
import './utility/interfaces/IContractRegistry.sol';
import './utility/interfaces/IContractFeatures.sol';
import './utility/interfaces/IWhitelist.sol';
import './utility/interfaces/IAddressList.sol';
import './token/interfaces/IEtherToken.sol';
import './token/interfaces/ISmartToken.sol';
import './token/interfaces/INonStandardERC20.sol';
import './bancorx/interfaces/IBancorX.sol';
/**
* @dev The BancorNetwork contract is the main entry point for Bancor token conversions. It also allows for the conversion of any token in the Bancor Network to any other token in a single transaction by providing a conversion path.
*
* A note on Conversion Path: Conversion path is a data structure that is used when converting a token to another token in the Bancor Network when the conversion cannot necessarily be done by a single converter and might require multiple 'hops'. The path defines which converters should be used and what kind of conversion should be done in each step.
*
* The path format doesn't include complex structure; instead, it is represented by a single array in which each 'hop' is represented by a 2-tuple - smart token & to token. In addition, the first element is always the source token. The smart token is only used as a pointer to a converter (since converter addresses are more likely to change as opposed to smart token addresses).
*
* Format:
* [source token, smart token, to token, smart token, to token...]
*/
contract BancorNetwork is IBancorNetwork, TokenHolder, ContractIds, FeatureIds {
using SafeMath for uint256;
uint256 private constant CONVERSION_FEE_RESOLUTION = 1000000;
uint256 private constant AFFILIATE_FEE_RESOLUTION = 1000000;
uint256 public maxAffiliateFee = 30000; // maximum affiliate-fee
address public signerAddress = 0x0; // verified address that allows conversions with higher gas price
IContractRegistry public registry; // contract registry contract address
mapping (address => bool) public etherTokens; // list of all supported ether tokens
mapping (bytes32 => bool) public conversionHashes; // list of conversion hashes, to prevent re-use of the same hash
/**
* @dev initializes a new BancorNetwork instance
*
* @param _registry address of a contract registry contract
*/
constructor(IContractRegistry _registry) public validAddress(_registry) {
registry = _registry;
}
/**
* @dev allows the owner to update the maximum affiliate-fee
*
* @param _maxAffiliateFee maximum affiliate-fee
*/
function setMaxAffiliateFee(uint256 _maxAffiliateFee)
public
ownerOnly
{
require(_maxAffiliateFee <= AFFILIATE_FEE_RESOLUTION);
maxAffiliateFee = _maxAffiliateFee;
}
/**
* @dev allows the owner to update the contract registry contract address
*
* @param _registry address of a contract registry contract
*/
function setRegistry(IContractRegistry _registry)
public
ownerOnly
validAddress(_registry)
notThis(_registry)
{
registry = _registry;
}
/**
* @dev allows the owner to update the signer address
*
* @param _signerAddress new signer address
*/
function setSignerAddress(address _signerAddress)
public
ownerOnly
validAddress(_signerAddress)
notThis(_signerAddress)
{
signerAddress = _signerAddress;
}
/**
* @dev allows the owner to register/unregister ether tokens
*
* @param _token ether token contract address
* @param _register true to register, false to unregister
*/
function registerEtherToken(IEtherToken _token, bool _register)
public
ownerOnly
validAddress(_token)
notThis(_token)
{
etherTokens[_token] = _register;
}
/**
* @dev verifies that the signer address is trusted by recovering
* the address associated with the public key from elliptic
* curve signature, returns zero on error.
* notice that the signature is valid only for one conversion
* and expires after the give block.
*/
function verifyTrustedSender(IERC20Token[] _path, address _addr, uint256[] memory _signature) private {
uint256 blockNumber = _signature[1];
// check that the current block number doesn't exceeded the maximum allowed with the current signature
require(block.number <= blockNumber);
// create the hash of the given signature
bytes32 hash = keccak256(abi.encodePacked(blockNumber, tx.gasprice, _addr, msg.sender, _signature[0], _path));
// check that it is the first conversion with the given signature
require(!conversionHashes[hash]);
// verify that the signing address is identical to the trusted signer address in the contract
bytes32 prefixedHash = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
require(ecrecover(prefixedHash, uint8(_signature[2]), bytes32(_signature[3]), bytes32(_signature[4])) == signerAddress);
// mark the hash so that it can't be used multiple times
conversionHashes[hash] = true;
}
/**
* @dev converts the token to any other token in the bancor network by following
* a predefined conversion path and transfers the result tokens to a target account
* note that the converter should already own the source tokens
*
* @param _path conversion path, see conversion path format above
* @param _amount amount to convert from (in the initial source token)
* @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
* @param _for account that will receive the conversion result
* @param _affiliateAccount affiliate account
* @param _affiliateFee affiliate fee in PPM
*
* @return tokens issued in return
*/
function convertFor2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256) {
return convertForPrioritized4(_path, _amount, _minReturn, _for, getSignature(0x0, 0x0, 0x0, 0x0, 0x0), _affiliateAccount, _affiliateFee);
}
/**
* @dev converts the token to any other token in the bancor network
* by following a predefined conversion path and transfers the result
* tokens to a target account.
* this version of the function also allows the verified signer
* to bypass the universal gas price limit.
* note that the converter should already own the source tokens
*
* @param _path conversion path, see conversion path format above
* @param _amount amount to convert from (in the initial source token)
* @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
* @param _for account that will receive the conversion result
* @param _signature an array of the following elements:
* [0] uint256 custom value that was signed for prioritized conversion
* [1] uint256 if the current block exceeded the given parameter - it is cancelled
* [2] uint8 (signature[128:130]) associated with the signer address and helps to validate if the signature is legit
* [3] bytes32 (signature[0:64]) associated with the signer address and helps to validate if the signature is legit
* [4] bytes32 (signature[64:128]) associated with the signer address and helps to validate if the signature is legit
* if the array is empty (length == 0), then the gas-price limit is verified instead of the signature
* @param _affiliateAccount affiliate account
* @param _affiliateFee affiliate fee in PPM
*
* @return tokens issued in return
*/
function convertForPrioritized4(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn,
address _for,
uint256[] memory _signature,
address _affiliateAccount,
uint256 _affiliateFee
)
public
payable
returns (uint256)
{
// verify that the conversion parameters are legal
verifyConversionParams(_path, _for, _for, _signature);
// handle msg.value
handleValue(_path[0], _amount, false);
// convert and get the resulting amount
uint256 amount = convertByPath(_path, _amount, _minReturn, _affiliateAccount, _affiliateFee);
// finished the conversion, transfer the funds to the target account
// if the target token is an ether token, withdraw the tokens and send them as ETH
// otherwise, transfer the tokens as is
IERC20Token toToken = _path[_path.length - 1];
if (etherTokens[toToken])
IEtherToken(toToken).withdrawTo(_for, amount);
else
ensureTransfer(toToken, _for, amount);
return amount;
}
/**
* @dev converts any other token to BNT in the bancor network
* by following a predefined conversion path and transfers the resulting
* tokens to BancorX.
* note that the network should already have been given allowance of the source token (if not ETH)
*
* @param _path conversion path, see conversion path format above
* @param _amount amount to convert from (in the initial source token)
* @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
* @param _toBlockchain blockchain BNT will be issued on
* @param _to address/account on _toBlockchain to send the BNT to
* @param _conversionId pre-determined unique (if non zero) id which refers to this transaction
*
* @return the amount of BNT received from this conversion
*/
function xConvert(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn,
bytes32 _toBlockchain,
bytes32 _to,
uint256 _conversionId
)
public
payable
returns (uint256)
{
return xConvertPrioritized2(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, getSignature(0x0, 0x0, 0x0, 0x0, 0x0));
}
/**
* @dev converts any other token to BNT in the bancor network
* by following a predefined conversion path and transfers the resulting
* tokens to BancorX.
* this version of the function also allows the verified signer
* to bypass the universal gas price limit.
* note that the network should already have been given allowance of the source token (if not ETH)
*
* @param _path conversion path, see conversion path format above
* @param _amount amount to convert from (in the initial source token)
* @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
* @param _toBlockchain blockchain BNT will be issued on
* @param _to address/account on _toBlockchain to send the BNT to
* @param _conversionId pre-determined unique (if non zero) id which refers to this transaction
* @param _signature an array of the following elements:
* [0] uint256 custom value that was signed for prioritized conversion; must be equal to _amount
* [1] uint256 if the current block exceeded the given parameter - it is cancelled
* [2] uint8 (signature[128:130]) associated with the signer address and helps to validate if the signature is legit
* [3] bytes32 (signature[0:64]) associated with the signer address and helps to validate if the signature is legit
* [4] bytes32 (signature[64:128]) associated with the signer address and helps to validate if the signature is legit
* if the array is empty (length == 0), then the gas-price limit is verified instead of the signature
*
* @return the amount of BNT received from this conversion
*/
function xConvertPrioritized2(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn,
bytes32 _toBlockchain,
bytes32 _to,
uint256 _conversionId,
uint256[] memory _signature
)
public
payable
returns (uint256)
{
// verify that the custom value (if valid) is equal to _amount
require(_signature.length == 0 || _signature[0] == _amount);
// verify that the conversion parameters are legal
verifyConversionParams(_path, msg.sender, this, _signature);
// verify that the destination token is BNT
require(_path[_path.length - 1] == registry.addressOf(ContractIds.BNT_TOKEN));
// handle msg.value
handleValue(_path[0], _amount, true);
// convert and get the resulting amount
uint256 amount = convertByPath(_path, _amount, _minReturn, address(0), 0);
// transfer the resulting amount to BancorX
IBancorX(registry.addressOf(ContractIds.BANCOR_X)).xTransfer(_toBlockchain, _to, amount, _conversionId);
return amount;
}
/**
* @dev executes the actual conversion by following the conversion path
*
* @param _path conversion path, see conversion path format above
* @param _amount amount to convert from (in the initial source token)
* @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
* @param _affiliateAccount affiliate account
* @param _affiliateFee affiliate fee in PPM
*
* @return amount of tokens issued
*/
function convertByPath(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn,
address _affiliateAccount,
uint256 _affiliateFee
) private returns (uint256) {
uint256 amount = _amount;
uint256 lastIndex = _path.length - 1;
address bntToken;
if (address(_affiliateAccount) == 0) {
require(_affiliateFee == 0);
bntToken = address(0);
}
else {
require(0 < _affiliateFee && _affiliateFee <= maxAffiliateFee);
bntToken = registry.addressOf(ContractIds.BNT_TOKEN);
}
// iterate over the conversion path
for (uint256 i = 2; i <= lastIndex; i += 2) {
IBancorConverter converter = IBancorConverter(ISmartToken(_path[i - 1]).owner());
// if the smart token isn't the source (from token), the converter doesn't have control over it and thus we need to approve the request
if (_path[i - 1] != _path[i - 2])
ensureAllowance(_path[i - 2], converter, amount);
// make the conversion - if it's the last one, also provide the minimum return value
amount = converter.change(_path[i - 2], _path[i], amount, i == lastIndex ? _minReturn : 1);
// pay affiliate-fee if needed
if (address(_path[i]) == bntToken) {
uint256 affiliateAmount = amount.mul(_affiliateFee).div(AFFILIATE_FEE_RESOLUTION);
require(_path[i].transfer(_affiliateAccount, affiliateAmount));
amount -= affiliateAmount;
bntToken = address(0);
}
}
return amount;
}
bytes4 private constant GET_RETURN_FUNC_SELECTOR = bytes4(uint256(keccak256("getReturn(address,address,uint256)") >> (256 - 4 * 8)));
function getReturn(address _dest, address _fromToken, address _toToken, uint256 _amount) internal view returns (uint256, uint256) {
uint256[2] memory ret;
bytes memory data = abi.encodeWithSelector(GET_RETURN_FUNC_SELECTOR, _fromToken, _toToken, _amount);
assembly {
let success := staticcall(
gas, // gas remaining
_dest, // destination address
add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array)
mload(data), // input length (loaded from the first 32 bytes in the `data` array)
ret, // output buffer
64 // output length
)
if iszero(success) {
revert(0, 0)
}
}
return (ret[0], ret[1]);
}
/**
* @dev returns the expected return amount for converting a specific amount by following
* a given conversion path.
* notice that there is no support for circular paths.
*
* @param _path conversion path, see conversion path format above
* @param _amount amount to convert from (in the initial source token)
*
* @return expected conversion return amount and conversion fee
*/
function getReturnByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256, uint256) {
uint256 amount;
uint256 fee;
uint256 supply;
uint256 balance;
uint32 ratio;
IBancorConverter converter;
IBancorFormula formula = IBancorFormula(registry.addressOf(ContractIds.BANCOR_FORMULA));
amount = _amount;
// verify that the number of elements is larger than 2 and odd
require(_path.length > 2 && _path.length % 2 == 1);
// iterate over the conversion path
for (uint256 i = 2; i < _path.length; i += 2) {
IERC20Token fromToken = _path[i - 2];
IERC20Token smartToken = _path[i - 1];
IERC20Token toToken = _path[i];
if (toToken == smartToken) { // buy the smart token
// check if the current smart token has changed
if (i < 3 || smartToken != _path[i - 3]) {
supply = smartToken.totalSupply();
converter = IBancorConverter(ISmartToken(smartToken).owner());
}
// validate input
require(getReserveSaleEnabled(converter, fromToken));
// calculate the amount & the conversion fee
balance = converter.getConnectorBalance(fromToken);
(, ratio, , , ) = converter.connectors(fromToken);
amount = formula.calculatePurchaseReturn(supply, balance, ratio, amount);
fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION);
amount -= fee;
// update the smart token supply for the next iteration
supply += amount;
}
else if (fromToken == smartToken) { // sell the smart token
// check if the current smart token has changed
if (i < 3 || smartToken != _path[i - 3]) {
supply = smartToken.totalSupply();
converter = IBancorConverter(ISmartToken(smartToken).owner());
}
// calculate the amount & the conversion fee
balance = converter.getConnectorBalance(toToken);
(, ratio, , , ) = converter.connectors(toToken);
amount = formula.calculateSaleReturn(supply, balance, ratio, amount);
fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION);
amount -= fee;
// update the smart token supply for the next iteration
supply -= amount;
}
else { // cross reserve conversion
// check if the current smart token has changed
if (i < 3 || smartToken != _path[i - 3]) {
converter = IBancorConverter(ISmartToken(smartToken).owner());
}
(amount, fee) = getReturn(converter, fromToken, toToken, amount);
}
}
return (amount, fee);
}
/**
* @dev claims the caller's tokens, converts them to any other token in the bancor network
* by following a predefined conversion path and transfers the result tokens to a target account
* note that allowance must be set beforehand
*
* @param _path conversion path, see conversion path format above
* @param _amount amount to convert from (in the initial source token)
* @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
* @param _for account that will receive the conversion result
* @param _affiliateAccount affiliate account
* @param _affiliateFee affiliate fee in PPM
*
* @return tokens issued in return
*/
function claimAndConvertFor2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _for, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256) {
// we need to transfer the tokens from the caller to the converter before we follow
// the conversion path, to allow it to execute the conversion on behalf of the caller
// note: we assume we already have allowance
IERC20Token fromToken = _path[0];
ensureTransferFrom(fromToken, msg.sender, this, _amount);
return convertFor2(_path, _amount, _minReturn, _for, _affiliateAccount, _affiliateFee);
}
/**
* @dev converts the token to any other token in the bancor network by following
* a predefined conversion path and transfers the result tokens back to the sender
* note that the converter should already own the source tokens
*
* @param _path conversion path, see conversion path format above
* @param _amount amount to convert from (in the initial source token)
* @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
* @param _affiliateAccount affiliate account
* @param _affiliateFee affiliate fee in PPM
*
* @return tokens issued in return
*/
function convert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public payable returns (uint256) {
return convertFor2(_path, _amount, _minReturn, msg.sender, _affiliateAccount, _affiliateFee);
}
/**
* @dev claims the caller's tokens, converts them to any other token in the bancor network
* by following a predefined conversion path and transfers the result tokens back to the sender
* note that allowance must be set beforehand
*
* @param _path conversion path, see conversion path format above
* @param _amount amount to convert from (in the initial source token)
* @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero
* @param _affiliateAccount affiliate account
* @param _affiliateFee affiliate fee in PPM
*
* @return tokens issued in return
*/
function claimAndConvert2(IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee) public returns (uint256) {
return claimAndConvertFor2(_path, _amount, _minReturn, msg.sender, _affiliateAccount, _affiliateFee);
}
/**
* @dev ensures transfer of tokens, taking into account that some ERC-20 implementations don't return
* true on success but revert on failure instead
*
* @param _token the token to transfer
* @param _to the address to transfer the tokens to
* @param _amount the amount to transfer
*/
function ensureTransfer(IERC20Token _token, address _to, uint256 _amount) private {
IAddressList addressList = IAddressList(registry.addressOf(ContractIds.NON_STANDARD_TOKEN_REGISTRY));
if (addressList.listedAddresses(_token)) {
uint256 prevBalance = _token.balanceOf(_to);
// we have to cast the token contract in an interface which has no return value
INonStandardERC20(_token).transfer(_to, _amount);
uint256 postBalance = _token.balanceOf(_to);
assert(postBalance > prevBalance);
} else {
// if the token isn't whitelisted, we assert on transfer
assert(_token.transfer(_to, _amount));
}
}
/**
* @dev ensures transfer of tokens, taking into account that some ERC-20 implementations don't return
* true on success but revert on failure instead
*
* @param _token the token to transfer
* @param _from the address to transfer the tokens from
* @param _to the address to transfer the tokens to
* @param _amount the amount to transfer
*/
function ensureTransferFrom(IERC20Token _token, address _from, address _to, uint256 _amount) private {
IAddressList addressList = IAddressList(registry.addressOf(ContractIds.NON_STANDARD_TOKEN_REGISTRY));
if (addressList.listedAddresses(_token)) {
uint256 prevBalance = _token.balanceOf(_to);
// we have to cast the token contract in an interface which has no return value
INonStandardERC20(_token).transferFrom(_from, _to, _amount);
uint256 postBalance = _token.balanceOf(_to);
assert(postBalance > prevBalance);
} else {
// if the token isn't whitelisted, we assert on transfer
assert(_token.transferFrom(_from, _to, _amount));
}
}
/**
* @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't.
* Note that we use the non standard erc-20 interface in which `approve` has no return value so that
* this function will work for both standard and non standard tokens
*
* @param _token token to check the allowance in
* @param _spender approved address
* @param _value allowance amount
*/
function ensureAllowance(IERC20Token _token, address _spender, uint256 _value) private {
// check if allowance for the given amount already exists
if (_token.allowance(this, _spender) >= _value)
return;
// if the allowance is nonzero, must reset it to 0 first
if (_token.allowance(this, _spender) != 0)
INonStandardERC20(_token).approve(_spender, 0);
// approve the new allowance
INonStandardERC20(_token).approve(_spender, _value);
}
/**
* @dev returns true if reserve sale is enabled
*
* @param _converter converter contract address
* @param _reserve reserve's address to read from
*
* @return true if reserve sale is enabled, otherwise - false
*/
function getReserveSaleEnabled(IBancorConverter _converter, IERC20Token _reserve)
private
view
returns(bool)
{
bool isSaleEnabled;
(, , , isSaleEnabled, ) = _converter.connectors(_reserve);
return isSaleEnabled;
}
function getSignature(
uint256 _customVal,
uint256 _block,
uint8 _v,
bytes32 _r,
bytes32 _s
) private pure returns (uint256[] memory) {
if (_v == 0x0 && _r == 0x0 && _s == 0x0)
return new uint256[](0);
uint256[] memory signature = new uint256[](5);
signature[0] = _customVal;
signature[1] = _block;
signature[2] = uint256(_v);
signature[3] = uint256(_r);
signature[4] = uint256(_s);
return signature;
}
function verifyConversionParams(
IERC20Token[] _path,
address _sender,
address _receiver,
uint256[] memory _signature
)
private
{
// verify that the number of elements is odd and that maximum number of 'hops' is 10
require(_path.length > 2 && _path.length <= (1 + 2 * 10) && _path.length % 2 == 1);
// verify that the account which should receive the conversion result is whitelisted
IContractFeatures features = IContractFeatures(registry.addressOf(ContractIds.CONTRACT_FEATURES));
for (uint256 i = 1; i < _path.length; i += 2) {
IBancorConverter converter = IBancorConverter(ISmartToken(_path[i]).owner());
if (features.isSupported(converter, FeatureIds.CONVERTER_CONVERSION_WHITELIST)) {
IWhitelist whitelist = converter.conversionWhitelist();
require (whitelist == address(0) || whitelist.isWhitelisted(_receiver));
}
}
if (_signature.length >= 5) {
// verify signature
verifyTrustedSender(_path, _sender, _signature);
}
else {
// verify gas price limit
IBancorGasPriceLimit gasPriceLimit = IBancorGasPriceLimit(registry.addressOf(ContractIds.BANCOR_GAS_PRICE_LIMIT));
gasPriceLimit.validateGasPrice(tx.gasprice);
}
}
function handleValue(IERC20Token _token, uint256 _amount, bool _claim) private {
// if ETH is provided, ensure that the amount is identical to _amount, verify that the source token is an ether token and deposit the ETH in it
if (msg.value > 0) {
require(_amount == msg.value && etherTokens[_token]);
IEtherToken(_token).deposit.value(msg.value)();
}
// Otherwise, claim the tokens from the sender if needed
else if (_claim) {
ensureTransferFrom(_token, msg.sender, this, _amount);
}
}
/**
* @dev deprecated, backward compatibility
*/
function convert(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn
) public payable returns (uint256)
{
return convert2(_path, _amount, _minReturn, address(0), 0);
}
/**
* @dev deprecated, backward compatibility
*/
function claimAndConvert(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn
) public returns (uint256)
{
return claimAndConvert2(_path, _amount, _minReturn, address(0), 0);
}
/**
* @dev deprecated, backward compatibility
*/
function convertFor(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn,
address _for
) public payable returns (uint256)
{
return convertFor2(_path, _amount, _minReturn, _for, address(0), 0);
}
/**
* @dev deprecated, backward compatibility
*/
function claimAndConvertFor(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn,
address _for
) public returns (uint256)
{
return claimAndConvertFor2(_path, _amount, _minReturn, _for, address(0), 0);
}
/**
* @dev deprecated, backward compatibility
*/
function xConvertPrioritized(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn,
bytes32 _toBlockchain,
bytes32 _to,
uint256 _conversionId,
uint256 _block,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
payable
returns (uint256)
{
// workaround the 'stack too deep' compilation error
uint256[] memory signature = getSignature(_amount, _block, _v, _r, _s);
return xConvertPrioritized2(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, signature);
// return xConvertPrioritized2(_path, _amount, _minReturn, _toBlockchain, _to, _conversionId, getSignature(_amount, _block, _v, _r, _s));
}
/**
* @dev deprecated, backward compatibility
*/
function convertForPrioritized3(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn,
address _for,
uint256 _customVal,
uint256 _block,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
payable
returns (uint256)
{
return convertForPrioritized4(_path, _amount, _minReturn, _for, getSignature(_customVal, _block, _v, _r, _s), address(0), 0);
}
/**
* @dev deprecated, backward compatibility
*/
function convertForPrioritized2(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn,
address _for,
uint256 _block,
uint8 _v,
bytes32 _r,
bytes32 _s
)
public
payable
returns (uint256)
{
return convertForPrioritized4(_path, _amount, _minReturn, _for, getSignature(_amount, _block, _v, _r, _s), address(0), 0);
}
/**
* @dev deprecated, backward compatibility
*/
function convertForPrioritized(
IERC20Token[] _path,
uint256 _amount,
uint256 _minReturn,
address _for,
uint256 _block,
uint256 _nonce,
uint8 _v,
bytes32 _r,
bytes32 _s)
public payable returns (uint256)
{
_nonce;
return convertForPrioritized4(_path, _amount, _minReturn, _for, getSignature(_amount, _block, _v, _r, _s), address(0), 0);
}
}
|
ensures transfer of tokens, taking into account that some ERC-20 implementations don't return true on success but revert on failure instead _token the token to transfer _from the address to transfer the tokens from _to the address to transfer the tokens to _amount the amount to transfer/
|
function ensureTransferFrom(IERC20Token _token, address _from, address _to, uint256 _amount) private {
IAddressList addressList = IAddressList(registry.addressOf(ContractIds.NON_STANDARD_TOKEN_REGISTRY));
if (addressList.listedAddresses(_token)) {
uint256 prevBalance = _token.balanceOf(_to);
INonStandardERC20(_token).transferFrom(_from, _to, _amount);
uint256 postBalance = _token.balanceOf(_to);
assert(postBalance > prevBalance);
assert(_token.transferFrom(_from, _to, _amount));
}
} else {
}
| 6,425,822
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* GEN.ART Collection Contract
*/
interface IGenArt {
function getTokensByOwner(address owner)
external
view
returns (uint256[] memory);
function ownerOf(uint256 tokenId) external view returns (address);
function isGoldToken(uint256 _tokenId) external view returns (bool);
}
interface IGenArtInterface {
function getMaxMintForMembership(uint256 _membershipId)
external
view
returns (uint256);
function getMaxMintForOwner(address owner) external view returns (uint256);
function upgradeGenArtTokenContract(address _genArtTokenAddress) external;
function setAllowGen(bool allow) external;
function genAllowed() external view returns (bool);
function isGoldToken(uint256 _membershipId) external view returns (bool);
function transferFrom(
address _from,
address _to,
uint256 _amount
) external;
function balanceOf(address _owner) external view returns (uint256);
function ownerOf(uint256 _membershipId) external view returns (address);
}
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
/**
* @dev 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 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);
}
}
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
/**
* @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 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;
}
}
// 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;
}
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title 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);
}
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
/**
* @dev 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;
}
}
/**
* @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;
}
/**
* @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);
}
/**
* @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);
}
/**
* @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 GenArtCollection is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable,
Ownable
{
using Address for address;
using Strings for uint256;
using Counters for Counters.Counter;
using SafeMath for uint256;
struct Collection {
uint256 tier;
uint256 invocations;
uint256 maxInvocations;
string script;
uint256 price;
uint256 priceGen;
uint256 artistPercentage;
address artist;
}
event Mint(address to, uint256 collectionId, uint256 tokenId, bytes32 hash);
// IGenArtMintState _genArtMintState;
mapping(uint256 => Collection) private _collectionsMap;
// Mapping collectionId to membershipId and total mints
mapping(uint256 => mapping(uint256 => uint256)) private _collectionsMintMap;
mapping(uint256 => bytes32) private _tokenIdToHashMap;
mapping(uint256 => uint256) private _tokenIdToCollectionIdMap;
Counters.Counter private _collectionIdCounter;
IGenArtInterface private _genArtInterface;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Base URI
string private _baseURI;
// 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;
// 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 Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(
string memory name_,
string memory symbol_,
string memory uri_,
address genArtInterfaceAddress_
) {
_name = name_;
_symbol = symbol_;
_baseURI = uri_;
_genArtInterface = IGenArtInterface(genArtInterfaceAddress_);
_collectionIdCounter.increment();
}
modifier onlyArtist(uint256 _collectionId) {
require(
_collectionsMap[_collectionId].artist == _msgSender(),
"GenArtCollection: only artist can call this function"
);
_;
}
function withdraw(uint256 value) public onlyOwner {
address _owner = owner();
payable(_owner).transfer(value);
}
function createGenCollection(
address _artist,
uint256 _artistPercentage,
uint256 _price,
uint256 _priceGen,
uint256 _maxInvocations,
uint256 _tier,
string memory _script
) public onlyOwner {
uint256 _collectionId = _collectionIdCounter.current();
_collectionsMap[_collectionId] = Collection({
tier: _tier,
invocations: 0,
maxInvocations: _maxInvocations,
script: _script,
price: _price,
priceGen: _priceGen,
artistPercentage: _artistPercentage,
artist: _artist
});
_collectionIdCounter.increment();
}
function checkMint(
address _sender,
uint256 _collectionId,
uint256 _membershipId,
uint256 _value,
uint256 _amount,
bool _isEthPayment
) internal virtual {
require(
_collectionsMap[_collectionId].tier != 0,
"GenArtCollection: incorrect collection id"
);
require(
_collectionsMap[_collectionId].invocations <
_collectionsMap[_collectionId].maxInvocations,
"GenArtCollection: max invocations was reached"
);
address _membershipOwner = _genArtInterface.ownerOf(_membershipId);
require(
_membershipOwner == _sender,
"GenArtCollection: sender must be membership owner"
);
bool _isGoldMember = _genArtInterface.isGoldToken(_membershipId);
uint256 _tier = _isGoldMember ? 2 : 1;
require(
_collectionsMap[_collectionId].tier == 3 ||
_collectionsMap[_collectionId].tier == _tier,
"GenArtCollection: no valid membership"
);
uint256 maxMint = getAllowedMintForMembership(
_collectionId,
_membershipId
);
require(
maxMint >= _amount,
"GenArtCollection: no mints avaliable"
);
if (_isEthPayment) {
require(
_collectionsMap[_collectionId].price.mul(_amount) <= _value,
"GenArtCollection: incorrect amount sent"
);
} else {
require(
_collectionsMap[_collectionId].priceGen.mul(_amount) <= _value,
"GenArtCollection: insufficient $GEN balance"
);
}
}
function mint(
address _to,
uint256 _collectionId,
uint256 _membershipId
) public payable {
checkMint(msg.sender, _collectionId, _membershipId, msg.value, 1, true);
updateMintState(_collectionId, _membershipId, 1);
_mintOne(_to, _collectionId);
splitFunds(msg.sender, _collectionId, 1, true);
}
function mintGen(
address _to,
uint256 _collectionId,
uint256 _membershipId
) public {
bool _genAllowed = _genArtInterface.genAllowed();
require(_genAllowed, "Mint with $GENART not allowed");
uint256 balance = _genArtInterface.balanceOf(msg.sender);
checkMint(msg.sender, _collectionId, _membershipId, balance, 1, false);
updateMintState(_collectionId, _membershipId, 1);
_mintOne(_to, _collectionId);
splitFunds(msg.sender, _collectionId, 1, false);
}
function mintMany(
address _to,
uint256 _collectionId,
uint256 _membershipId,
uint256 _amount
) public payable {
checkMint(
msg.sender,
_collectionId,
_membershipId,
msg.value,
_amount,
true
);
updateMintState(_collectionId, _membershipId, _amount);
_mintMany(_to, _collectionId, _amount);
splitFunds(msg.sender, _collectionId, _amount, true);
}
function mintManyGen(
address _to,
uint256 _collectionId,
uint256 _membershipId,
uint256 _amount
) public {
bool _genAllowed = _genArtInterface.genAllowed();
require(_genAllowed, "Mint with $GENART not allowed");
uint256 balance = _genArtInterface.balanceOf(msg.sender);
checkMint(
msg.sender,
_collectionId,
_membershipId,
balance,
_amount,
false
);
updateMintState(_collectionId, _membershipId, _amount);
_mintMany(_to, _collectionId, _amount);
splitFunds(msg.sender, _collectionId, _amount, false);
}
function _mintMany(
address _to,
uint256 _collectionId,
uint256 _amount
) internal virtual {
for (uint256 i = 0; i < _amount; i++) {
_mintOne(_to, _collectionId);
}
}
function _mintOne(address _to, uint256 _collectionId) internal virtual {
uint256 invocation = _collectionsMap[_collectionId].invocations + 1;
uint256 _tokenId = _collectionId * 100000 + invocation;
_collectionsMap[_collectionId].invocations = invocation;
bytes32 hash = keccak256(
abi.encodePacked(invocation, block.number, block.difficulty, _to)
);
_tokenIdToHashMap[_tokenId] = hash;
_tokenIdToCollectionIdMap[_tokenId] = _collectionId;
_safeMint(_to, _tokenId);
emit Mint(_to, _collectionId, _tokenId, hash);
}
function splitFunds(
address _sender,
uint256 _collectionId,
uint256 _amount,
bool _isEthPayment
) internal virtual {
uint256 value = _isEthPayment
? _collectionsMap[_collectionId].price.mul(_amount)
: _collectionsMap[_collectionId].priceGen.mul(_amount);
address _owner = owner();
uint256 artistReward = (value *
_collectionsMap[_collectionId].artistPercentage) / 100;
if (_isEthPayment) {
payable(_collectionsMap[_collectionId].artist).transfer(
artistReward
);
} else {
_genArtInterface.transferFrom(
_sender,
_owner,
value - artistReward
);
_genArtInterface.transferFrom(
_sender,
_collectionsMap[_collectionId].artist,
artistReward
);
}
}
function burn(uint256 _tokenId) public {
_burn(_tokenId);
}
function getAllowedMintForMembership(
uint256 _collectionId,
uint256 _membershipId
) public view returns (uint256) {
uint256 maxMint = _genArtInterface.getMaxMintForMembership(
_membershipId
);
return maxMint - _collectionsMintMap[_collectionId][_membershipId];
}
function updateMintState(
uint256 _collectionId,
uint256 _membershipId,
uint256 _amount
) internal virtual {
_collectionsMintMap[_collectionId][_membershipId] =
_collectionsMintMap[_collectionId][_membershipId] +
_amount;
}
function updateArtistAddress(uint256 _collectionId, address _artist)
public
onlyArtist(_collectionId)
{
_collectionsMap[_collectionId].artist = _artist;
}
function updateMaxInvocations(
uint256 _collectionId,
uint256 _maxInvocations
) public onlyOwner {
_collectionsMap[_collectionId].maxInvocations = _maxInvocations;
}
function updateScript(uint256 _collectionId, string memory _script)
public
onlyOwner
{
_collectionsMap[_collectionId].script = _script;
}
function upgradeGenArtInterfaceContract(address _genArtInterfaceAddress)
public
onlyOwner
{
_genArtInterface = IGenArtInterface(_genArtInterfaceAddress);
}
function updatePrice(
uint256 _collectionId,
uint256 _price,
uint256 _priceGen
) public onlyOwner {
_collectionsMap[_collectionId].price = _price;
_collectionsMap[_collectionId].priceGen = _priceGen;
}
function getCollectionInfo(uint256 _collectionId)
public
view
returns (
uint256 invocations,
uint256 maxInvocations,
string memory script,
uint256 price,
uint256 priceGen,
address artist,
uint256 artistPercentage
)
{
require(
_collectionsMap[_collectionId].tier != 0,
"GenArtCollection: invalid collection id"
);
return (
_collectionsMap[_collectionId].invocations,
_collectionsMap[_collectionId].maxInvocations,
_collectionsMap[_collectionId].script,
_collectionsMap[_collectionId].price,
_collectionsMap[_collectionId].priceGen,
_collectionsMap[_collectionId].artist,
_collectionsMap[_collectionId].artistPercentage
);
}
function getTokenInfo(uint256 _tokenId)
public
view
returns (
uint256,
uint256,
address,
bytes32
)
{
_exists(_tokenId);
bytes32 hash = _tokenIdToHashMap[_tokenId];
uint256 _collectionId = _tokenIdToCollectionIdMap[_tokenId];
address owner = GenArtCollection.ownerOf(_tokenId);
return (_tokenId, _collectionId, owner, hash);
}
function getTokensByOwner(address _owner)
public
view
returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_owner);
uint256[] memory tokenIds = new uint256[](tokenCount);
for (uint256 i; i < tokenCount; i++) {
tokenIds[i] = tokenOfOwnerByIndex(_owner, i);
}
return tokenIds;
}
/**
* @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 ||
interfaceId == type(IERC721Enumerable).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 _baseURI;
}
/**
* @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_) public onlyOwner {
_baseURI = baseURI_;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = GenArtCollection.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 = GenArtCollection.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 = GenArtCollection.ownerOf(tokenId);
require(
_msgSender() == owner,
"GenArtCollection: only token owner can burn"
);
_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(
GenArtCollection.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(GenArtCollection.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 See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
require(
index < GenArtCollection.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 < GenArtCollection.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 {
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 = GenArtCollection.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 = GenArtCollection.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();
}
}
|
Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Clear approvals
|
function _burn(uint256 tokenId) internal virtual {
address owner = GenArtCollection.ownerOf(tokenId);
require(
_msgSender() == owner,
"GenArtCollection: only token owner can burn"
);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
| 5,773,415
|
./full_match/5/0x8Fe4d94ef5fC4c61DDb2c050653b4664Fcfa3C07/sources/project_/contracts/TellorFlex.sol
|
Returns total amount of token staked for reporting return uint256 total amount of token staked/
|
function getTotalStakeAmount() external view returns (uint256) {
return totalStakeAmount;
}
| 7,079,484
|
./full_match/80001/0x9e931a143eC263C2eF9302ca6D859F80751f6941/sources/contracts/upgradeable/tokens/Stations.sol
|
solhint-disable-next-line ordering
|
function registerToken(MetadataParams memory _md)
public
onlyRole(ADMIN_ROLE)
requireValidMetadata(_md)
whenNotPaused
{
uint256 _id = nextTokenId;
metadata[_id] = _md;
nextTokenId++;
emit NewToken(_id, _md.props.country, _md.props.city);
}
| 5,641,150
|
// SPDX-License-Identifier: Apache-2.0
pragma solidity >=0.6.4 <0.8.0;
pragma experimental ABIEncoderV2;
import "https://github.com/vigilance91/solidarity/contracts/token/mortal/ERC20/MortalERC20BurnableToken.sol";
import "https://github.com/vigilance91/solidarity/contracts/token/TokenSupply/supplyCap/MutableSupplyCapABC.sol";
import "https://github.com/vigilance91/solidarity/contracts/accessControl/PausableAccessControl.sol";
import "https://github.com/vigilance91/solidarity/contracts/token/TokenSupply/supplyCap/iMutableSupplyCap.sol";
//interface iSafeERC20MutableCapMint is iERC20,
// iPausable
//{
//}
///
/// @title Safe ERC20 Token Mint
/// @author Tyler R. Drury <vigilstudios.td@gmail.com> (www.twitter.com/StudiosVigil) - copyright 6/5/2021, All Rights Reserved
/// @dev Generic ERC20 compliant token mint which is pausable, with an uncapped, dynamic (mutable) supply,
/// capable of permissioned minting and burning of tokens by addresses designated with minter and burner roles
///
abstract contract MortalERC20Mint is MortalERC20BurnableToken,
PausableAccessControl
{
using SafeMath for uint256;
//using LogicConstraints for bool;
using AddressLogic for address;
//using uint256Constraints for uint256;
//using stringUtilities for string;
bytes32 public constant ROLE_MINTER = keccak256("MortalPermissionERC20Mint.ROLE_MINTER");
bytes32 public constant ROLE_BURNER = keccak256("MortalPermissionERC20Mint.ROLE_BURNER");
//string private constant _NAME = ' MortalERC20MutableCapMint: ';
///
/// @dev explicitly prevent proxying
/// NOTE:
/// since this contracts methods are external with ReentrancyGuard, not public,
/// this will automatically prevent proxying but cauases obscure and hard to track down errors
/// so, simply prevent proxying here and any attempt to call a function not declared in this implementation
/// will always revert here, no need to figure out issues with function visibility, modifiers, execution context, etc
///
//fallback(
//)external view nonReentrant payable{
//LogicConstraints.alwaysRevert('proxying disabled');
//}
// note: derived contracts may optionally implement iEtherReceiver/iEtherTransactor, etc,
// as desired or simply declare {receive()} to accept payments of ETH to this contract
// this is neccessary if the inheriting contract must pay ETH for external transactions to
// other contracts or wallet addresses
constructor(
string memory name,
string memory symbol,
//string memory version,
uint256 initialSupply
)internal
//ERC20AccessControlToken(name,symbol,0)
MortalERC20BurnableToken(
name,
symbol
)
PausableAccessControl()
{
//tokenCap.requireGreaterThanOrEqual(
//initialSupply,
//_NAME.concatenate("initial supply > cap")
//);
address sender = _msgSender();
_setupRole(ROLE_MINTER, sender);
_setupRole(ROLE_BURNER, sender);
//_registerInterface(type(iSafeERC20Mint).interfaceId);
if(initialSupply > 0){
_mint(sender, initialSupply);
}
}
///
/// @dev Creates `amount` new tokens for `to`
/// See {ERC20._mint}
///
/// Requirements:
/// - the caller must have the `MINTER_ROLE`
///
function mint(
address to,
uint256 amount
)external virtual nonReentrant
//onlyRole(MINTER_ROLE)
{
require(
hasRole(ROLE_MINTER, _msgSender())
//_NAME.concatenate("must have minter role to mint")
);
_mint(to, amount);
}
///
/// @dev caller destroys `amount` of their tokens
/// See {ERC20._burn}
///
/// Requirements:
/// - `amount` must be non-zero
/// - caller's balance must be at least `amount`
///
function burn(
uint256 amount
)external virtual override nonReentrant
{
address sender = _msgSender();
require(
hasRole(ROLE_BURNER, sender)
//_NAME.concatenate("must have minter role to mint")
);
_burn(
sender,
amount
);
}
///
/// @dev caller destroys `amount` of `account`'s tokens,
/// deducting from the caller's allowance
/// See {ERC20._burn} and {ERC20.allowance}
///
/// Requirements:
/// - caller can not be `account`
/// - `account` can not be null address
/// - `amount` must be non-zero
/// - `account` must have previously granted caller an allowance of at least `amount` tokens
///
function burnFrom(
address account,
uint256 amount
)external virtual override nonReentrant
{
address sender = _msgSender();
require(
hasRole(ROLE_BURNER, sender)
//_NAME.concatenate("must have minter role to mint")
);
sender.requireNotEqual(account);
uint256 A = _allowance(
account,
sender
);
//_requireAllowanceGreaterThanOrEqual(amount);
A.requireGreaterThanZero(
//'zero allowance available'
);
A.requireGreaterThanOrEqual(amount);
//_decreasedAllowance(account, sender, amount);
_approve(
account,
sender,
A.sub(
amount,
"burn amount exceeds allowance"
)
);
_burn(
account,
amount
);
}
///
/// @dev See {ERC20._beforeTokenTransfer}
///
/// Requirements:
/// - the contract must not be paused
///
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
)internal virtual override
//whenNotPaused()
{
require(
!paused()
//_NAME.concatenate("paused")
);
super._beforeTokenTransfer(
from,
to,
amount
);
}
/**
///
/// @dev transfer ownership and any roles the owner has to the new owner, otherwise,
/// the previous owner would retain their privellages and be able to undermine the new owner,
/// such as by forcing the mint to pause, minting/burning tokens or performing other admin only functions
/// which they should not be entitled to anymore since they are not the contract's owner
///
/// note:
/// renounceOwnership does NOT revoke any assigned roles, only transfering
///
//function transferOwnership(
//)external virtual override onlyOwner nonReentrant
//{
//if(){
//}
//super.transferOwnership(newOwner);
//}
//function safeTransferOwnership(
//)virtual override
//{
//if(){
//}
//super.safeTransferOwnership(newOwner);
//}
function externalSafeTransferOwnership(
address ownable,
address newOwner
)external virtual override onlyOwner nonReentrant
{
_safeTransferOwnership(ownable, newOwner);
}
/// @dev like _safeTransferOwnership but exclusively transfers ownership of `ownable` contract address to this contract's owner,
///
/// Requirements:
/// * this contract's owner must not be null, otherwise call _safeRenounceOwnership
/// * `ownable` must not already be this contract's owner
///
function safeTransferOwnershipToThisOwner(
address ownable
)external virtual override onlyOwner nonReentrant
{
//address O = owner();
//address _this = address(this);
if(hasRole(ROLE_PAUSER), _this){
_transferRole(ROLE_PAUSER, _this, O);
}
if(hasRole(ROLE_MINTER), _this){
_transferRole(ROLE_MINTER, _this, O);
}
if(hasRole(ROLE_BURNER), _this){
_transferRole(ROLE_BURNER, _this, O);
}
_safeTransferOwnershipToThisOwner(ownable);
}
///
/// @dev this contract renounces ownership of `ownable`, only if this contract is `ownable`s owner,
/// otherwise transaction will revert
///
function externalSafeRenounceOwnership(
address ownable
)external virtual override onlyOwner nonReentrant
{
_safeRenounceOwnership(ownable);
}
*/
}
|
this contract renounces ownership of `ownable`, only if this contract is `ownable`s owner, otherwise transaction will revert
|
function externalSafeRenounceOwnership(
address ownable
)external virtual override onlyOwner nonReentrant
{
_safeRenounceOwnership(ownable);
}
| 12,750,961
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.4;
import "@chainlink/contracts/src/v0.8/VRFConsumerBase.sol";
import "@openzeppelin/contracts/security/Pausable.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/token/ERC1155/utils/ERC1155Holder.sol";
import "@openzeppelin/contracts/token/ERC1155/IERC1155.sol";
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
// Cryptogs Reborn Game contract v0.3
// updated by 0xAA, 2022, 03, 13
// Development / Design / Coordination :@cosmoburn, @0xAA_Science, @deepe_eth, @steve0xp, TylerS, @beastadon, @OrHalldor, @Thisisnottap
contract CryptogsGame is ERC1155Holder, VRFConsumerBase, Pausable, Ownable {
struct Game {
uint gameState;
address creator;
address opponent;
uint256[] creatorTogs;
uint256[] creatorTogsAmount;
uint256[] opponentTogs;
uint256[] opponentTogsAmount;
uint256 expirationBlock;
bool withdrawed;
}
mapping(uint256 => Game) public games;
uint256 public gameId = 0;
// CryptogsReborn NFT address on Polygon
address public CryptogsAddress;
IERC1155 Cryptogs;
// The number of blocks that can pass until the opponent can no longer call playGame(), update to 25 blocks (~ 6 mins)
uint256 blocksUntilExpiration = 25;
// Chainlink VRF
bytes32 internal keyHash;
uint256 internal fee;
mapping(bytes32 => uint256) private _vrfRequestIdToGameId;
// constructor
/**
* Constructor inherits VRFConsumerBase
*
* Network: Polygon
* Chainlink VRF Coordinator address: 0x3d2341ADb2D31f1c5530cDC622016af293177AE0
* LINK token address: 0xb0897686c545045aFc77CF20eC7A532E3120E0F1
* Key Hash: 0xf86195cf7690c55907b2b611ebb7343a6f649bff128701cc542f0569e2c549da
*/
// 0xAA update: keyHash is no longer hardcoded, and add cryptogs contract address to verify the crytogs NFTs are legit.
constructor(address _vrfCoordinator, address _linkToken, bytes32 _keyHash, address _Cryptogs)
VRFConsumerBase(_vrfCoordinator, _linkToken)
{
keyHash = _keyHash;
fee = 0.0001 * 10 ** 18; // 0.0001 LINK (on polygon network)
CryptogsAddress = _Cryptogs; // set cryptogsReborn contract address
Cryptogs = IERC1155(_Cryptogs);
}
// function to get sum of array
function getArraySum(uint256[] memory _array)
public
pure
returns (uint256 sum_)
{
sum_ = 0;
for (uint i = 0; i < _array.length; i++) {
sum_ += _array[i];
}
}
// function to flatten a ERC1155 (tokenId, amount) array
function getArraySum(uint256[] memory _tokenId, uint256[] memory _amount) public pure returns (uint256[] memory , uint256[] memory ){
require(_tokenId.length == _amount.length);
uint j = 0;
uint256[] memory flatId = new uint256[](getArraySum(_amount));
uint256[] memory flatAmount = new uint256[](getArraySum(_amount));
for (uint i = 0; i < _tokenId.length; i++){
while(_amount[i] != 0){
flatId[j] = _tokenId[i];
flatAmount[j] =1;
_amount[i] -=1;
j += 1;
}
}
return(flatId, flatAmount);
}
// gameInit event: player 0 set up the game
event gameInit(uint256 indexed GameId, address indexed Creator, uint256 indexed ExpirationBlock);
// player 0 init Game
function initGame(uint256[] calldata _creatorTogs, uint256[] calldata _amounts) public {
require(_creatorTogs.length == _amounts.length);
require(_creatorTogs.length <= 5);
require(getArraySum(_amounts) == 5);
// transfer 5 Pogs to game
Cryptogs.safeBatchTransferFrom(_msgSender(), address(this), _creatorTogs, _amounts, "");
// set gameState to 1: initGame state
uint gameState = 1;
uint256 expirationBlock = block.number + blocksUntilExpiration;
uint256[] memory tmp0 = new uint256[](5);
uint256[] memory tmp1 = new uint256[](5);
// create game struct
Game memory game0 = Game({
gameState: gameState,
creator: _msgSender(),
opponent: address(0),
creatorTogs: _creatorTogs,
creatorTogsAmount: _amounts,
opponentTogs: tmp0,
opponentTogsAmount: tmp1,
expirationBlock: expirationBlock,
withdrawed: false
});
// push current game to array
games[gameId] = game0;
emit gameInit(gameId, _msgSender(), expirationBlock);
gameId += 1;
}
// gameJoin event: player 1 joins the game
event gameJoin(uint256 indexed GameId, address indexed Player0, address indexed Player1, bytes32 RequestId);
// player 1 join Game
function joinPlay(uint256 _gameId, uint256[] calldata _joinTogs, uint256[] calldata _amounts) public {
require(_gameId <= gameId);
require(games[_gameId].gameState == 1); // game state check
require(block.number <= games[_gameId].expirationBlock); // game not expiration
require(_joinTogs.length == _amounts.length); // two array have same length
require(_joinTogs.length <= 5);
require(getArraySum(_amounts) == 5); // transfer amount = 5
require(games[_gameId].creator != _msgSender()); // player0 != player1
require(LINK.balanceOf(address(this)) >= fee, "Not enough LINK");
// fill opponent information to game
Game storage game0 = games[_gameId];
game0.opponent = _msgSender();
game0.opponentTogs = _joinTogs;
game0.opponentTogsAmount = _amounts;
game0.gameState = 2; // change game state to 2: finished
// SLAMMER TIME!
// get random number
bytes32 requestId = requestRandomness(keyHash, fee);
_vrfRequestIdToGameId[requestId] = _gameId;
emit gameJoin(_gameId, game0.creator, _msgSender(), requestId);
}
event flipTogs(uint256 indexed GameId, address indexed Player0, address indexed Player1, uint256[] FlippedTogs, uint256[] AmountPlayer0, uint256[] AmountPlayer1);
// Once chainlink VRF generates a random number, this function will be called automatically to transfer flipped togs to players.
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
// get gameId by vrf requestId
uint256 _gameId = _vrfRequestIdToGameId[requestId];
// get game object
Game storage game0 = games[_gameId];
uint256 sumAmount = getArraySum(game0.creatorTogsAmount)+ getArraySum(game0.opponentTogsAmount);
// flipped togs
uint256[] memory flippedTogs = new uint256[](sumAmount);
uint256[] memory amountPlayer0 = new uint256[](sumAmount);
uint256[] memory amountPlayer1 = new uint256[](sumAmount);
uint256 _rand;
uint256 j = 0;
// flip togs of player 0
for (uint256 i = 0; i < game0.creatorTogs.length; i++) {
while(game0.creatorTogsAmount[i] != 0){
_rand = uint256(keccak256(abi.encode(randomness, j))) % 2;
flippedTogs[j] = game0.creatorTogs[i];
if(_rand == 0){
amountPlayer0[j] =1;
}else{
amountPlayer1[j] =1;
}
game0.creatorTogsAmount[i] -=1;
j += 1;
}
}
// flip togs of player 1
for (uint256 i = 0; i < game0.opponentTogs.length; i++) {
while(game0.opponentTogsAmount[i] != 0){
_rand = uint256(keccak256(abi.encode(randomness, j))) % 2;
flippedTogs[j] = game0.opponentTogs[i];
if(_rand == 0){
amountPlayer0[j] =1;
}else{
amountPlayer1[j] =1;
}
game0.opponentTogsAmount[i] -=1;
j += 1;
}
}
game0.gameState = 3;
// transfer flipped Pog
Cryptogs.safeBatchTransferFrom(address(this), game0.creator, flippedTogs, amountPlayer0, "");
Cryptogs.safeBatchTransferFrom(address(this), game0.opponent, flippedTogs, amountPlayer1, "");
emit FlipTogs(_gameId, game0.creator, game0.opponent, flippedTogs, amountPlayer0, amountPlayer1);
}
event withdrawTogs (uint256 indexed GameId, address indexed Creator);
// Withdraw Togs when game completed or expired
function withdrawTogs (uint256 _gameId) public {
require(_gameId <= gameId); // game exists
require(games[_gameId].expirationBlock < block.number); // game expired
require(games[_gameId].withdrawed == false & games[_gameId].gameState == 1); // not withdrawed
Cryptogs.safeBatchTransferFrom(address(this), games[_gameId].creator, games[_gameId].creatorTogs, games[_gameId].creatorTogsAmount, "");
//Cryptogs.safeBatchTransferFrom(address(this), games[_gameId].opponent, games[_gameId].opponentTogs, games[_gameId].opponentTogsAmount, "");
// end the game
games[_gameId].withdrawed = true;
games[_gameId].gameState = 4;
uint256[] memory tmp0 = new uint256[](games[_gameId].creatorTogsAmount.length);
// uint256[] memory tmp1 = new uint256[](games[_gameId].opponentTogsAmount.length);
emit WithdrawTogs(_gameId, games[_gameId].creator);
games[_gameId].creatorTogsAmount = tmp0;
// games[_gameId].opponentTogsAmount = tmp1;
}
event withdrawToken(address indexed TokenContract, uint256 indexed Amount);
// withdraw token: LINK (only owner)
function withdrawToken(address _tokenContract, uint256 _amount) public onlyOwner {
IERC20 tokenContract = IERC20(_tokenContract);
// transfer the token from address of this contract
// to address of the user (executing the withdrawToken() function)
tokenContract.transfer(msg.sender, _amount);
emit WithdrawToken(_tokenContract, _amount);
}
// withdraw ETH/Polygon
function withdrawETH() public onlyOwner {
address payable _owner = payable(owner());
_owner.transfer(address(this).balance);
}
}
|
withdraw ETH/Polygon
|
function withdrawETH() public onlyOwner {
address payable _owner = payable(owner());
_owner.transfer(address(this).balance);
}
| 979,694
|
./full_match/1/0x2d94AA3e47d9D5024503Ca8491fcE9A2fB4DA198/sources/contracts/Bank.sol
|
Transfer `amount` tokens from `msg.sender` to `dst` dst The address of the destination account rawAmount The number of tokens to transfer return Whether or not the transfer succeeded/
|
function transfer(address dst, uint rawAmount) external returns (bool) {
uint96 amount = safe96(rawAmount, "Bank::transfer: amount exceeds 96 bits");
_transferTokens(msg.sender, dst, amount);
return true;
}
| 4,950,952
|
./full_match/4/0x6133B3b6d3364E4d1c1f952FCA469687d847F8DE/sources/browser/test.sol
|
address(0) means payment mode is ether else that particular stable coin
|
function BuyNetwork(address _coinAddress, uint256 amount) public payable returns(bool)
{
require(msg.value == networkPrice, "pls pay correct price");
require(_coinAddress == address(0) || validStableCoin[_coinAddress] > 0, "Invalid coin address");
require(msg.value == networkPrice || checkAmount(amount,networkPrice, _coinAddress), "Invalid amount sent");
if(msg.value > 0 ) amount = msg.value;
networkIdCount++;
uint nID = networkIdCount;
networkId[msg.sender] = nID;
networkOwner[nID] = msg.sender;
coinAddress[nID] = _coinAddress;
pausenetwork[nID] = true;
require(doTransaction(nID, address(0), owner,amount,0,false,0), "amount tx fail");
emit BuynetworkEv(now, msg.sender, msg.value, networkIdCount);
}
| 707,879
|
./full_match/4/0xee2E5e30881623D00aa3f556800887f3Af8dE6d8/sources/contracts/utils/SignerV2.sol
|
Signature generator _to receiver address. _value value in wei. _data encoded transaction data. _operation type of operation call. _safeTxGas safe transaction gas for gnosis safe. _baseGas base gas for gnosis safe. _gasPrice gas price for gnosis safe transaction. _gasToken token which gas needs to paid for gnosis safe transaction. _refundReceiver address account to receive refund for remaining gas. _nonce gnosis safe contract nonce./ check if transaction parameters are correct get contractTransactionHash from gnosis safe check if transaction is not signed before solhint-disable-next-line reason-string generate signature and add it to approvedSignatures mapping
|
function generateSignature(
address _to,
uint256 _value,
bytes calldata _data,
Enum.Operation _operation,
uint256 _safeTxGas,
uint256 _baseGas,
uint256 _gasPrice,
address _gasToken,
address _refundReceiver,
uint256 _nonce
) external returns (bytes memory signature, bytes32 hash) {
require(
allowedTransactions[_to][_getFunctionHashFromData(_data)],
"Signer: invalid function"
);
require(
_value == 0 &&
_refundReceiver == address(0) &&
_operation == Enum.Operation.Call,
"Signer: invalid arguments"
);
hash = Safe(safe).getTransactionHash(
_to,
0,
_data,
_operation,
_safeTxGas,
_baseGas,
_gasPrice,
_gasToken,
_refundReceiver,
_nonce
);
bytes memory paddedAddress = bytes.concat(
bytes12(0),
bytes20(address(this))
);
bytes memory messageHash = _encodeMessageHash(hash);
require(
approvedSignatures[hash] != keccak256(messageHash),
"Signer: transaction already signed"
);
signature = bytes.concat(
paddedAddress,
bytes32(uint256(65)),
bytes1(0),
bytes32(uint256(messageHash.length)),
messageHash
);
approvedSignatures[hash] = keccak256(messageHash);
emit SignatureCreated(signature, hash);
}
| 698,068
|
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol";
import "./ERC721AUpgradeable.sol";
contract ATCC is
OwnableUpgradeable,
ERC721AUpgradeable,
ReentrancyGuardUpgradeable
{
uint256 public constant MAX_SUPPLY = 3500;
//set the cap for minting
uint256 public mintSaleCap;
uint256 public itemPrice;
//0->not started | 1-> whitelist | 2-> public
uint256 public saleStatus;
uint256 public minted;
string private _baseTokenURI;
address public wallet;
modifier whenPublicMintActive() {
require(saleStatus == 2, "Public mint hasn't started yet");
_;
}
modifier whenWhitelistMintActive() {
require(saleStatus == 1, "Whitelist minting hasn't started yet");
_;
}
modifier checkPrice(uint256 _howMany) {
require(
itemPrice * _howMany <= msg.value,
"Ether value sent is not correct"
);
_;
}
function initialize() external initializer {
__Ownable_init();
__ReentrancyGuard_init();
initialize(
"Alpha Trader's Country Club",
"ATCC",
200,
MAX_SUPPLY
);
itemPrice = 0.11 ether;
mintSaleCap = 3000;
}
function forAirdrop(address[] memory _to, uint256[] memory _count)
external
onlyOwner
{
uint256 _length = _to.length;
for (uint256 i = 0; i < _length; i++) {
giveaway(_to[i], _count[i]);
}
}
function giveaway(address _to, uint256 _howMany) public onlyOwner {
require(_to != address(0), "Zero address");
_beforeMint(_howMany);
_safeMint(_to, _howMany);
}
function _beforeMint(uint256 _howMany) private view {
require(_howMany > 0, "Must mint at least one");
uint256 supply = totalSupply();
require(
supply + _howMany <= MAX_SUPPLY,
"Minting would exceed max supply"
);
}
function mintTo(address to, uint256 _howMany) external payable {
// Optional Restriction
require(
_msgSender() == 0xdAb1a1854214684acE522439684a145E62505233,
"This function is for Crossmint only."
);
require(saleStatus > 0, "Minting hasn't started yet");
_mintToken(to, _howMany);
}
function whitelistMint(uint256 _howMany)
external
payable
whenWhitelistMintActive
{
_mintToken(_msgSender(), _howMany);
}
function publicMint(uint256 _howMany)
external
payable
whenPublicMintActive
{
_mintToken(_msgSender(), _howMany);
}
function _mintToken(address _to, uint256 _howMany)
internal
nonReentrant
checkPrice(_howMany)
{
_beforeMint(_howMany);
if (_howMany >= 4) {
_howMany += _howMany / 4;
}
require(
minted + _howMany <= mintSaleCap,
"Minting would exceed max cap"
);
minted += _howMany;
_safeMint(_to, _howMany);
}
function startPublicMint() external onlyOwner {
require(saleStatus != 2, "Public minting has already begun");
saleStatus = 2;
}
function startWhitelistMint() external onlyOwner {
require(saleStatus != 1, "Whitelist minting has already begun");
saleStatus = 1;
}
function stopSale() external onlyOwner {
saleStatus = 0;
}
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
function setBaseURI(string calldata baseURI) external onlyOwner {
_baseTokenURI = baseURI;
}
// list all the tokens ids of a wallet
function tokensOfOwner(address _owner)
external
view
returns (uint256[] memory)
{
uint256 tokenCount = balanceOf(_owner);
if (tokenCount == 0) {
// Return an empty array
return new uint256[](0);
} else {
uint256[] memory result = new uint256[](tokenCount);
uint256 index;
for (index = 0; index < tokenCount; index++) {
result[index] = tokenOfOwnerByIndex(_owner, index);
}
return result;
}
}
function updateWallet(address _wallet) external onlyOwner {
wallet = _wallet;
}
function withdrawMoney() external onlyOwner nonReentrant {
_withdraw();
}
function _withdraw() internal {
uint256 bal = accountBalance();
(bool success1, ) = wallet.call{value: bal}("");
require(success1, "Transfer failed.");
}
function accountBalance() public view returns (uint256) {
return address(this).balance;
}
function setPrice(uint256 _newPrice) external onlyOwner {
itemPrice = _newPrice;
}
function setSaleCap(uint256 _mintSaleCap) external onlyOwner {
mintSaleCap = _mintSaleCap;
}
function setOwnersExplicit(uint256 quantity)
external
onlyOwner
nonReentrant
{
_setOwnersExplicit(quantity);
}
function numberMinted(address owner) public view returns (uint256) {
return _numberMinted(owner);
}
function exists(uint256 _tokenId) external view returns (bool) {
return _exists(_tokenId);
}
function getOwnershipData(uint256 tokenId)
external
view
returns (TokenOwnership memory)
{
return ownershipOf(tokenId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165Upgradeable.sol";
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
abstract contract ERC721AUpgradeable is
ContextUpgradeable,
ERC165Upgradeable,
IERC721Upgradeable,
IERC721MetadataUpgradeable,
IERC721EnumerableUpgradeable
{
using AddressUpgradeable for address;
using StringsUpgradeable for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex;
uint256 internal collectionSize;
uint256 internal maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// 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
* `maxBatchSize` refers to how much a minter can mint at a time.
* `collectionSize_` refers to how many tokens are in the collection.
*/
function initialize(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
) internal {
__Context_init();
__ERC165_init();
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
collectionSize = collectionSize_;
currentIndex = 1;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex - 1;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165Upgradeable, IERC165Upgradeable)
returns (bool)
{
return
interfaceId == type(IERC721Upgradeable).interfaceId ||
interfaceId == type(IERC721MetadataUpgradeable).interfaceId ||
interfaceId == type(IERC721EnumerableUpgradeable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(
owner != address(0),
"ERC721A: balance query for the zero address"
);
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @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 override {
address owner = ERC721AUpgradeable.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
require(
_exists(tokenId),
"ERC721A: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
override
{
require(operator != _msgSender(), "ERC721A: 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 override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: 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`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex && tokenId > 0;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - there must be `quantity` tokens remaining unminted in the total collection.
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* 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
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > collectionSize - 1) {
endIndex = collectionSize - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @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
IERC721ReceiverUpgradeable(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721ReceiverUpgradeable(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721A: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal onlyInitializing {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal onlyInitializing {
_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;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/utils/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal onlyInitializing {
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal onlyInitializing {
_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);
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165Upgradeable.sol";
import "../../proxy/utils/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
function __ERC165_init() internal onlyInitializing {
}
function __ERC165_init_unchained() internal onlyInitializing {
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library StringsUpgradeable {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
import "../proxy/utils/Initializable.sol";
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal onlyInitializing {
}
function __Context_init_unchained() internal onlyInitializing {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
/**
* @dev This empty reserved space is put in place to allow future versions to add new
* variables without shifting down storage in the inheritance chain.
* See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps
*/
uint256[50] private __gap;
}
// 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 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
* ====
*
* [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 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 (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721ReceiverUpgradeable {
/**
* @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 `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
/**
* @dev 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 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 the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @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);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.6.0) (proxy/utils/Initializable.sol)
pragma solidity ^0.8.2;
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 proxied contracts do not make use of a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* The initialization functions use a version number. Once a version number is used, it is consumed and cannot be
* reused. This mechanism prevents re-execution of each "step" but allows the creation of new initialization steps in
* case an upgrade adds a module that needs to be initialized.
*
* For example:
*
* [.hljs-theme-light.nopadding]
* ```
* contract MyToken is ERC20Upgradeable {
* function initialize() initializer public {
* __ERC20_init("MyToken", "MTK");
* }
* }
* contract MyTokenV2 is MyToken, ERC20PermitUpgradeable {
* function initializeV2() reinitializer(2) public {
* __ERC20Permit_init("MyToken");
* }
* }
* ```
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*
* [CAUTION]
* ====
* Avoid leaving a contract uninitialized.
*
* An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation
* contract, which may impact the proxy. To prevent the implementation contract from being used, you should invoke
* the {_disableInitializers} function in the constructor to automatically lock it when it is deployed:
*
* [.hljs-theme-light.nopadding]
* ```
* /// @custom:oz-upgrades-unsafe-allow constructor
* constructor() {
* _disableInitializers();
* }
* ```
* ====
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
* @custom:oz-retyped-from bool
*/
uint8 private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Triggered when the contract has been initialized or reinitialized.
*/
event Initialized(uint8 version);
/**
* @dev A modifier that defines a protected initializer function that can be invoked at most once. In its scope,
* `onlyInitializing` functions can be used to initialize parent contracts. Equivalent to `reinitializer(1)`.
*/
modifier initializer() {
bool isTopLevelCall = _setInitializedVersion(1);
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(1);
}
}
/**
* @dev A modifier that defines a protected reinitializer function that can be invoked at most once, and only if the
* contract hasn't been initialized to a greater version before. In its scope, `onlyInitializing` functions can be
* used to initialize parent contracts.
*
* `initializer` is equivalent to `reinitializer(1)`, so a reinitializer may be used after the original
* initialization step. This is essential to configure modules that are added through upgrades and that require
* initialization.
*
* Note that versions can jump in increments greater than 1; this implies that if multiple reinitializers coexist in
* a contract, executing them in the right order is up to the developer or operator.
*/
modifier reinitializer(uint8 version) {
bool isTopLevelCall = _setInitializedVersion(version);
if (isTopLevelCall) {
_initializing = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
emit Initialized(version);
}
}
/**
* @dev Modifier to protect an initialization function so that it can only be invoked by functions with the
* {initializer} and {reinitializer} modifiers, directly or indirectly.
*/
modifier onlyInitializing() {
require(_initializing, "Initializable: contract is not initializing");
_;
}
/**
* @dev Locks the contract, preventing any future reinitialization. This cannot be part of an initializer call.
* Calling this in the constructor of a contract will prevent that contract from being initialized or reinitialized
* to any version. It is recommended to use this to lock implementation contracts that are designed to be called
* through proxies.
*/
function _disableInitializers() internal virtual {
_setInitializedVersion(type(uint8).max);
}
function _setInitializedVersion(uint8 version) private returns (bool) {
// If the contract is initializing we ignore whether _initialized is set in order to support multiple
// inheritance patterns, but we only do this in the context of a constructor, and for the lowest level
// of initializers, because in other contexts the contract may have been reentered.
if (_initializing) {
require(
version == 1 && !AddressUpgradeable.isContract(address(this)),
"Initializable: contract is already initialized"
);
return false;
} else {
require(_initialized < version, "Initializable: contract is already initialized");
_initialized = version;
return true;
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
|
Optional Restriction
|
function mintTo(address to, uint256 _howMany) external payable {
require(
_msgSender() == 0xdAb1a1854214684acE522439684a145E62505233,
"This function is for Crossmint only."
);
require(saleStatus > 0, "Minting hasn't started yet");
_mintToken(to, _howMany);
}
| 323,336
|
pragma solidity ^0.4.23;
contract Necropolis {
function addDragon(address _lastDragonOwner, uint256 _dragonID, uint256 _deathReason) external;
}
contract GenRNG {
function getNewGens(address _from, uint256 _dragonID) external returns (uint256[2] resultGen);
}
contract DragonSelectFight2Death {
function addSelctFight2Death(
address _dragonOwner,
uint256 _yourDragonID,
uint256 _oppDragonID,
uint256 _endBlockNumber,
uint256 _priceSelectFight2Death
)
external;
}
contract DragonsRandomFight2Death {
function addRandomFight2Death(address _dragonOwner, uint256 _DragonID) external;
}
contract FixMarketPlace {
function add2MarketPlace(address _dragonOwner, uint256 _dragonID, uint256 _dragonPrice, uint256 _endBlockNumber) external returns (bool);
}
contract Auction {
function add2Auction(
address _dragonOwner,
uint256 _dragonID,
uint256 _startPrice,
uint256 _step,
uint256 _endPrice,
uint256 _endBlockNumber
)
external
returns (bool);
}
contract DragonStats {
function setParents(uint256 _dragonID, uint256 _parentOne, uint256 _parentTwo) external;
function setBirthBlock(uint256 _dragonID) external;
function incChildren(uint256 _dragonID) external;
function setDeathBlock(uint256 _dragonID) external;
function getDragonFight(uint256 _dragonID) external view returns (uint256);
}
contract SuperContract {
function checkDragon(uint256 _dragonID) external returns (bool);
}
contract Mutagen2Face {
function addDragon(address _dragonOwner, uint256 _dragonID, uint256 mutagenCount) external;
}
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 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) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
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;
}
}
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev give an address access to this role
*/
function add(Role storage role, address addr)
internal
{
role.bearer[addr] = true;
}
/**
* @dev remove an address' access to this role
*/
function remove(Role storage role, address addr)
internal
{
role.bearer[addr] = false;
}
/**
* @dev check if an address has this role
* // reverts
*/
function check(Role storage role, address addr)
view
internal
{
require(has(role, addr));
}
/**
* @dev check if an address has this role
* @return bool
*/
function has(Role storage role, address addr)
view
internal
returns (bool)
{
return role.bearer[addr];
}
}
contract RBAC {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address addr, string roleName);
event RoleRemoved(address addr, string roleName);
/**
* @dev reverts if addr does not have role
* @param addr address
* @param roleName the name of the role
* // reverts
*/
function checkRole(address addr, string roleName)
view
public
{
roles[roleName].check(addr);
}
/**
* @dev determine if addr has role
* @param addr address
* @param roleName the name of the role
* @return bool
*/
function hasRole(address addr, string roleName)
view
public
returns (bool)
{
return roles[roleName].has(addr);
}
/**
* @dev add a role to an address
* @param addr address
* @param roleName the name of the role
*/
function addRole(address addr, string roleName)
internal
{
roles[roleName].add(addr);
emit RoleAdded(addr, roleName);
}
/**
* @dev remove a role from an address
* @param addr address
* @param roleName the name of the role
*/
function removeRole(address addr, string roleName)
internal
{
roles[roleName].remove(addr);
emit RoleRemoved(addr, roleName);
}
/**
* @dev modifier to scope access to a single role (uses msg.sender as addr)
* @param roleName the name of the role
* // reverts
*/
modifier onlyRole(string roleName)
{
checkRole(msg.sender, roleName);
_;
}
/**
* @dev modifier to scope access to a set of roles (uses msg.sender as addr)
* @param roleNames the names of the roles to scope access to
* // reverts
*
* @TODO - when solidity supports dynamic arrays as arguments to modifiers, provide this
* see: https://github.com/ethereum/solidity/issues/2467
*/
// modifier onlyRoles(string[] roleNames) {
// bool hasAnyRole = false;
// for (uint8 i = 0; i < roleNames.length; i++) {
// if (hasRole(msg.sender, roleNames[i])) {
// hasAnyRole = true;
// break;
// }
// }
// require(hasAnyRole);
// _;
// }
}
contract RBACWithAdmin is RBAC {
/**
* A constant role name for indicating admins.
*/
string public constant ROLE_ADMIN = "admin";
string public constant ROLE_PAUSE_ADMIN = "pauseAdmin";
/**
* @dev modifier to scope access to admins
* // reverts
*/
modifier onlyAdmin()
{
checkRole(msg.sender, ROLE_ADMIN);
_;
}
modifier onlyPauseAdmin()
{
checkRole(msg.sender, ROLE_PAUSE_ADMIN);
_;
}
/**
* @dev constructor. Sets msg.sender as admin by default
*/
constructor()
public
{
addRole(msg.sender, ROLE_ADMIN);
addRole(msg.sender, ROLE_PAUSE_ADMIN);
}
/**
* @dev add a role to an address
* @param addr address
* @param roleName the name of the role
*/
function adminAddRole(address addr, string roleName)
onlyAdmin
public
{
addRole(addr, roleName);
}
/**
* @dev remove a role from an address
* @param addr address
* @param roleName the name of the role
*/
function adminRemoveRole(address addr, string roleName)
onlyAdmin
public
{
removeRole(addr, roleName);
}
}
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 payable;
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 payable;
function safeTransferFrom(address _from, address _to, uint256 _tokenId) public payable;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public payable;
}
contract ERC721Metadata is ERC721Basic {
function name() public view returns (string _name);
function symbol() public view returns (string _symbol);
function tokenURI(uint256 _tokenId) external view returns (string);
}
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 payable{
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;
if (msg.value > 0 && _to != address(0)) _to.transfer(msg.value);
if (msg.value > 0 && _to == address(0)) owner.transfer(msg.value);
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 payable canTransfer(_tokenId) {
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
if (msg.value > 0) _to.transfer(msg.value);
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
payable
canTransfer(_tokenId)
{
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
payable
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
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) public 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);
}
}
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);
}
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);
}
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
contract ERC721Token is ERC721, ERC721BasicToken {
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping (address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
// mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
constructor(string _name, string _symbol) public {
name_ = _name;
symbol_ = _symbol;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() public view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() public view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* @dev Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
bytes constant firstPartURI = "https://www.dragonseth.com/image/";
function tokenURI(uint256 _tokenId) external view returns (string) {
require(exists(_tokenId));
bytes memory tmpBytes = new bytes(96);
uint256 i = 0;
uint256 tokenId = _tokenId;
// for same use case need "if (tokenId == 0)"
while (tokenId != 0) {
uint256 remainderDiv = tokenId % 10;
tokenId = tokenId / 10;
tmpBytes[i++] = byte(48 + remainderDiv);
}
bytes memory resaultBytes = new bytes(firstPartURI.length + i);
for (uint256 j = 0; j < firstPartURI.length; j++) {
resaultBytes[j] = firstPartURI[j];
}
i--;
for (j = 0; j <= i; j++) {
resaultBytes[j + firstPartURI.length] = tmpBytes[i - j];
}
return string(resaultBytes);
}
/*
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;
}
/**
* @dev 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) external view returns (uint256[]) {
return ownedTokens[_owner];
}
}
contract DragonsETH_GC is RBACWithAdmin {
GenRNG public genRNGContractAddress;
FixMarketPlace public fmpContractAddress;
DragonStats public dragonsStatsContract;
Necropolis public necropolisContract;
Auction public auctionContract;
SuperContract public superContract;
DragonSelectFight2Death public selectFight2DeathContract;
DragonsRandomFight2Death public randomFight2DeathContract;
Mutagen2Face public mutagen2FaceContract;
address wallet;
uint8 adultDragonStage = 3;
bool stageThirdBegin = false;
uint256 constant UINT256_MAX = 115792089237316195423570985008687907853269984665640564039457584007913129639935;
uint256 public secondsInBlock = 15;
uint256 public priceDecraseTime2Action = 0.000005 ether; // 1 block
uint256 public priceRandomFight2Death = 0.02 ether;
uint256 public priceSelectFight2Death = 0.03 ether;
uint256 public priceChangeName = 0.01 ether;
uint256 public needFightToAdult = 100;
function changeGenRNGcontractAddress(address _genRNGContractAddress) external onlyAdmin {
genRNGContractAddress = GenRNG(_genRNGContractAddress);
}
function changeFMPcontractAddress(address _fmpContractAddress) external onlyAdmin {
fmpContractAddress = FixMarketPlace(_fmpContractAddress);
}
function changeDragonsStatsContract(address _dragonsStatsContract) external onlyAdmin {
dragonsStatsContract = DragonStats(_dragonsStatsContract);
}
function changeAuctionContract(address _auctionContract) external onlyAdmin {
auctionContract = Auction(_auctionContract);
}
function changeSelectFight2DeathContract(address _selectFight2DeathContract) external onlyAdmin {
selectFight2DeathContract = DragonSelectFight2Death(_selectFight2DeathContract);
}
function changeRandomFight2DeathContract(address _randomFight2DeathContract) external onlyAdmin {
randomFight2DeathContract = DragonsRandomFight2Death(_randomFight2DeathContract);
}
function changeMutagen2FaceContract(address _mutagen2FaceContract) external onlyAdmin {
mutagen2FaceContract = Mutagen2Face(_mutagen2FaceContract);
}
function changeSuperContract(address _superContract) external onlyAdmin {
superContract = SuperContract(_superContract);
}
function changeWallet(address _wallet) external onlyAdmin {
wallet = _wallet;
}
function changePriceDecraseTime2Action(uint256 _priceDecraseTime2Action) external onlyAdmin {
priceDecraseTime2Action = _priceDecraseTime2Action;
}
function changePriceRandomFight2Death(uint256 _priceRandomFight2Death) external onlyAdmin {
priceRandomFight2Death = _priceRandomFight2Death;
}
function changePriceSelectFight2Death(uint256 _priceSelectFight2Death) external onlyAdmin {
priceSelectFight2Death = _priceSelectFight2Death;
}
function changePriceChangeName(uint256 _priceChangeName) external onlyAdmin {
priceChangeName = _priceChangeName;
}
function changeSecondsInBlock(uint256 _secondsInBlock) external onlyAdmin {
secondsInBlock = _secondsInBlock;
}
function changeNeedFightToAdult(uint256 _needFightToAdult) external onlyAdmin {
needFightToAdult = _needFightToAdult;
}
function changeAdultDragonStage(uint8 _adultDragonStage) external onlyAdmin {
adultDragonStage = _adultDragonStage;
}
function setStageThirdBegin() external onlyAdmin {
stageThirdBegin = true;
}
function withdrawAllEther() external onlyAdmin {
require(wallet != 0);
wallet.transfer(address(this).balance);
}
// EIP-165 and EIP-721
bytes4 constant ERC165_Signature = 0x01ffc9a7;
bytes4 constant ERC721_Signature = 0x80ac58cd;
bytes4 constant ERC721Metadata_Signature = 0x5b5e139f;
bytes4 constant ERC721Enumerable_Signature = 0x780e9d63;
function supportsInterface(bytes4 _interfaceID) external pure returns (bool) {
return (
(_interfaceID == ERC165_Signature) ||
(_interfaceID == ERC721_Signature) ||
(_interfaceID == ERC721Metadata_Signature) ||
(_interfaceID == ERC721Enumerable_Signature)
);
}
}
contract ReentrancyGuard {
/**
* @dev We use a single lock for the whole contract.
*/
bool private reentrancyLock = false;
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* @notice If you mark a function `nonReentrant`, you should also
* mark it `external`. Calling one nonReentrant function from
* another is not supported. Instead, you can implement a
* `private` function doing the actual work, and a `external`
* wrapper marked as `nonReentrant`.
*/
modifier nonReentrant() {
require(!reentrancyLock);
reentrancyLock = true;
_;
reentrancyLock = false;
}
}
contract DragonsETH is ERC721Token("DragonsETH.com Dragon", "DragonsETH"), DragonsETH_GC, ReentrancyGuard {
uint256 public totalDragons;
uint256 public liveDragons;
struct Dragon {
uint256 gen1;
uint8 stage; // 0 - Dead, 1 - Egg, 2 - Young Dragon ...
uint8 currentAction;
// 0 - free, 1 - fight place, 2 - random fight, 3 - breed market, 4 - breed auction, 5 - random breed ... 0xFF - Necropolis
uint240 gen2;
uint256 nextBlock2Action;
}
Dragon[] public dragons;
mapping(uint256 => string) public dragonName;
constructor(address _wallet, address _necropolisContract, address _dragonsStatsContract) public {
_mint(msg.sender, 0);
Dragon memory _dragon = Dragon({
gen1: 0,
stage: 0,
currentAction: 0,
gen2: 0,
nextBlock2Action: UINT256_MAX
});
dragons.push(_dragon);
transferFrom(msg.sender, _necropolisContract, 0);
dragonsStatsContract = DragonStats(_dragonsStatsContract);
necropolisContract = Necropolis(_necropolisContract);
wallet = _wallet;
}
function add2MarketPlace(uint256 _dragonID, uint256 _dragonPrice, uint256 _endBlockNumber) external canTransfer(_dragonID) {
require(dragons[_dragonID].stage != 0); // dragon not dead
if (dragons[_dragonID].stage >= 2) {
checkDragonStatus(_dragonID, 2);
}
address dragonOwner = ownerOf(_dragonID);
if (fmpContractAddress.add2MarketPlace(dragonOwner, _dragonID, _dragonPrice, _endBlockNumber)) {
transferFrom(dragonOwner, fmpContractAddress, _dragonID);
}
}
function add2Auction(
uint256 _dragonID,
uint256 _startPrice,
uint256 _step,
uint256 _endPrice,
uint256 _endBlockNumber
)
external
canTransfer(_dragonID)
{
require(dragons[_dragonID].stage != 0); // dragon not dead
if (dragons[_dragonID].stage >= 2) {
checkDragonStatus(_dragonID, 2);
}
address dragonOwner = ownerOf(_dragonID);
if (auctionContract.add2Auction(dragonOwner, _dragonID, _startPrice, _step, _endPrice, _endBlockNumber)) {
transferFrom(dragonOwner, auctionContract, _dragonID);
}
}
function addRandomFight2Death(uint256 _dragonID) external payable nonReentrant canTransfer(_dragonID) {
checkDragonStatus(_dragonID, adultDragonStage);
if (priceRandomFight2Death > 0) {
require(msg.value >= priceRandomFight2Death);
wallet.transfer(priceRandomFight2Death);
if (msg.value - priceRandomFight2Death > 0)
msg.sender.transfer(msg.value - priceRandomFight2Death);
} else {
if (msg.value > 0)
msg.sender.transfer(msg.value);
}
address dragonOwner = ownerOf(_dragonID);
transferFrom(dragonOwner, randomFight2DeathContract, _dragonID);
randomFight2DeathContract.addRandomFight2Death(dragonOwner, _dragonID);
}
function addSelctFight2Death(uint256 _yourDragonID, uint256 _oppDragonID, uint256 _endBlockNumber)
external
payable
nonReentrant
canTransfer(_yourDragonID)
{
checkDragonStatus(_yourDragonID, adultDragonStage);
if (priceSelectFight2Death > 0) {
require(msg.value >= priceSelectFight2Death);
address(selectFight2DeathContract).transfer(priceSelectFight2Death);
if (msg.value - priceSelectFight2Death > 0) msg.sender.transfer(msg.value - priceSelectFight2Death);
} else {
if (msg.value > 0)
msg.sender.transfer(msg.value);
}
address dragonOwner = ownerOf(_yourDragonID);
transferFrom(dragonOwner, selectFight2DeathContract, _yourDragonID);
selectFight2DeathContract.addSelctFight2Death(dragonOwner, _yourDragonID, _oppDragonID, _endBlockNumber, priceSelectFight2Death);
}
function mutagen2Face(uint256 _dragonID, uint256 _mutagenCount) external canTransfer(_dragonID) {
checkDragonStatus(_dragonID, 2);
address dragonOwner = ownerOf(_dragonID);
transferFrom(dragonOwner, mutagen2FaceContract, _dragonID);
mutagen2FaceContract.addDragon(dragonOwner, _dragonID, _mutagenCount);
}
function createDragon(
address _to,
uint256 _timeToBorn,
uint256 _parentOne,
uint256 _parentTwo,
uint256 _gen1,
uint240 _gen2
)
external
onlyRole("CreateContract")
{
totalDragons++;
liveDragons++;
_mint(_to, totalDragons);
uint256[2] memory twoGen;
if (_parentOne == 0 && _parentTwo == 0 && _gen1 == 0 && _gen2 == 0) {
twoGen = genRNGContractAddress.getNewGens(_to, totalDragons);
} else {
twoGen[0] = _gen1;
twoGen[1] = uint256(_gen2);
}
Dragon memory _dragon = Dragon({
gen1: twoGen[0],
stage: 1,
currentAction: 0,
gen2: uint240(twoGen[1]),
nextBlock2Action: _timeToBorn
});
dragons.push(_dragon);
if (_parentOne != 0) {
dragonsStatsContract.setParents(totalDragons,_parentOne,_parentTwo);
dragonsStatsContract.incChildren(_parentOne);
dragonsStatsContract.incChildren(_parentTwo);
}
dragonsStatsContract.setBirthBlock(totalDragons);
}
function changeDragonGen(uint256 _dragonID, uint256 _gen, uint8 _which) external onlyRole("ChangeContract") {
require(dragons[_dragonID].stage >= 2); // dragon not dead and not egg
if (_which == 0) {
dragons[_dragonID].gen1 = _gen;
} else {
dragons[_dragonID].gen2 = uint240(_gen);
}
}
function birthDragon(uint256 _dragonID) external canTransfer(_dragonID) {
require(dragons[_dragonID].stage != 0); // dragon not dead
require(dragons[_dragonID].nextBlock2Action <= block.number);
dragons[_dragonID].stage = 2;
}
function matureDragon(uint256 _dragonID) external canTransfer(_dragonID) {
require(stageThirdBegin);
checkDragonStatus(_dragonID, 2);
require(dragonsStatsContract.getDragonFight(_dragonID) >= needFightToAdult);
dragons[_dragonID].stage = 3;
}
function superDragon(uint256 _dragonID) external canTransfer(_dragonID) {
checkDragonStatus(_dragonID, 3);
require(superContract.checkDragon(_dragonID));
dragons[_dragonID].stage = 4;
}
function killDragon(uint256 _dragonID) external onlyOwnerOf(_dragonID) {
checkDragonStatus(_dragonID, 2);
dragons[_dragonID].stage = 0;
dragons[_dragonID].currentAction = 0xFF;
dragons[_dragonID].nextBlock2Action = UINT256_MAX;
necropolisContract.addDragon(ownerOf(_dragonID), _dragonID, 1);
transferFrom(ownerOf(_dragonID), necropolisContract, _dragonID);
dragonsStatsContract.setDeathBlock(_dragonID);
liveDragons--;
}
function killDragonDeathContract(address _lastOwner, uint256 _dragonID, uint256 _deathReason)
external
canTransfer(_dragonID)
onlyRole("DeathContract")
{
checkDragonStatus(_dragonID, 2);
dragons[_dragonID].stage = 0;
dragons[_dragonID].currentAction = 0xFF;
dragons[_dragonID].nextBlock2Action = UINT256_MAX;
necropolisContract.addDragon(_lastOwner, _dragonID, _deathReason);
transferFrom(ownerOf(_dragonID), necropolisContract, _dragonID);
dragonsStatsContract.setDeathBlock(_dragonID);
liveDragons--;
}
function decraseTimeToAction(uint256 _dragonID) external payable nonReentrant canTransfer(_dragonID) {
require(dragons[_dragonID].stage != 0); // dragon not dead
require(msg.value >= priceDecraseTime2Action);
require(dragons[_dragonID].nextBlock2Action > block.number);
uint256 maxBlockCount = dragons[_dragonID].nextBlock2Action - block.number;
if (msg.value > maxBlockCount * priceDecraseTime2Action) {
msg.sender.transfer(msg.value - maxBlockCount * priceDecraseTime2Action);
wallet.transfer(maxBlockCount * priceDecraseTime2Action);
dragons[_dragonID].nextBlock2Action = 0;
} else {
if (priceDecraseTime2Action == 0) {
dragons[_dragonID].nextBlock2Action = 0;
} else {
wallet.transfer(msg.value);
dragons[_dragonID].nextBlock2Action = dragons[_dragonID].nextBlock2Action - msg.value / priceDecraseTime2Action - 1;
}
}
}
function addDragonName(uint256 _dragonID,string _newName) external payable nonReentrant canTransfer(_dragonID) {
checkDragonStatus(_dragonID, 2);
if (bytes(dragonName[_dragonID]).length == 0) {
dragonName[_dragonID] = _newName;
if (msg.value > 0)
msg.sender.transfer(msg.value);
} else {
if (priceChangeName == 0) {
dragonName[_dragonID] = _newName;
if (msg.value > 0)
msg.sender.transfer(msg.value);
} else {
require(msg.value >= priceChangeName);
wallet.transfer(priceChangeName);
if (msg.value - priceChangeName > 0)
msg.sender.transfer(msg.value - priceChangeName);
dragonName[_dragonID] = _newName;
}
}
}
function checkDragonStatus(uint256 _dragonID, uint8 _stage) public view {
require(dragons[_dragonID].stage != 0); // dragon not dead
// dragon not in action and not in rest and not egg
require(
dragons[_dragonID].nextBlock2Action <= block.number &&
dragons[_dragonID].currentAction == 0 &&
dragons[_dragonID].stage >= _stage
);
}
function setCurrentAction(uint256 _dragonID, uint8 _currentAction) external onlyRole("ActionContract") {
dragons[_dragonID].currentAction = _currentAction;
}
function setTime2Rest(uint256 _dragonID, uint256 _addNextBlock2Action) external onlyRole("ActionContract") {
dragons[_dragonID].nextBlock2Action = block.number + _addNextBlock2Action;
}
}
|
Returns whether the given spender can transfer a given token ID _spender address of the spender to query _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) public view returns (bool) {
address owner = ownerOf(_tokenId);
return _spender == owner || getApproved(_tokenId) == _spender || isApprovedForAll(owner, _spender);
}
| 12,891,425
|
// Copyright (C) 2018 Argent Labs Ltd. <https://argent.xyz>
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
pragma solidity ^0.5.4;
contract Proxy {
address implementation;
event RECEIVED369(uint indexed value, address indexed sender, bytes data); //inject NONSTANDARD NAMING
constructor(address _implementation) public {
implementation = _implementation;
}
function() external payable {
if (msg.data.length == 0 && msg.value > 0) {
emit RECEIVED369(msg.value, msg.sender, msg.data);
} else {
// solium-disable-next-line security/no-inline-assembly
assembly {
let target := sload(0)
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas, target, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
}
contract BaseWallet {
function INIT685(address _owner, address[] calldata _modules) external; //inject NONSTANDARD NAMING
function AUTHORISEMODULE812(address _module, bool _value) external; //inject NONSTANDARD NAMING
function ENABLESTATICCALL186(address _module, bytes4 _method) external; //inject NONSTANDARD NAMING
function SETOWNER798(address _newOwner) external; //inject NONSTANDARD NAMING
function INVOKE21(address _target, uint _value, bytes calldata _data) external returns (bytes memory _result); //inject NONSTANDARD NAMING
function() external payable;
}
contract Owned {
// The owner
address public owner;
event OWNERCHANGED436(address indexed _newOwner); //inject NONSTANDARD NAMING
modifier ONLYOWNER47 { //inject NONSTANDARD NAMING
require(msg.sender == owner, "Must be owner");
_;
}
constructor() public {
owner = msg.sender;
}
function CHANGEOWNER39(address _newOwner) external ONLYOWNER47 { //inject NONSTANDARD NAMING
require(_newOwner != address(0), "Address must not be null");
owner = _newOwner;
emit OWNERCHANGED436(_newOwner);
}
}
contract Managed is Owned {
// The managers
mapping (address => bool) public managers;
modifier ONLYMANAGER653 { //inject NONSTANDARD NAMING
require(managers[msg.sender] == true, "M: Must be manager");
_;
}
event MANAGERADDED439(address indexed _manager); //inject NONSTANDARD NAMING
event MANAGERREVOKED398(address indexed _manager); //inject NONSTANDARD NAMING
function ADDMANAGER871(address _manager) external ONLYOWNER47 { //inject NONSTANDARD NAMING
require(_manager != address(0), "M: Address must not be null");
if (managers[_manager] == false) {
managers[_manager] = true;
emit MANAGERADDED439(_manager);
}
}
function REVOKEMANAGER965(address _manager) external ONLYOWNER47 { //inject NONSTANDARD NAMING
require(managers[_manager] == true, "M: Target must be an existing manager");
delete managers[_manager];
emit MANAGERREVOKED398(_manager);
}
}
interface IENSManager {
event ROOTNODEOWNERCHANGE990(bytes32 indexed _rootnode, address indexed _newOwner); //inject NONSTANDARD NAMING
event ENSRESOLVERCHANGED200(address addr); //inject NONSTANDARD NAMING
event REGISTERED245(address indexed _owner, string _ens); //inject NONSTANDARD NAMING
event UNREGISTERED914(string _ens); //inject NONSTANDARD NAMING
function CHANGEROOTNODEOWNER398(address _newOwner) external; //inject NONSTANDARD NAMING
function REGISTER194(string calldata _label, address _owner) external; //inject NONSTANDARD NAMING
function ISAVAILABLE666(bytes32 _subnode) external view returns(bool); //inject NONSTANDARD NAMING
function GETENSREVERSEREGISTRAR478() external view returns (address); //inject NONSTANDARD NAMING
function ENSRESOLVER758() external view returns (address); //inject NONSTANDARD NAMING
}
contract ModuleRegistry {
function REGISTERMODULE445(address _module, bytes32 _name) external; //inject NONSTANDARD NAMING
function DEREGISTERMODULE847(address _module) external; //inject NONSTANDARD NAMING
function REGISTERUPGRADER868(address _upgrader, bytes32 _name) external; //inject NONSTANDARD NAMING
function DEREGISTERUPGRADER19(address _upgrader) external; //inject NONSTANDARD NAMING
function MODULEINFO202(address _module) external view returns (bytes32); //inject NONSTANDARD NAMING
function UPGRADERINFO731(address _upgrader) external view returns (bytes32); //inject NONSTANDARD NAMING
function ISREGISTEREDMODULE404(address _module) external view returns (bool); //inject NONSTANDARD NAMING
function ISREGISTEREDMODULE404(address[] calldata _modules) external view returns (bool); //inject NONSTANDARD NAMING
function ISREGISTEREDUPGRADER426(address _upgrader) external view returns (bool); //inject NONSTANDARD NAMING
}
interface IGuardianStorage{
function ADDGUARDIAN190(BaseWallet _wallet, address _guardian) external; //inject NONSTANDARD NAMING
function REVOKEGUARDIAN58(BaseWallet _wallet, address _guardian) external; //inject NONSTANDARD NAMING
function ISGUARDIAN756(BaseWallet _wallet, address _guardian) external view returns (bool); //inject NONSTANDARD NAMING
}
contract WalletFactory is Owned, Managed {
// The address of the module dregistry
address public moduleRegistry;
// The address of the base wallet implementation
address public walletImplementation;
// The address of the ENS manager
address public ensManager;
// The address of the GuardianStorage
address public guardianStorage;
// *************** Events *************************** //
event MODULEREGISTRYCHANGED334(address addr); //inject NONSTANDARD NAMING
event ENSMANAGERCHANGED648(address addr); //inject NONSTANDARD NAMING
event GUARDIANSTORAGECHANGED398(address addr); //inject NONSTANDARD NAMING
event WALLETCREATED189(address indexed wallet, address indexed owner, address indexed guardian); //inject NONSTANDARD NAMING
// *************** Modifiers *************************** //
modifier GUARDIANSTORAGEDEFINED740 { //inject NONSTANDARD NAMING
require(guardianStorage != address(0), "GuardianStorage address not defined");
_;
}
// *************** Constructor ********************** //
constructor(address _moduleRegistry, address _walletImplementation, address _ensManager) public {
moduleRegistry = _moduleRegistry;
walletImplementation = _walletImplementation;
ensManager = _ensManager;
}
// *************** External Functions ********************* //
function CREATEWALLET541( //inject NONSTANDARD NAMING
address _owner,
address[] calldata _modules,
string calldata _label
)
external
ONLYMANAGER653
{
_CREATEWALLET379(_owner, _modules, _label, address(0));
}
function CREATEWALLETWITHGUARDIAN388( //inject NONSTANDARD NAMING
address _owner,
address[] calldata _modules,
string calldata _label,
address _guardian
)
external
ONLYMANAGER653
GUARDIANSTORAGEDEFINED740
{
require(_guardian != (address(0)), "WF: guardian cannot be null");
_CREATEWALLET379(_owner, _modules, _label, _guardian);
}
function CREATECOUNTERFACTUALWALLET430( //inject NONSTANDARD NAMING
address _owner,
address[] calldata _modules,
string calldata _label,
bytes32 _salt
)
external
ONLYMANAGER653
{
_CREATECOUNTERFACTUALWALLET436(_owner, _modules, _label, address(0), _salt);
}
function CREATECOUNTERFACTUALWALLETWITHGUARDIAN167( //inject NONSTANDARD NAMING
address _owner,
address[] calldata _modules,
string calldata _label,
address _guardian,
bytes32 _salt
)
external
ONLYMANAGER653
GUARDIANSTORAGEDEFINED740
{
require(_guardian != (address(0)), "WF: guardian cannot be null");
_CREATECOUNTERFACTUALWALLET436(_owner, _modules, _label, _guardian, _salt);
}
function GETADDRESSFORCOUNTERFACTUALWALLET140( //inject NONSTANDARD NAMING
address _owner,
address[] calldata _modules,
bytes32 _salt
)
external
view
returns (address _wallet)
{
_wallet = _GETADDRESSFORCOUNTERFACTUALWALLET709(_owner, _modules, address(0), _salt);
}
function GETADDRESSFORCOUNTERFACTUALWALLETWITHGUARDIAN758( //inject NONSTANDARD NAMING
address _owner,
address[] calldata _modules,
address _guardian,
bytes32 _salt
)
external
view
returns (address _wallet)
{
require(_guardian != (address(0)), "WF: guardian cannot be null");
_wallet = _GETADDRESSFORCOUNTERFACTUALWALLET709(_owner, _modules, _guardian, _salt);
}
function CHANGEMODULEREGISTRY647(address _moduleRegistry) external ONLYOWNER47 { //inject NONSTANDARD NAMING
require(_moduleRegistry != address(0), "WF: address cannot be null");
moduleRegistry = _moduleRegistry;
emit MODULEREGISTRYCHANGED334(_moduleRegistry);
}
function CHANGEENSMANAGER916(address _ensManager) external ONLYOWNER47 { //inject NONSTANDARD NAMING
require(_ensManager != address(0), "WF: address cannot be null");
ensManager = _ensManager;
emit ENSMANAGERCHANGED648(_ensManager);
}
function CHANGEGUARDIANSTORAGE66(address _guardianStorage) external ONLYOWNER47 { //inject NONSTANDARD NAMING
require(_guardianStorage != address(0), "WF: address cannot be null");
guardianStorage = _guardianStorage;
emit GUARDIANSTORAGECHANGED398(_guardianStorage);
}
function INIT685(BaseWallet _wallet) external pure { // solium-disable-line no-empty-blocks //inject NONSTANDARD NAMING
//do nothing
}
// *************** Internal Functions ********************* //
function _CREATEWALLET379(address _owner, address[] memory _modules, string memory _label, address _guardian) internal { //inject NONSTANDARD NAMING
_VALIDATEINPUTS330(_owner, _modules, _label);
Proxy proxy = new Proxy(walletImplementation);
address payable wallet = address(proxy);
_CONFIGUREWALLET163(BaseWallet(wallet), _owner, _modules, _label, _guardian);
}
function _CREATECOUNTERFACTUALWALLET436( //inject NONSTANDARD NAMING
address _owner,
address[] memory _modules,
string memory _label,
address _guardian,
bytes32 _salt
)
internal
{
_VALIDATEINPUTS330(_owner, _modules, _label);
bytes32 newsalt = _NEWSALT377(_salt, _owner, _modules, _guardian);
bytes memory code = abi.encodePacked(type(Proxy).creationCode, uint256(walletImplementation));
address payable wallet;
// solium-disable-next-line security/no-inline-assembly
assembly {
wallet := create2(0, add(code, 0x20), mload(code), newsalt)
if iszero(extcodesize(wallet)) { revert(0, returndatasize) }
}
_CONFIGUREWALLET163(BaseWallet(wallet), _owner, _modules, _label, _guardian);
}
function _CONFIGUREWALLET163( //inject NONSTANDARD NAMING
BaseWallet _wallet,
address _owner,
address[] memory _modules,
string memory _label,
address _guardian
)
internal
{
// add the factory to modules so it can claim the reverse ENS or add a guardian
address[] memory extendedModules = new address[](_modules.length + 1);
extendedModules[0] = address(this);
for (uint i = 0; i < _modules.length; i++) {
extendedModules[i + 1] = _modules[i];
}
// initialise the wallet with the owner and the extended modules
_wallet.INIT685(_owner, extendedModules);
// add guardian if needed
if (_guardian != address(0)) {
IGuardianStorage(guardianStorage).ADDGUARDIAN190(_wallet, _guardian);
}
// register ENS
_REGISTERWALLETENS735(address(_wallet), _label);
// remove the factory from the authorised modules
_wallet.AUTHORISEMODULE812(address(this), false);
// emit event
emit WALLETCREATED189(address(_wallet), _owner, _guardian);
}
function _GETADDRESSFORCOUNTERFACTUALWALLET709( //inject NONSTANDARD NAMING
address _owner,
address[] memory _modules,
address _guardian,
bytes32 _salt
)
internal
view
returns (address _wallet)
{
bytes32 newsalt = _NEWSALT377(_salt, _owner, _modules, _guardian);
bytes memory code = abi.encodePacked(type(Proxy).creationCode, uint256(walletImplementation));
bytes32 hash = keccak256(abi.encodePacked(bytes1(0xff), address(this), newsalt, keccak256(code)));
_wallet = address(uint160(uint256(hash)));
}
function _NEWSALT377(bytes32 _salt, address _owner, address[] memory _modules, address _guardian) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
if (_guardian == address(0)) {
return keccak256(abi.encodePacked(_salt, _owner, _modules));
} else {
return keccak256(abi.encodePacked(_salt, _owner, _modules, _guardian));
}
}
function _VALIDATEINPUTS330(address _owner, address[] memory _modules, string memory _label) internal view { //inject NONSTANDARD NAMING
require(_owner != address(0), "WF: owner cannot be null");
require(_modules.length > 0, "WF: cannot assign with less than 1 module");
require(ModuleRegistry(moduleRegistry).ISREGISTEREDMODULE404(_modules), "WF: one or more modules are not registered");
bytes memory labelBytes = bytes(_label);
require(labelBytes.length != 0, "WF: ENS lable must be defined");
}
function _REGISTERWALLETENS735(address payable _wallet, string memory _label) internal { //inject NONSTANDARD NAMING
// claim reverse
address ensResolver = IENSManager(ensManager).ENSRESOLVER758();
bytes memory methodData = abi.encodeWithSignature("claimWithResolver(address,address)", ensManager, ensResolver);
address ensReverseRegistrar = IENSManager(ensManager).GETENSREVERSEREGISTRAR478();
BaseWallet(_wallet).INVOKE21(ensReverseRegistrar, 0, methodData);
// register with ENS manager
IENSManager(ensManager).REGISTER194(_label, _wallet);
}
}
|
inject NONSTANDARD NAMING
|
function ADDMANAGER871(address _manager) external ONLYOWNER47 {
| 2,513,353
|
./full_match/5/0x7c08b08e17189b2976314eBf6ebfAc1F2A82e3D7/sources/SafuERC721Staking.sol
|
function used by owner to enable or disable the claimRewards function _newState the state of claiming
|
function setClaimingState(bool _newState) external onlyOwner {
claiming = _newState;
}
| 1,886,892
|
pragma solidity 0.5.17;
import './MixinLockCore.sol';
import '@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol';
/**
* @title Mixin for managing `Key` data, as well as the * Approval related functions needed to meet the ERC721
* standard.
* @author HardlyDifficult
* @dev `Mixins` are a design pattern seen in the 0x contracts. It simply
* separates logically groupings of code to ease readability.
*/
contract MixinKeys is
MixinLockCore
{
using SafeMath for uint;
// The struct for a key
struct Key {
uint tokenId;
uint expirationTimestamp;
}
// Emitted when the Lock owner expires a user's Key
event ExpireKey(uint indexed tokenId);
// Emitted when the expiration of a key is modified
event ExpirationChanged(
uint indexed _tokenId,
uint _amount,
bool _timeAdded
);
event KeyManagerChanged(uint indexed _tokenId, address indexed _newManager);
// Keys
// Each owner can have at most exactly one key
// TODO: could we use public here? (this could be confusing though because it getter will
// return 0 values when missing a key)
mapping (address => Key) internal keyByOwner;
// Each tokenId can have at most exactly one owner at a time.
// Returns 0 if the token does not exist
// TODO: once we decouple tokenId from owner address (incl in js), then we can consider
// merging this with totalSupply into an array instead.
mapping (uint => address) internal _ownerOf;
// Addresses of owners are also stored in an array.
// Addresses are never removed by design to avoid abuses around referals
address[] public owners;
// A given key has both an owner and a manager.
// If keyManager == address(0) then the key owner is also the manager
// Each key can have at most 1 keyManager.
mapping (uint => address) public keyManagerOf;
// Keeping track of approved transfers
// This is a mapping of addresses which have approved
// the transfer of a key to another address where their key can be transferred
// Note: the approver may actually NOT have a key... and there can only
// be a single approved address
mapping (uint => address) private approved;
// Keeping track of approved operators for a given Key manager.
// This approves a given operator for all keys managed by the calling "keyManager"
// The caller may not currently be the keyManager for ANY keys.
// These approvals are never reset/revoked automatically, unlike "approved",
// which is reset on transfer.
mapping (address => mapping (address => bool)) private managerToOperatorApproved;
// Ensure that the caller is the keyManager of the key
// or that the caller has been approved
// for ownership of that key
modifier onlyKeyManagerOrApproved(
uint _tokenId
)
{
require(
_isKeyManager(_tokenId, msg.sender) ||
_isApproved(_tokenId, msg.sender) ||
isApprovedForAll(_ownerOf[_tokenId], msg.sender),
'ONLY_KEY_MANAGER_OR_APPROVED'
);
_;
}
// Ensures that an owner owns or has owned a key in the past
modifier ownsOrHasOwnedKey(
address _keyOwner
) {
require(
keyByOwner[_keyOwner].expirationTimestamp > 0, 'HAS_NEVER_OWNED_KEY'
);
_;
}
// Ensures that an owner has a valid key
modifier hasValidKey(
address _user
) {
require(
getHasValidKey(_user), 'KEY_NOT_VALID'
);
_;
}
// Ensures that a key has an owner
modifier isKey(
uint _tokenId
) {
require(
_ownerOf[_tokenId] != address(0), 'NO_SUCH_KEY'
);
_;
}
// Ensure that the caller owns the key
modifier onlyKeyOwner(
uint _tokenId
) {
require(
ownerOf(_tokenId) == msg.sender, 'ONLY_KEY_OWNER'
);
_;
}
/**
* In the specific case of a Lock, each owner can own only at most 1 key.
* @return The number of NFTs owned by `_keyOwner`, either 0 or 1.
*/
function balanceOf(
address _keyOwner
)
public
view
returns (uint)
{
require(_keyOwner != address(0), 'INVALID_ADDRESS');
return getHasValidKey(_keyOwner) ? 1 : 0;
}
/**
* Checks if the user has a non-expired key.
*/
function getHasValidKey(
address _keyOwner
)
public
view
returns (bool)
{
return keyByOwner[_keyOwner].expirationTimestamp > block.timestamp;
}
/**
* @notice Find the tokenId for a given user
* @return The tokenId of the NFT, else returns 0
*/
function getTokenIdFor(
address _account
) public view
returns (uint)
{
return keyByOwner[_account].tokenId;
}
/**
* @dev Returns the key's ExpirationTimestamp field for a given owner.
* @param _keyOwner address of the user for whom we search the key
* @dev Returns 0 if the owner has never owned a key for this lock
*/
function keyExpirationTimestampFor(
address _keyOwner
) public view
returns (uint)
{
return keyByOwner[_keyOwner].expirationTimestamp;
}
/**
* Public function which returns the total number of unique owners (both expired
* and valid). This may be larger than totalSupply.
*/
function numberOfOwners()
public
view
returns (uint)
{
return owners.length;
}
// Returns the owner of a given tokenId
function ownerOf(
uint _tokenId
) public view
returns(address)
{
return _ownerOf[_tokenId];
}
/**
* @notice Public function for updating transfer and cancel rights for a given key
* @param _tokenId The id of the key to assign rights for
* @param _keyManager The address with the manager's rights for the given key.
* Setting _keyManager to address(0) means the keyOwner is also the keyManager
*/
function setKeyManagerOf(
uint _tokenId,
address _keyManager
) public
isKey(_tokenId)
{
require(
_isKeyManager(_tokenId, msg.sender) ||
isLockManager(msg.sender),
'UNAUTHORIZED_KEY_MANAGER_UPDATE'
);
_setKeyManagerOf(_tokenId, _keyManager);
}
function _setKeyManagerOf(
uint _tokenId,
address _keyManager
) internal
{
if(keyManagerOf[_tokenId] != _keyManager) {
keyManagerOf[_tokenId] = _keyManager;
_clearApproval(_tokenId);
emit KeyManagerChanged(_tokenId, address(0));
}
}
/**
* This approves _approved to get ownership of _tokenId.
* Note: that since this is used for both purchase and transfer approvals
* the approved token may not exist.
*/
function approve(
address _approved,
uint _tokenId
)
public
onlyIfAlive
onlyKeyManagerOrApproved(_tokenId)
{
require(msg.sender != _approved, 'APPROVE_SELF');
approved[_tokenId] = _approved;
emit Approval(_ownerOf[_tokenId], _approved, _tokenId);
}
/**
* @notice Get the approved address for a single NFT
* @dev Throws if `_tokenId` is not a valid NFT.
* @param _tokenId The NFT to find the approved address for
* @return The approved address for this NFT, or the zero address if there is none
*/
function getApproved(
uint _tokenId
) public view
isKey(_tokenId)
returns (address)
{
address approvedRecipient = approved[_tokenId];
return approvedRecipient;
}
/**
* @dev Tells whether an operator is approved by a given keyManager
* @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)
{
uint tokenId = keyByOwner[_owner].tokenId;
address keyManager = keyManagerOf[tokenId];
if(keyManager == address(0)) {
return managerToOperatorApproved[_owner][_operator];
} else {
return managerToOperatorApproved[keyManager][_operator];
}
}
/**
* Returns true if _keyManager is the manager of the key
* identified by _tokenId
*/
function _isKeyManager(
uint _tokenId,
address _keyManager
) internal view
returns (bool)
{
if(keyManagerOf[_tokenId] == _keyManager ||
(keyManagerOf[_tokenId] == address(0) && ownerOf(_tokenId) == _keyManager)) {
return true;
} else {
return false;
}
}
/**
* Assigns the key a new tokenId (from totalSupply) if it does not already have
* one assigned.
*/
function _assignNewTokenId(
Key storage _key
) internal
{
if (_key.tokenId == 0) {
// This is a brand new owner
// We increment the tokenId counter
_totalSupply++;
// we assign the incremented `_totalSupply` as the tokenId for the new key
_key.tokenId = _totalSupply;
}
}
/**
* Records the owner of a given tokenId
*/
function _recordOwner(
address _keyOwner,
uint _tokenId
) internal
{
if (ownerOf(_tokenId) != _keyOwner) {
// TODO: this may include duplicate entries
owners.push(_keyOwner);
// We register the owner of the tokenID
_ownerOf[_tokenId] = _keyOwner;
}
}
/**
* @notice Modify the expirationTimestamp of a key
* by a given amount.
* @param _tokenId The ID of the key to modify.
* @param _deltaT The amount of time in seconds by which
* to modify the keys expirationTimestamp
* @param _addTime Choose whether to increase or decrease
* expirationTimestamp (false == decrease, true == increase)
* @dev Throws if owner does not have a valid key.
*/
function _timeMachine(
uint _tokenId,
uint256 _deltaT,
bool _addTime
) internal
{
address tokenOwner = ownerOf(_tokenId);
require(tokenOwner != address(0), 'NON_EXISTENT_KEY');
Key storage key = keyByOwner[tokenOwner];
uint formerTimestamp = key.expirationTimestamp;
bool validKey = getHasValidKey(tokenOwner);
if(_addTime) {
if(validKey) {
key.expirationTimestamp = formerTimestamp.add(_deltaT);
} else {
key.expirationTimestamp = block.timestamp.add(_deltaT);
}
} else {
key.expirationTimestamp = formerTimestamp.sub(_deltaT);
}
emit ExpirationChanged(_tokenId, _deltaT, _addTime);
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(
address _to,
bool _approved
) public
onlyIfAlive
{
require(_to != msg.sender, 'APPROVE_SELF');
managerToOperatorApproved[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Checks if the given user is approved to transfer the tokenId.
*/
function _isApproved(
uint _tokenId,
address _user
) internal view
returns (bool)
{
return approved[_tokenId] == _user;
}
/**
* @dev Function to clear current approval of a given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function _clearApproval(
uint256 _tokenId
) internal
{
if (approved[_tokenId] != address(0)) {
approved[_tokenId] = address(0);
}
}
}
|
Modify the expirationTimestamp of a key by a given amount. _tokenId The ID of the key to modify. _deltaT The amount of time in seconds by which to modify the keys expirationTimestamp _addTime Choose whether to increase or decrease expirationTimestamp (false == decrease, true == increase) Throws if owner does not have a valid key./
|
function _timeMachine(
uint _tokenId,
uint256 _deltaT,
bool _addTime
) internal
{
address tokenOwner = ownerOf(_tokenId);
require(tokenOwner != address(0), 'NON_EXISTENT_KEY');
Key storage key = keyByOwner[tokenOwner];
uint formerTimestamp = key.expirationTimestamp;
bool validKey = getHasValidKey(tokenOwner);
if(_addTime) {
if(validKey) {
key.expirationTimestamp = formerTimestamp.add(_deltaT);
key.expirationTimestamp = block.timestamp.add(_deltaT);
}
key.expirationTimestamp = formerTimestamp.sub(_deltaT);
}
emit ExpirationChanged(_tokenId, _deltaT, _addTime);
}
| 2,561,892
|
//Address: 0x9464e7d6dc5e8f34d162f3ca190d788f8ce8cc13
//Contract name: GPower
//Balance: 0 Ether
//Verification Date: 1/12/2018
//Transacion Count: 300
// CODE STARTS HERE
pragma solidity ^0.4.13;
library SafeMath {
function mul(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal constant returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal constant returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal constant returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract Ownable {
address public owner;
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) onlyOwner {
if (newOwner != address(0)) {
owner = newOwner;
}
}
}
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) constant returns (uint256);
function transfer(address to, uint256 value) returns (bool);
event Transfer(address indexed _from, address indexed _to, uint _value);
}
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) returns (bool) {
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return balances[_owner];
}
}
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) constant returns (uint256);
function transferFrom(address from, address to, uint256 value) returns (bool);
function approve(address spender, uint256 value) returns (bool);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amout of tokens to be transfered
*/
function transferFrom(address _from, address _to, uint256 _value) returns (bool) {
var _allowance = allowed[_from][msg.sender];
// Check is not needed because sub(_allowance, _value) will already throw if this condition is not met
// require (_value <= _allowance);
// KYBER-NOTE! code changed to comply with ERC20 standard
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
//balances[_from] = balances[_from].sub(_value); // this was removed
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender.
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) returns (bool) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifing the amount of tokens still avaible for the spender.
*/
function allowance(address _owner, address _spender) constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract GPower is StandardToken, Ownable {
string public constant name = "GPower";
string public constant symbol = "GRP";
uint public constant decimals = 18;
//*** ICO ***//
uint icoStart;
uint256 icoSaleTotalTokens=400000000;
address icoAddress;
bool public enableIco=false;
//*** Walet ***//
address public wallet;
//*** TranferCoin ***//
bool public transferEnabled = false;
bool public stopSale=false;
uint256 newCourceSale=0;
function GPower() {
// Mint all tokens. Then disable minting forever.
totalSupply = (500000000*1000000000000000000);
balances[msg.sender] = totalSupply;
Transfer(address(0x0), msg.sender, totalSupply);
transferOwnership(msg.sender);
}
//*** Transfer Enabled ***//
modifier onlyWhenTransferEnabled() {
if(transferEnabled){
require(true);
}
else if(transferEnabled==false && msg.sender==owner){
require(true);
}
else{
require(false);
}
_;
}
modifier validDestination( address to ) {
require(to != address(0x0));
require(to != address(this) );
_;
}
//*** Payable ***//
function() payable public {
require(msg.value>0);
require(msg.sender != 0x0);
wallet=owner;
if(!stopSale){
uint256 weiAmount;
uint256 tokens;
wallet=owner;
wallet=icoAddress;
if((icoStart+(7*24*60*60)) >= now){
weiAmount=4000;
}
else if((icoStart+(14*24*60*60)) >= now){
weiAmount=3750;
}
else if((icoStart+(21*24*60*60)) >= now){
weiAmount=3500;
}
else if((icoStart+(28*24*60*60)) >= now){
weiAmount=3250;
}
else if((icoStart+(35*24*60*60)) >= now){
weiAmount=3000;
}
else{
weiAmount=2000;
}
}
wallet.transfer(msg.value);
}
//*** Transfer ***//
function transfer(address _to, uint _value)
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transfer(_to, _value);
}
//*** Transfer From ***//
function transferFrom(address _from, address _to, uint _value)
onlyWhenTransferEnabled
validDestination(_to)
returns (bool) {
return super.transferFrom(_from, _to, _value);
}
event Burn(address indexed _burner, uint _value);
//*** Burn ***//
function burn(uint _value) onlyWhenTransferEnabled
returns (bool){
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(msg.sender, _value);
Transfer(msg.sender, address(0x0), _value);
return true;
}
//*** Burn From ***//
function burnFrom(address _from, uint256 _value) onlyWhenTransferEnabled
returns (bool) {
assert( transferFrom( _from, msg.sender, _value ) );
return burn(_value);
}
//*** EmergencyERC20Drain ***//
function emergencyERC20Drain(ERC20 token, uint amount ) onlyOwner {
token.transfer( owner, amount );
}
//*** Set CourceSale ***//
function setCourceSale(uint256 value) public onlyOwner{
newCourceSale=value;
}
//*** Set Params For Sale ***//
function setParamsStopSale(bool _value) public onlyOwner{
stopSale=_value;
}
//*** Set ParamsTransfer ***//
function setParamsTransfer(bool _value) public onlyOwner{
transferEnabled=_value;
}
//*** Set ParamsICO ***//
function setParamsIco(bool _value) public onlyOwner returns(bool result){
enableIco=_value;
return true;
}
//*** Set ParamsICO ***//
function startIco(uint _value) public onlyOwner returns(bool result){
stopSale=false;
icoStart=_value;
enableIco=true;
return true;
}
//*** Set Params For TotalSupply ***//
function setParamsTotalSupply(uint256 value) public onlyOwner{
totalSupply=value;
}
}
|
Set CourceSale
|
function setCourceSale(uint256 value) public onlyOwner{
newCourceSale=value;
}
| 14,094,124
|
// File: @openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/drafts/SignedSafeMath.sol
pragma solidity ^0.5.0;
/**
* @title SignedSafeMath
* @dev Signed math operations with safety checks that revert on error.
*/
library SignedSafeMath {
int256 constant private INT256_MIN = -2**255;
/**
* @dev Multiplies two signed integers, reverts on 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 Integer division of two signed integers truncating the quotient, reverts on division by 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 Subtracts two signed integers, reverts on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow");
return c;
}
/**
* @dev Adds two signed integers, reverts on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow");
return c;
}
}
// File: @openzeppelin/upgrades/contracts/Initializable.sol
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;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/GSN/Context.sol
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Initializable, Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function initialize(address sender) public initializer {
_owner = sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[50] private ______gap;
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol
pragma solidity ^0.5.5;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
// File: @openzeppelin/contracts-ethereum-package/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.5.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).isContract(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @0x/contracts-utils/contracts/src/LibEIP712.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibEIP712 {
// Hash of the EIP712 Domain Separator Schema
// keccak256(abi.encodePacked(
// "EIP712Domain(",
// "string name,",
// "string version,",
// "uint256 chainId,",
// "address verifyingContract",
// ")"
// ))
bytes32 constant internal _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH = 0x8b73c3c69bb8fe3d512ecc4cf759cc79239f7b179b0ffacaa9a75d522b39400f;
/// @dev Calculates a EIP712 domain separator.
/// @param name The EIP712 domain name.
/// @param version The EIP712 domain version.
/// @param verifyingContract The EIP712 verifying contract.
/// @return EIP712 domain separator.
function hashEIP712Domain(
string memory name,
string memory version,
uint256 chainId,
address verifyingContract
)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH;
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// _EIP712_DOMAIN_SEPARATOR_SCHEMA_HASH,
// keccak256(bytes(name)),
// keccak256(bytes(version)),
// chainId,
// uint256(verifyingContract)
// ))
assembly {
// Calculate hashes of dynamic data
let nameHash := keccak256(add(name, 32), mload(name))
let versionHash := keccak256(add(version, 32), mload(version))
// Load free memory pointer
let memPtr := mload(64)
// Store params in memory
mstore(memPtr, schemaHash)
mstore(add(memPtr, 32), nameHash)
mstore(add(memPtr, 64), versionHash)
mstore(add(memPtr, 96), chainId)
mstore(add(memPtr, 128), verifyingContract)
// Compute hash
result := keccak256(memPtr, 160)
}
return result;
}
/// @dev Calculates EIP712 encoding for a hash struct with a given domain hash.
/// @param eip712DomainHash Hash of the domain domain separator data, computed
/// with getDomainHash().
/// @param hashStruct The EIP712 hash struct.
/// @return EIP712 hash applied to the given EIP712 Domain.
function hashEIP712Message(bytes32 eip712DomainHash, bytes32 hashStruct)
internal
pure
returns (bytes32 result)
{
// Assembly for more efficient computing:
// keccak256(abi.encodePacked(
// EIP191_HEADER,
// EIP712_DOMAIN_HASH,
// hashStruct
// ));
assembly {
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, 0x1901000000000000000000000000000000000000000000000000000000000000) // EIP191 header
mstore(add(memPtr, 2), eip712DomainHash) // EIP712 domain hash
mstore(add(memPtr, 34), hashStruct) // Hash of struct
// Compute hash
result := keccak256(memPtr, 66)
}
return result;
}
}
// File: @0x/contracts-exchange-libs/contracts/src/LibOrder.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibOrder {
using LibOrder for Order;
// Hash for the EIP712 Order Schema:
// keccak256(abi.encodePacked(
// "Order(",
// "address makerAddress,",
// "address takerAddress,",
// "address feeRecipientAddress,",
// "address senderAddress,",
// "uint256 makerAssetAmount,",
// "uint256 takerAssetAmount,",
// "uint256 makerFee,",
// "uint256 takerFee,",
// "uint256 expirationTimeSeconds,",
// "uint256 salt,",
// "bytes makerAssetData,",
// "bytes takerAssetData,",
// "bytes makerFeeAssetData,",
// "bytes takerFeeAssetData",
// ")"
// ))
bytes32 constant internal _EIP712_ORDER_SCHEMA_HASH =
0xf80322eb8376aafb64eadf8f0d7623f22130fd9491a221e902b713cb984a7534;
// A valid order remains fillable until it is expired, fully filled, or cancelled.
// An order's status is unaffected by external factors, like account balances.
enum OrderStatus {
INVALID, // Default value
INVALID_MAKER_ASSET_AMOUNT, // Order does not have a valid maker asset amount
INVALID_TAKER_ASSET_AMOUNT, // Order does not have a valid taker asset amount
FILLABLE, // Order is fillable
EXPIRED, // Order has already expired
FULLY_FILLED, // Order is fully filled
CANCELLED // Order has been cancelled
}
// solhint-disable max-line-length
/// @dev Canonical order structure.
struct Order {
address makerAddress; // Address that created the order.
address takerAddress; // Address that is allowed to fill the order. If set to 0, any address is allowed to fill the order.
address feeRecipientAddress; // Address that will recieve fees when order is filled.
address senderAddress; // Address that is allowed to call Exchange contract methods that affect this order. If set to 0, any address is allowed to call these methods.
uint256 makerAssetAmount; // Amount of makerAsset being offered by maker. Must be greater than 0.
uint256 takerAssetAmount; // Amount of takerAsset being bid on by maker. Must be greater than 0.
uint256 makerFee; // Fee paid to feeRecipient by maker when order is filled.
uint256 takerFee; // Fee paid to feeRecipient by taker when order is filled.
uint256 expirationTimeSeconds; // Timestamp in seconds at which order expires.
uint256 salt; // Arbitrary number to facilitate uniqueness of the order's hash.
bytes makerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerAsset. The leading bytes4 references the id of the asset proxy.
bytes takerAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerAsset. The leading bytes4 references the id of the asset proxy.
bytes makerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring makerFeeAsset. The leading bytes4 references the id of the asset proxy.
bytes takerFeeAssetData; // Encoded data that can be decoded by a specified proxy contract when transferring takerFeeAsset. The leading bytes4 references the id of the asset proxy.
}
// solhint-enable max-line-length
/// @dev Order information returned by `getOrderInfo()`.
struct OrderInfo {
OrderStatus orderStatus; // Status that describes order's validity and fillability.
bytes32 orderHash; // EIP712 typed data hash of the order (see LibOrder.getTypedDataHash).
uint256 orderTakerAssetFilledAmount; // Amount of order that has already been filled.
}
/// @dev Calculates the EIP712 typed data hash of an order with a given domain separator.
/// @param order The order structure.
/// @return EIP712 typed data hash of the order.
function getTypedDataHash(Order memory order, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 orderHash)
{
orderHash = LibEIP712.hashEIP712Message(
eip712ExchangeDomainHash,
order.getStructHash()
);
return orderHash;
}
/// @dev Calculates EIP712 hash of the order struct.
/// @param order The order structure.
/// @return EIP712 hash of the order struct.
function getStructHash(Order memory order)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_ORDER_SCHEMA_HASH;
bytes memory makerAssetData = order.makerAssetData;
bytes memory takerAssetData = order.takerAssetData;
bytes memory makerFeeAssetData = order.makerFeeAssetData;
bytes memory takerFeeAssetData = order.takerFeeAssetData;
// Assembly for more efficiently computing:
// keccak256(abi.encodePacked(
// EIP712_ORDER_SCHEMA_HASH,
// uint256(order.makerAddress),
// uint256(order.takerAddress),
// uint256(order.feeRecipientAddress),
// uint256(order.senderAddress),
// order.makerAssetAmount,
// order.takerAssetAmount,
// order.makerFee,
// order.takerFee,
// order.expirationTimeSeconds,
// order.salt,
// keccak256(order.makerAssetData),
// keccak256(order.takerAssetData),
// keccak256(order.makerFeeAssetData),
// keccak256(order.takerFeeAssetData)
// ));
assembly {
// Assert order offset (this is an internal error that should never be triggered)
if lt(order, 32) {
invalid()
}
// Calculate memory addresses that will be swapped out before hashing
let pos1 := sub(order, 32)
let pos2 := add(order, 320)
let pos3 := add(order, 352)
let pos4 := add(order, 384)
let pos5 := add(order, 416)
// Backup
let temp1 := mload(pos1)
let temp2 := mload(pos2)
let temp3 := mload(pos3)
let temp4 := mload(pos4)
let temp5 := mload(pos5)
// Hash in place
mstore(pos1, schemaHash)
mstore(pos2, keccak256(add(makerAssetData, 32), mload(makerAssetData))) // store hash of makerAssetData
mstore(pos3, keccak256(add(takerAssetData, 32), mload(takerAssetData))) // store hash of takerAssetData
mstore(pos4, keccak256(add(makerFeeAssetData, 32), mload(makerFeeAssetData))) // store hash of makerFeeAssetData
mstore(pos5, keccak256(add(takerFeeAssetData, 32), mload(takerFeeAssetData))) // store hash of takerFeeAssetData
result := keccak256(pos1, 480)
// Restore
mstore(pos1, temp1)
mstore(pos2, temp2)
mstore(pos3, temp3)
mstore(pos4, temp4)
mstore(pos5, temp5)
}
return result;
}
}
// File: @0x/contracts-erc20/contracts/src/interfaces/IERC20Token.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IERC20Token {
// solhint-disable no-simple-event-func-name
event Transfer(
address indexed _from,
address indexed _to,
uint256 _value
);
event Approval(
address indexed _owner,
address indexed _spender,
uint256 _value
);
/// @dev send `value` token to `to` from `msg.sender`
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return True if transfer was successful
function transfer(address _to, uint256 _value)
external
returns (bool);
/// @dev send `value` token to `to` from `from` on the condition it is approved by `from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return True if transfer was successful
function transferFrom(
address _from,
address _to,
uint256 _value
)
external
returns (bool);
/// @dev `msg.sender` approves `_spender` to spend `_value` tokens
/// @param _spender The address of the account able to transfer the tokens
/// @param _value The amount of wei to be approved for transfer
/// @return Always true if the call has enough gas to complete execution
function approve(address _spender, uint256 _value)
external
returns (bool);
/// @dev Query total supply of token
/// @return Total supply of token
function totalSupply()
external
view
returns (uint256);
/// @param _owner The address from which the balance will be retrieved
/// @return Balance of owner
function balanceOf(address _owner)
external
view
returns (uint256);
/// @param _owner The address of the account owning tokens
/// @param _spender The address of the account able to transfer the tokens
/// @return Amount of remaining tokens allowed to spent
function allowance(address _owner, address _spender)
external
view
returns (uint256);
}
// File: @0x/contracts-erc20/contracts/src/interfaces/IEtherToken.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IEtherToken is
IERC20Token
{
function deposit()
public
payable;
function withdraw(uint256 amount)
public;
}
// File: contracts/external/dydx/lib/Account.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.17;
pragma experimental ABIEncoderV2;
/**
* @title Account
* @author dYdX
*
* Library of structs and functions that represent an account
*/
library Account {
// Represents the unique key that specifies an account
struct Info {
address owner; // The address that owns the account
uint256 number; // A nonce that allows a single address to control many accounts
}
}
// File: contracts/external/dydx/lib/Types.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.17;
/**
* @title Types
* @author dYdX
*
* Library for interacting with the basic structs used in Solo
*/
library Types {
// ============ AssetAmount ============
enum AssetDenomination {
Wei, // the amount is denominated in wei
Par // the amount is denominated in par
}
enum AssetReference {
Delta, // the amount is given as a delta from the current value
Target // the amount is given as an exact number to end up at
}
struct AssetAmount {
bool sign; // true if positive
AssetDenomination denomination;
AssetReference ref;
uint256 value;
}
// ============ Par (Principal Amount) ============
// Individual principal amount for an account
struct Par {
bool sign; // true if positive
uint128 value;
}
// ============ Wei (Token Amount) ============
// Individual token amount for an account
struct Wei {
bool sign; // true if positive
uint256 value;
}
}
// File: contracts/external/dydx/Getters.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.17;
/**
* @title Getters
* @author dYdX
*
* Public read-only functions that allow transparency into the state of Solo
*/
contract Getters {
using Types for Types.Par;
/**
* Get an account's summary for each market.
*
* @param account The account to query
* @return The following values:
* - The ERC20 token address for each market
* - The account's principal value for each market
* - The account's (supplied or borrowed) number of tokens for each market
*/
function getAccountBalances(
Account.Info memory account
)
public
view
returns (
address[] memory,
Types.Par[] memory,
Types.Wei[] memory
);
}
// File: contracts/external/dydx/lib/Actions.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.17;
/**
* @title Actions
* @author dYdX
*
* Library that defines and parses valid Actions
*/
library Actions {
// ============ Enums ============
enum ActionType {
Deposit, // supply tokens
Withdraw, // borrow tokens
Transfer, // transfer balance between accounts
Buy, // buy an amount of some token (externally)
Sell, // sell an amount of some token (externally)
Trade, // trade tokens against another account
Liquidate, // liquidate an undercollateralized or expiring account
Vaporize, // use excess tokens to zero-out a completely negative account
Call // send arbitrary data to an address
}
// ============ Structs ============
/*
* Arguments that are passed to Solo in an ordered list as part of a single operation.
* Each ActionArgs has an actionType which specifies which action struct that this data will be
* parsed into before being processed.
*/
struct ActionArgs {
ActionType actionType;
uint256 accountId;
Types.AssetAmount amount;
uint256 primaryMarketId;
uint256 secondaryMarketId;
address otherAddress;
uint256 otherAccountId;
bytes data;
}
}
// File: contracts/external/dydx/Operation.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.17;
/**
* @title Operation
* @author dYdX
*
* Primary public function for allowing users and contracts to manage accounts within Solo
*/
contract Operation {
/**
* The main entry-point to Solo that allows users and contracts to manage accounts.
* Take one or more actions on one or more accounts. The msg.sender must be the owner or
* operator of all accounts except for those being liquidated, vaporized, or traded with.
* One call to operate() is considered a singular "operation". Account collateralization is
* ensured only after the completion of the entire operation.
*
* @param accounts A list of all accounts that will be used in this operation. Cannot contain
* duplicates. In each action, the relevant account will be referred-to by its
* index in the list.
* @param actions An ordered list of all actions that will be taken in this operation. The
* actions will be processed in order.
*/
function operate(
Account.Info[] memory accounts,
Actions.ActionArgs[] memory actions
)
public;
}
// File: contracts/external/dydx/SoloMargin.sol
/*
Copyright 2019 dYdX Trading Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity 0.5.17;
/**
* @title SoloMargin
* @author dYdX
*
* Main contract that inherits from other contracts
*/
contract SoloMargin is
Getters,
Operation
{ }
// File: contracts/lib/pools/DydxPoolController.sol
/**
* COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title DydxPoolController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb)
* @dev This library handles deposits to and withdrawals from dYdX liquidity pools.
*/
library DydxPoolController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address constant private SOLO_MARGIN_CONTRACT = 0x1E0447b19BB6EcFdAe1e4AE1694b0C3659614e4e;
SoloMargin constant private _soloMargin = SoloMargin(SOLO_MARGIN_CONTRACT);
uint256 constant private WETH_MARKET_ID = 0;
address constant private WETH_CONTRACT = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
IEtherToken constant private _weth = IEtherToken(WETH_CONTRACT);
/**
* @dev Returns the fund's balance of the specified currency in the dYdX pool.
*/
function getBalance() external view returns (uint256) {
Account.Info memory account = Account.Info(address(this), 0);
(, , Types.Wei[] memory weis) = _soloMargin.getAccountBalances(account);
return weis[WETH_MARKET_ID].sign ? weis[WETH_MARKET_ID].value : 0;
}
/**
* @dev Approves WETH to dYdX without spending gas on every deposit.
* @param amount Amount of the WETH to approve to dYdX.
*/
function approve(uint256 amount) external {
uint256 allowance = _weth.allowance(address(this), SOLO_MARGIN_CONTRACT);
if (allowance == amount) return;
if (amount > 0 && allowance > 0) _weth.approve(SOLO_MARGIN_CONTRACT, 0);
_weth.approve(SOLO_MARGIN_CONTRACT, amount);
}
/**
* @dev Deposits funds to the dYdX pool. Assumes that you have already approved >= the amount of WETH to dYdX.
* @param amount The amount of ETH to be deposited.
*/
function deposit(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
_weth.deposit.value(amount)();
Account.Info memory account = Account.Info(address(this), 0);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = account;
Types.AssetAmount memory assetAmount = Types.AssetAmount(true, Types.AssetDenomination.Wei, Types.AssetReference.Delta, amount);
bytes memory emptyData;
Actions.ActionArgs memory action = Actions.ActionArgs(
Actions.ActionType.Deposit,
0,
assetAmount,
WETH_MARKET_ID,
0,
address(this),
0,
emptyData
);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
actions[0] = action;
_soloMargin.operate(accounts, actions);
}
/**
* @dev Withdraws funds from the dYdX pool.
* @param amount The amount of ETH to be withdrawn.
*/
function withdraw(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
Account.Info memory account = Account.Info(address(this), 0);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = account;
Types.AssetAmount memory assetAmount = Types.AssetAmount(false, Types.AssetDenomination.Wei, Types.AssetReference.Delta, amount);
bytes memory emptyData;
Actions.ActionArgs memory action = Actions.ActionArgs(
Actions.ActionType.Withdraw,
0,
assetAmount,
WETH_MARKET_ID,
0,
address(this),
0,
emptyData
);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
actions[0] = action;
_soloMargin.operate(accounts, actions);
_weth.withdraw(amount); // Convert WETH to ETH
}
/**
* @dev Withdraws all funds from the dYdX pool.
*/
function withdrawAll() external {
Account.Info memory account = Account.Info(address(this), 0);
Account.Info[] memory accounts = new Account.Info[](1);
accounts[0] = account;
Types.AssetAmount memory assetAmount = Types.AssetAmount(true, Types.AssetDenomination.Par, Types.AssetReference.Target, 0);
bytes memory emptyData;
Actions.ActionArgs memory action = Actions.ActionArgs(
Actions.ActionType.Withdraw,
0,
assetAmount,
WETH_MARKET_ID,
0,
address(this),
0,
emptyData
);
Actions.ActionArgs[] memory actions = new Actions.ActionArgs[](1);
actions[0] = action;
_soloMargin.operate(accounts, actions);
_weth.withdraw(_weth.balanceOf(address(this))); // Convert WETH to ETH
}
}
// File: contracts/external/compound/CEther.sol
/**
* Copyright 2020 Compound Labs, Inc.
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
pragma solidity 0.5.17;
/**
* @title Compound's CEther Contract
* @notice CToken which wraps Ether
* @author Compound
*/
interface CEther {
function mint() external payable;
function redeem(uint redeemTokens) external returns (uint);
function redeemUnderlying(uint redeemAmount) external returns (uint);
function balanceOf(address account) external view returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
}
// File: contracts/lib/pools/CompoundPoolController.sol
/**
* COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title CompoundPoolController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb)
* @dev This library handles deposits to and withdrawals from Compound liquidity pools.
*/
library CompoundPoolController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address constant private cETH_CONTACT_ADDRESS = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5;
CEther constant private _cETHContract = CEther(cETH_CONTACT_ADDRESS);
/**
* @dev Returns the fund's balance of the specified currency in the Compound pool.
*/
function getBalance() external returns (uint256) {
return _cETHContract.balanceOfUnderlying(address(this));
}
/**
* @dev Deposits funds to the Compound pool. Assumes that you have already approved >= the amount to Compound.
* @param amount The amount of tokens to be deposited.
*/
function deposit(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
_cETHContract.mint.value(amount)();
}
/**
* @dev Withdraws funds from the Compound pool.
* @param amount The amount of tokens to be withdrawn.
*/
function withdraw(uint256 amount) external {
require(amount > 0, "Amount must be greater than to 0.");
uint256 redeemResult = _cETHContract.redeemUnderlying(amount);
require(redeemResult == 0, "Error calling redeemUnderlying on Compound cToken: error code not equal to 0");
}
/**
* @dev Withdraws all funds from the Compound pool.
* @return Boolean indicating success.
*/
function withdrawAll() external returns (bool) {
uint256 balance = _cETHContract.balanceOf(address(this));
if (balance <= 0) return false;
uint256 redeemResult = _cETHContract.redeem(balance);
require(redeemResult == 0, "Error calling redeem on Compound cToken: error code not equal to 0");
return true;
}
}
// File: contracts/external/keeperdao/IKToken.sol
pragma solidity 0.5.17;
interface IKToken {
function underlying() external view returns (address);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function approve(address spender, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function mint(address recipient, uint256 amount) external returns (bool);
function burnFrom(address sender, uint256 amount) external;
function addMinter(address sender) external;
function renounceMinter() external;
}
// File: contracts/external/keeperdao/ILiquidityPool.sol
pragma solidity 0.5.17;
interface ILiquidityPool {
function () external payable;
function kToken(address _token) external view returns (IKToken);
function register(IKToken _kToken) external;
function renounceOperator() external;
function deposit(address _token, uint256 _amount) external payable returns (uint256);
function withdraw(address payable _to, IKToken _kToken, uint256 _kTokenAmount) external;
function borrowableBalance(address _token) external view returns (uint256);
function underlyingBalance(address _token, address _owner) external view returns (uint256);
}
// File: contracts/lib/pools/KeeperDaoPoolController.sol
/**
* COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title KeeperDaoPoolController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb)
* @dev This library handles deposits to and withdrawals from KeeperDAO liquidity pools.
*/
library KeeperDaoPoolController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address payable constant private KEEPERDAO_CONTRACT = 0x35fFd6E268610E764fF6944d07760D0EFe5E40E5;
ILiquidityPool constant private _liquidityPool = ILiquidityPool(KEEPERDAO_CONTRACT);
// KeeperDAO's representation of ETH
address constant private ETHEREUM_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/**
* @dev Returns the fund's balance in the KeeperDAO pool.
*/
function getBalance() external view returns (uint256) {
return _liquidityPool.underlyingBalance(ETHEREUM_ADDRESS, address(this));
}
/**
* @dev Approves kEther to KeeperDAO to burn without spending gas on every deposit.
* @param amount Amount of kEther to approve to KeeperDAO.
*/
function approve(uint256 amount) external {
IKToken kEther = _liquidityPool.kToken(ETHEREUM_ADDRESS);
uint256 allowance = kEther.allowance(address(this), KEEPERDAO_CONTRACT);
if (allowance == amount) return;
if (amount > 0 && allowance > 0) kEther.approve(KEEPERDAO_CONTRACT, 0);
kEther.approve(KEEPERDAO_CONTRACT, amount);
}
/**
* @dev Deposits funds to the KeeperDAO pool..
* @param amount The amount of ETH to be deposited.
*/
function deposit(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
_liquidityPool.deposit.value(amount)(ETHEREUM_ADDRESS, amount);
}
/**
* @dev Withdraws funds from the KeeperDAO pool.
* @param amount The amount of ETH to be withdrawn.
*/
function withdraw(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
_liquidityPool.withdraw(address(uint160(address(this))),
_liquidityPool.kToken(ETHEREUM_ADDRESS),
calculatekEtherWithdrawAmount(amount));
}
/**
* @dev Withdraws all funds from the KeeperDAO pool.
* @return Boolean indicating success.
*/
function withdrawAll() external returns (bool) {
IKToken kEther = _liquidityPool.kToken(ETHEREUM_ADDRESS);
uint256 balance = kEther.balanceOf(address(this));
if (balance <= 0) return false;
_liquidityPool.withdraw(address(uint160(address(this))), kEther, balance);
return true;
}
/**
* @dev Calculates an amount of kEther to withdraw equivalent to amount parameter in ETH.
* @return amount to withdraw in kEther.
*/
function calculatekEtherWithdrawAmount(uint256 amount) internal view returns (uint256) {
IKToken kEther = _liquidityPool.kToken(ETHEREUM_ADDRESS);
uint256 totalSupply = kEther.totalSupply();
uint256 borrowableBalance = _liquidityPool.borrowableBalance(ETHEREUM_ADDRESS);
uint256 kEtherAmount = amount.mul(totalSupply).div(borrowableBalance);
if (kEtherAmount.mul(borrowableBalance).div(totalSupply) < amount) kEtherAmount++;
return kEtherAmount;
}
}
// File: contracts/external/aave/LendingPool.sol
/**
* Aave Protocol
* Copyright (C) 2019 Aave
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details
*/
pragma solidity 0.5.17;
/**
* @title LendingPool contract
* @notice Implements the actions of the LendingPool, and exposes accessory methods to fetch the users and reserve data
* @author Aave
*/
contract LendingPool {
/**
* @dev deposits The underlying asset into the reserve. A corresponding amount of the overlying asset (aTokens)
* is minted.
* @param _reserve the address of the reserve
* @param _amount the amount to be deposited
* @param _referralCode integrators are assigned a referral code and can potentially receive rewards.
*/
function deposit(address _reserve, uint256 _amount, uint16 _referralCode) external payable;
}
// File: contracts/external/aave/AToken.sol
/**
* Aave Protocol
* Copyright (C) 2019 Aave
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or any later version.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details
*/
pragma solidity 0.5.17;
/**
* @title Aave ERC20 AToken
* @dev Implementation of the interest bearing token for the DLP protocol.
* @author Aave
*/
contract AToken {
/**
* @dev redeems aToken for the underlying asset
* @param _amount the amount being redeemed
*/
function redeem(uint256 _amount) external;
/**
* @dev calculates the balance of the user, which is the
* principal balance + interest generated by the principal balance + interest generated by the redirected balance
* @param _user the user for which the balance is being calculated
* @return the total balance of the user
*/
function balanceOf(address _user) public view returns (uint256);
}
// File: contracts/lib/pools/AavePoolController.sol
/**
* COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title AavePoolController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb)
* @dev This library handles deposits to and withdrawals from Aave liquidity pools.
*/
library AavePoolController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev Aave LendingPool contract address.
*/
address constant private LENDING_POOL_CONTRACT = 0x398eC7346DcD622eDc5ae82352F02bE94C62d119;
/**
* @dev Aave LendingPool contract object.
*/
LendingPool constant private _lendingPool = LendingPool(LENDING_POOL_CONTRACT);
/**
* @dev Aave LendingPoolCore contract address.
*/
address constant private LENDING_POOL_CORE_CONTRACT = 0x3dfd23A6c5E8BbcFc9581d2E864a68feb6a076d3;
/**
* @dev AETH contract address.
*/
address constant private AETH_CONTRACT = 0x3a3A65aAb0dd2A17E3F1947bA16138cd37d08c04;
/**
* @dev AETH contract.
*/
AToken constant private aETH = AToken(AETH_CONTRACT);
/**
* @dev Ethereum address abstraction
*/
address constant private ETHEREUM_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE);
/**
* @dev Returns the fund's balance of the specified currency in the Aave pool.
*/
function getBalance() external view returns (uint256) {
return aETH.balanceOf(address(this));
}
/**
* @dev Deposits funds to the Aave pool. Assumes that you have already approved >= the amount to Aave.
* @param amount The amount of tokens to be deposited.
* @param referralCode Referral code.
*/
function deposit(uint256 amount, uint16 referralCode) external {
require(amount > 0, "Amount must be greater than 0.");
_lendingPool.deposit.value(amount)(ETHEREUM_ADDRESS, amount, referralCode);
}
/**
* @dev Withdraws funds from the Aave pool.
* @param amount The amount of tokens to be withdrawn.
*/
function withdraw(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
aETH.redeem(amount);
}
/**
* @dev Withdraws all funds from the Aave pool.
*/
function withdrawAll() external {
aETH.redeem(uint256(-1));
}
}
// File: contracts/external/alpha/Bank.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
contract Bank is IERC20 {
/// @dev Return the total ETH entitled to the token holders. Be careful of unaccrued interests.
function totalETH() public view returns (uint256);
/// @dev Add more ETH to the bank. Hope to get some good returns.
function deposit() external payable;
/// @dev Withdraw ETH from the bank by burning the share tokens.
function withdraw(uint256 share) external;
}
// File: contracts/lib/pools/AlphaPoolController.sol
/**
* COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title AlphaPoolController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @dev This library handles deposits to and withdrawals from Alpha Homora's ibETH pool.
*/
library AlphaPoolController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev Alpha Homora ibETH token contract address.
*/
address constant private IBETH_CONTRACT = 0x67B66C99D3Eb37Fa76Aa3Ed1ff33E8e39F0b9c7A;
/**
* @dev Alpha Homora ibETH token contract object.
*/
Bank constant private _ibEth = Bank(IBETH_CONTRACT);
/**
* @dev Returns the fund's balance of the specified currency in the ibETH pool.
*/
function getBalance() external view returns (uint256) {
return _ibEth.balanceOf(address(this)).mul(_ibEth.totalETH()).div(_ibEth.totalSupply());
}
/**
* @dev Deposits funds to the ibETH pool. Assumes that you have already approved >= the amount to the ibETH token contract.
* @param amount The amount of ETH to be deposited.
*/
function deposit(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
_ibEth.deposit.value(amount)();
}
/**
* @dev Withdraws funds from the ibETH pool.
* @param amount The amount of tokens to be withdrawn.
*/
function withdraw(uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
uint256 totalEth = _ibEth.totalETH();
uint256 totalSupply = _ibEth.totalSupply();
uint256 credits = amount.mul(totalSupply).div(totalEth);
if (credits.mul(totalEth).div(totalSupply) < amount) credits++; // Round up if necessary (i.e., if the division above left a remainder)
_ibEth.withdraw(credits);
}
/**
* @dev Withdraws all funds from the ibETH pool.
* @return Boolean indicating success.
*/
function withdrawAll() external returns (bool) {
uint256 balance = _ibEth.balanceOf(address(this));
if (balance <= 0) return false;
_ibEth.withdraw(balance);
return true;
}
}
// File: contracts/external/enzyme/ComptrollerLib.sol
// SPDX-License-Identifier: GPL-3.0
/*
This file is part of the Enzyme Protocol.
(c) Enzyme Council <council@enzyme.finance>
For the full license information, please view the LICENSE
file that was distributed with this source code.
*/
pragma solidity 0.5.17;
/// @title ComptrollerLib Contract
/// @author Enzyme Council <security@enzyme.finance>
/// @notice The core logic library shared by all funds
interface ComptrollerLib {
////////////////
// ACCOUNTING //
////////////////
/// @notice Calculates the gross value of 1 unit of shares in the fund's denomination asset
/// @param _requireFinality True if all assets must have exact final balances settled
/// @return grossShareValue_ The amount of the denomination asset per share
/// @return isValid_ True if the conversion rates to derive the value are all valid
/// @dev Does not account for any fees outstanding.
function calcGrossShareValue(bool _requireFinality)
external
returns (uint256 grossShareValue_, bool isValid_);
///////////////////
// PARTICIPATION //
///////////////////
// BUY SHARES
/// @notice Buys shares in the fund for multiple sets of criteria
/// @param _buyers The accounts for which to buy shares
/// @param _investmentAmounts The amounts of the fund's denomination asset
/// with which to buy shares for the corresponding _buyers
/// @param _minSharesQuantities The minimum quantities of shares to buy
/// with the corresponding _investmentAmounts
/// @return sharesReceivedAmounts_ The actual amounts of shares received
/// by the corresponding _buyers
/// @dev Param arrays have indexes corresponding to individual __buyShares() orders.
function buyShares(
address[] calldata _buyers,
uint256[] calldata _investmentAmounts,
uint256[] calldata _minSharesQuantities
) external returns (uint256[] memory sharesReceivedAmounts_);
// REDEEM SHARES
/// @notice Redeem all of the sender's shares for a proportionate slice of the fund's assets
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev See __redeemShares() for further detail
function redeemShares()
external
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_);
/// @notice Redeem a specified quantity of the sender's shares for a proportionate slice of
/// the fund's assets, optionally specifying additional assets and assets to skip.
/// @param _sharesQuantity The quantity of shares to redeem
/// @param _additionalAssets Additional (non-tracked) assets to claim
/// @param _assetsToSkip Tracked assets to forfeit
/// @return payoutAssets_ The assets paid out to the redeemer
/// @return payoutAmounts_ The amount of each asset paid out to the redeemer
/// @dev Any claim to passed _assetsToSkip will be forfeited entirely. This should generally
/// only be exercised if a bad asset is causing redemption to fail.
function redeemSharesDetailed(
uint256 _sharesQuantity,
address[] calldata _additionalAssets,
address[] calldata _assetsToSkip
)
external
returns (address[] memory payoutAssets_, uint256[] memory payoutAmounts_);
///////////////////
// STATE GETTERS //
///////////////////
/// @notice Gets the `vaultProxy` variable
/// @return vaultProxy_ The `vaultProxy` variable value
function getVaultProxy() external view returns (address vaultProxy_);
}
// File: contracts/lib/pools/EnzymePoolController.sol
/**
* COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title EnzymePoolController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @dev This library handles deposits to and withdrawals from Enzyme's Rari ETH (technically WETH) pool.
*/
library EnzymePoolController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
/**
* @dev The WETH contract address.
*/
address constant private WETH_CONTRACT = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
/**
* @dev The WETH contract object.
*/
IEtherToken constant private _weth = IEtherToken(WETH_CONTRACT);
/**
* @dev Alpha Homora ibETH token contract address.
*/
address constant private IBETH_CONTRACT = 0x67B66C99D3Eb37Fa76Aa3Ed1ff33E8e39F0b9c7A;
/**
* @dev Returns the fund's balance of ETH (technically WETH) in the Enzyme pool.
*/
function getBalance(address comptroller) external returns (uint256) {
ComptrollerLib _comptroller = ComptrollerLib(comptroller);
(uint256 price, bool valid) = _comptroller.calcGrossShareValue(true);
require(valid, "Enzyme gross share value not valid.");
return IERC20(_comptroller.getVaultProxy()).balanceOf(address(this)).mul(price).div(1e18);
}
/**
* @dev Approves WETH to the Enzyme pool Comptroller without spending gas on every deposit.
* @param comptroller The Enzyme pool Comptroller contract address.
* @param amount Amount of the WETH to approve to the Enzyme pool Comptroller.
*/
function approve(address comptroller, uint256 amount) external {
uint256 allowance = _weth.allowance(address(this), comptroller);
if (allowance == amount) return;
if (amount > 0 && allowance > 0) _weth.approve(comptroller, 0);
_weth.approve(comptroller, amount);
}
/**
* @dev Deposits funds to the Enzyme pool. Assumes that you have already approved >= the amount to the Enzyme Comptroller contract.
* @param comptroller The Enzyme pool Comptroller contract address.
* @param amount The amount of ETH to be deposited.
*/
function deposit(address comptroller, uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
_weth.deposit.value(amount)();
address[] memory buyers = new address[](1);
buyers[0] = address(this);
uint256[] memory amounts = new uint256[](1);
amounts[0] = amount;
uint256[] memory minShares = new uint256[](1);
minShares[0] = 0;
ComptrollerLib(comptroller).buyShares(buyers, amounts, minShares);
}
/**
* @dev Withdraws funds from the Enzyme pool.
* @param comptroller The Enzyme pool Comptroller contract address.
* @param amount The amount of tokens to be withdrawn.
*/
function withdraw(address comptroller, uint256 amount) external {
require(amount > 0, "Amount must be greater than 0.");
ComptrollerLib _comptroller = ComptrollerLib(comptroller);
(uint256 price, bool valid) = _comptroller.calcGrossShareValue(true);
require(valid, "Enzyme gross share value not valid.");
uint256 shares = amount.mul(1e18).div(price);
if (shares.mul(price).div(1e18) < amount) shares++; // Round up if necessary (i.e., if the division above left a remainder)
address[] memory additionalAssets = new address[](0);
address[] memory assetsToSkip = new address[](0);
_comptroller.redeemSharesDetailed(shares, additionalAssets, assetsToSkip);
_weth.withdraw(_weth.balanceOf(address(this)));
}
/**
* @dev Withdraws all funds from the Enzyme pool.
* @param comptroller The Enzyme pool Comptroller contract address.
*/
function withdrawAll(address comptroller) external {
ComptrollerLib(comptroller).redeemShares();
_weth.withdraw(_weth.balanceOf(address(this)));
}
}
// File: @0x/contracts-utils/contracts/src/LibRichErrors.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibRichErrors {
// bytes4(keccak256("Error(string)"))
bytes4 internal constant STANDARD_ERROR_SELECTOR =
0x08c379a0;
// solhint-disable func-name-mixedcase
/// @dev ABI encode a standard, string revert error payload.
/// This is the same payload that would be included by a `revert(string)`
/// solidity statement. It has the function signature `Error(string)`.
/// @param message The error string.
/// @return The ABI encoded error.
function StandardError(
string memory message
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
STANDARD_ERROR_SELECTOR,
bytes(message)
);
}
// solhint-enable func-name-mixedcase
/// @dev Reverts an encoded rich revert reason `errorData`.
/// @param errorData ABI encoded error data.
function rrevert(bytes memory errorData)
internal
pure
{
assembly {
revert(add(errorData, 0x20), mload(errorData))
}
}
}
// File: @0x/contracts-utils/contracts/src/LibSafeMathRichErrors.sol
pragma solidity ^0.5.9;
library LibSafeMathRichErrors {
// bytes4(keccak256("Uint256BinOpError(uint8,uint256,uint256)"))
bytes4 internal constant UINT256_BINOP_ERROR_SELECTOR =
0xe946c1bb;
// bytes4(keccak256("Uint256DowncastError(uint8,uint256)"))
bytes4 internal constant UINT256_DOWNCAST_ERROR_SELECTOR =
0xc996af7b;
enum BinOpErrorCodes {
ADDITION_OVERFLOW,
MULTIPLICATION_OVERFLOW,
SUBTRACTION_UNDERFLOW,
DIVISION_BY_ZERO
}
enum DowncastErrorCodes {
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT32,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT64,
VALUE_TOO_LARGE_TO_DOWNCAST_TO_UINT96
}
// solhint-disable func-name-mixedcase
function Uint256BinOpError(
BinOpErrorCodes errorCode,
uint256 a,
uint256 b
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_BINOP_ERROR_SELECTOR,
errorCode,
a,
b
);
}
function Uint256DowncastError(
DowncastErrorCodes errorCode,
uint256 a
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
UINT256_DOWNCAST_ERROR_SELECTOR,
errorCode,
a
);
}
}
// File: @0x/contracts-utils/contracts/src/LibSafeMath.sol
pragma solidity ^0.5.9;
library LibSafeMath {
function safeMul(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (a == 0) {
return 0;
}
uint256 c = a * b;
if (c / a != b) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.MULTIPLICATION_OVERFLOW,
a,
b
));
}
return c;
}
function safeDiv(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b == 0) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.DIVISION_BY_ZERO,
a,
b
));
}
uint256 c = a / b;
return c;
}
function safeSub(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
if (b > a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.SUBTRACTION_UNDERFLOW,
a,
b
));
}
return a - b;
}
function safeAdd(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
uint256 c = a + b;
if (c < a) {
LibRichErrors.rrevert(LibSafeMathRichErrors.Uint256BinOpError(
LibSafeMathRichErrors.BinOpErrorCodes.ADDITION_OVERFLOW,
a,
b
));
}
return c;
}
function max256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b)
internal
pure
returns (uint256)
{
return a < b ? a : b;
}
}
// File: @0x/contracts-exchange-libs/contracts/src/LibMathRichErrors.sol
pragma solidity ^0.5.9;
library LibMathRichErrors {
// bytes4(keccak256("DivisionByZeroError()"))
bytes internal constant DIVISION_BY_ZERO_ERROR =
hex"a791837c";
// bytes4(keccak256("RoundingError(uint256,uint256,uint256)"))
bytes4 internal constant ROUNDING_ERROR_SELECTOR =
0x339f3de2;
// solhint-disable func-name-mixedcase
function DivisionByZeroError()
internal
pure
returns (bytes memory)
{
return DIVISION_BY_ZERO_ERROR;
}
function RoundingError(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bytes memory)
{
return abi.encodeWithSelector(
ROUNDING_ERROR_SELECTOR,
numerator,
denominator,
target
);
}
}
// File: @0x/contracts-exchange-libs/contracts/src/LibMath.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibMath {
using LibSafeMath for uint256;
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function safeGetPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorFloor(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// Reverts if rounding error is >= 0.1%
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function safeGetPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
if (isRoundingErrorCeil(
numerator,
denominator,
target
)) {
LibRichErrors.rrevert(LibMathRichErrors.RoundingError(
numerator,
denominator,
target
));
}
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded down.
function getPartialAmountFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
partialAmount = numerator.safeMul(target).safeDiv(denominator);
return partialAmount;
}
/// @dev Calculates partial value given a numerator and denominator rounded down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to calculate partial of.
/// @return Partial value of target rounded up.
function getPartialAmountCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (uint256 partialAmount)
{
// safeDiv computes `floor(a / b)`. We use the identity (a, b integer):
// ceil(a / b) = floor((a + b - 1) / b)
// To implement `ceil(a / b)` using safeDiv.
partialAmount = numerator.safeMul(target)
.safeAdd(denominator.safeSub(1))
.safeDiv(denominator);
return partialAmount;
}
/// @dev Checks if rounding error >= 0.1% when rounding down.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorFloor(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// The absolute rounding error is the difference between the rounded
// value and the ideal value. The relative rounding error is the
// absolute rounding error divided by the absolute value of the
// ideal value. This is undefined when the ideal value is zero.
//
// The ideal value is `numerator * target / denominator`.
// Let's call `numerator * target % denominator` the remainder.
// The absolute error is `remainder / denominator`.
//
// When the ideal value is zero, we require the absolute error to
// be zero. Fortunately, this is always the case. The ideal value is
// zero iff `numerator == 0` and/or `target == 0`. In this case the
// remainder and absolute error are also zero.
if (target == 0 || numerator == 0) {
return false;
}
// Otherwise, we want the relative rounding error to be strictly
// less than 0.1%.
// The relative error is `remainder / (numerator * target)`.
// We want the relative error less than 1 / 1000:
// remainder / (numerator * denominator) < 1 / 1000
// or equivalently:
// 1000 * remainder < numerator * target
// so we have a rounding error iff:
// 1000 * remainder >= numerator * target
uint256 remainder = mulmod(
target,
numerator,
denominator
);
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
/// @dev Checks if rounding error >= 0.1% when rounding up.
/// @param numerator Numerator.
/// @param denominator Denominator.
/// @param target Value to multiply with numerator/denominator.
/// @return Rounding error is present.
function isRoundingErrorCeil(
uint256 numerator,
uint256 denominator,
uint256 target
)
internal
pure
returns (bool isError)
{
if (denominator == 0) {
LibRichErrors.rrevert(LibMathRichErrors.DivisionByZeroError());
}
// See the comments in `isRoundingError`.
if (target == 0 || numerator == 0) {
// When either is zero, the ideal value and rounded value are zero
// and there is no rounding error. (Although the relative error
// is undefined.)
return false;
}
// Compute remainder as before
uint256 remainder = mulmod(
target,
numerator,
denominator
);
remainder = denominator.safeSub(remainder) % denominator;
isError = remainder.safeMul(1000) >= numerator.safeMul(target);
return isError;
}
}
// File: @0x/contracts-exchange-libs/contracts/src/LibFillResults.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibFillResults {
using LibSafeMath for uint256;
struct BatchMatchedFillResults {
FillResults[] left; // Fill results for left orders
FillResults[] right; // Fill results for right orders
uint256 profitInLeftMakerAsset; // Profit taken from left makers
uint256 profitInRightMakerAsset; // Profit taken from right makers
}
struct FillResults {
uint256 makerAssetFilledAmount; // Total amount of makerAsset(s) filled.
uint256 takerAssetFilledAmount; // Total amount of takerAsset(s) filled.
uint256 makerFeePaid; // Total amount of fees paid by maker(s) to feeRecipient(s).
uint256 takerFeePaid; // Total amount of fees paid by taker to feeRecipients(s).
uint256 protocolFeePaid; // Total amount of fees paid by taker to the staking contract.
}
struct MatchedFillResults {
FillResults left; // Amounts filled and fees paid of left order.
FillResults right; // Amounts filled and fees paid of right order.
uint256 profitInLeftMakerAsset; // Profit taken from the left maker
uint256 profitInRightMakerAsset; // Profit taken from the right maker
}
/// @dev Calculates amounts filled and fees paid by maker and taker.
/// @param order to be filled.
/// @param takerAssetFilledAmount Amount of takerAsset that will be filled.
/// @param protocolFeeMultiplier The current protocol fee of the exchange contract.
/// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue
/// to be pure rather than view.
/// @return fillResults Amounts filled and fees paid by maker and taker.
function calculateFillResults(
LibOrder.Order memory order,
uint256 takerAssetFilledAmount,
uint256 protocolFeeMultiplier,
uint256 gasPrice
)
internal
pure
returns (FillResults memory fillResults)
{
// Compute proportional transfer amounts
fillResults.takerAssetFilledAmount = takerAssetFilledAmount;
fillResults.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.makerAssetAmount
);
fillResults.makerFeePaid = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.makerFee
);
fillResults.takerFeePaid = LibMath.safeGetPartialAmountFloor(
takerAssetFilledAmount,
order.takerAssetAmount,
order.takerFee
);
// Compute the protocol fee that should be paid for a single fill.
fillResults.protocolFeePaid = gasPrice.safeMul(protocolFeeMultiplier);
return fillResults;
}
/// @dev Calculates fill amounts for the matched orders.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the leftOrder order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftOrderTakerAssetFilledAmount Amount of left order already filled.
/// @param rightOrderTakerAssetFilledAmount Amount of right order already filled.
/// @param protocolFeeMultiplier The current protocol fee of the exchange contract.
/// @param gasPrice The gasprice of the transaction. This is provided so that the function call can continue
/// to be pure rather than view.
/// @param shouldMaximallyFillOrders A value that indicates whether or not this calculation should use
/// the maximal fill order matching strategy.
/// @param matchedFillResults Amounts to fill and fees to pay by maker and taker of matched orders.
function calculateMatchedFillResults(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftOrderTakerAssetFilledAmount,
uint256 rightOrderTakerAssetFilledAmount,
uint256 protocolFeeMultiplier,
uint256 gasPrice,
bool shouldMaximallyFillOrders
)
internal
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Derive maker asset amounts for left & right orders, given store taker assert amounts
uint256 leftTakerAssetAmountRemaining = leftOrder.takerAssetAmount.safeSub(leftOrderTakerAssetFilledAmount);
uint256 leftMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor(
leftOrder.makerAssetAmount,
leftOrder.takerAssetAmount,
leftTakerAssetAmountRemaining
);
uint256 rightTakerAssetAmountRemaining = rightOrder.takerAssetAmount.safeSub(rightOrderTakerAssetFilledAmount);
uint256 rightMakerAssetAmountRemaining = LibMath.safeGetPartialAmountFloor(
rightOrder.makerAssetAmount,
rightOrder.takerAssetAmount,
rightTakerAssetAmountRemaining
);
// Maximally fill the orders and pay out profits to the matcher in one or both of the maker assets.
if (shouldMaximallyFillOrders) {
matchedFillResults = _calculateMatchedFillResultsWithMaximalFill(
leftOrder,
rightOrder,
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else {
matchedFillResults = _calculateMatchedFillResults(
leftOrder,
rightOrder,
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Compute fees for left order
matchedFillResults.left.makerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.left.makerAssetFilledAmount,
leftOrder.makerAssetAmount,
leftOrder.makerFee
);
matchedFillResults.left.takerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.left.takerAssetFilledAmount,
leftOrder.takerAssetAmount,
leftOrder.takerFee
);
// Compute fees for right order
matchedFillResults.right.makerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.right.makerAssetFilledAmount,
rightOrder.makerAssetAmount,
rightOrder.makerFee
);
matchedFillResults.right.takerFeePaid = LibMath.safeGetPartialAmountFloor(
matchedFillResults.right.takerAssetFilledAmount,
rightOrder.takerAssetAmount,
rightOrder.takerFee
);
// Compute the protocol fee that should be paid for a single fill. In this
// case this should be made the protocol fee for both the left and right orders.
uint256 protocolFee = gasPrice.safeMul(protocolFeeMultiplier);
matchedFillResults.left.protocolFeePaid = protocolFee;
matchedFillResults.right.protocolFeePaid = protocolFee;
// Return fill results
return matchedFillResults;
}
/// @dev Adds properties of both FillResults instances.
/// @param fillResults1 The first FillResults.
/// @param fillResults2 The second FillResults.
/// @return The sum of both fill results.
function addFillResults(
FillResults memory fillResults1,
FillResults memory fillResults2
)
internal
pure
returns (FillResults memory totalFillResults)
{
totalFillResults.makerAssetFilledAmount = fillResults1.makerAssetFilledAmount.safeAdd(fillResults2.makerAssetFilledAmount);
totalFillResults.takerAssetFilledAmount = fillResults1.takerAssetFilledAmount.safeAdd(fillResults2.takerAssetFilledAmount);
totalFillResults.makerFeePaid = fillResults1.makerFeePaid.safeAdd(fillResults2.makerFeePaid);
totalFillResults.takerFeePaid = fillResults1.takerFeePaid.safeAdd(fillResults2.takerFeePaid);
totalFillResults.protocolFeePaid = fillResults1.protocolFeePaid.safeAdd(fillResults2.protocolFeePaid);
return totalFillResults;
}
/// @dev Calculates part of the matched fill results for a given situation using the fill strategy that only
/// awards profit denominated in the left maker asset.
/// @param leftOrder The left order in the order matching situation.
/// @param rightOrder The right order in the order matching situation.
/// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled.
/// @return MatchFillResults struct that does not include fees paid.
function _calculateMatchedFillResults(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Calculate fill results for maker and taker assets: at least one order will be fully filled.
// The maximum amount the left maker can buy is `leftTakerAssetAmountRemaining`
// The maximum amount the right maker can sell is `rightMakerAssetAmountRemaining`
// We have two distinct cases for calculating the fill results:
// Case 1.
// If the left maker can buy more than the right maker can sell, then only the right order is fully filled.
// If the left maker can buy exactly what the right maker can sell, then both orders are fully filled.
// Case 2.
// If the left maker cannot buy more than the right maker can sell, then only the left order is fully filled.
// Case 3.
// If the left maker can buy exactly as much as the right maker can sell, then both orders are fully filled.
if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) {
// Case 1: Right order is fully filled
matchedFillResults = _calculateCompleteRightFill(
leftOrder,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else if (leftTakerAssetAmountRemaining < rightMakerAssetAmountRemaining) {
// Case 2: Left order is fully filled
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
matchedFillResults.right.makerAssetFilledAmount = leftTakerAssetAmountRemaining;
// Round up to ensure the maker's exchange rate does not exceed the price specified by the order.
// We favor the maker when the exchange rate must be rounded.
matchedFillResults.right.takerAssetFilledAmount = LibMath.safeGetPartialAmountCeil(
rightOrder.takerAssetAmount,
rightOrder.makerAssetAmount,
leftTakerAssetAmountRemaining // matchedFillResults.right.makerAssetFilledAmount
);
} else {
// leftTakerAssetAmountRemaining == rightMakerAssetAmountRemaining
// Case 3: Both orders are fully filled. Technically, this could be captured by the above cases, but
// this calculation will be more precise since it does not include rounding.
matchedFillResults = _calculateCompleteFillBoth(
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Calculate amount given to taker
matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub(
matchedFillResults.right.takerAssetFilledAmount
);
return matchedFillResults;
}
/// @dev Calculates part of the matched fill results for a given situation using the maximal fill order matching
/// strategy.
/// @param leftOrder The left order in the order matching situation.
/// @param rightOrder The right order in the order matching situation.
/// @param leftMakerAssetAmountRemaining The amount of the left order maker asset that can still be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left order taker asset that can still be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right order maker asset that can still be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right order taker asset that can still be filled.
/// @return MatchFillResults struct that does not include fees paid.
function _calculateMatchedFillResultsWithMaximalFill(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// If a maker asset is greater than the opposite taker asset, than there will be a spread denominated in that maker asset.
bool doesLeftMakerAssetProfitExist = leftMakerAssetAmountRemaining > rightTakerAssetAmountRemaining;
bool doesRightMakerAssetProfitExist = rightMakerAssetAmountRemaining > leftTakerAssetAmountRemaining;
// Calculate the maximum fill results for the maker and taker assets. At least one of the orders will be fully filled.
//
// The maximum that the left maker can possibly buy is the amount that the right order can sell.
// The maximum that the right maker can possibly buy is the amount that the left order can sell.
//
// If the left order is fully filled, profit will be paid out in the left maker asset. If the right order is fully filled,
// the profit will be out in the right maker asset.
//
// There are three cases to consider:
// Case 1.
// If the left maker can buy more than the right maker can sell, then only the right order is fully filled.
// Case 2.
// If the right maker can buy more than the left maker can sell, then only the right order is fully filled.
// Case 3.
// If the right maker can sell the max of what the left maker can buy and the left maker can sell the max of
// what the right maker can buy, then both orders are fully filled.
if (leftTakerAssetAmountRemaining > rightMakerAssetAmountRemaining) {
// Case 1: Right order is fully filled with the profit paid in the left makerAsset
matchedFillResults = _calculateCompleteRightFill(
leftOrder,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
} else if (rightTakerAssetAmountRemaining > leftMakerAssetAmountRemaining) {
// Case 2: Left order is fully filled with the profit paid in the right makerAsset.
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
// Round down to ensure the right maker's exchange rate does not exceed the price specified by the order.
// We favor the right maker when the exchange rate must be rounded and the profit is being paid in the
// right maker asset.
matchedFillResults.right.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
rightOrder.makerAssetAmount,
rightOrder.takerAssetAmount,
leftMakerAssetAmountRemaining
);
matchedFillResults.right.takerAssetFilledAmount = leftMakerAssetAmountRemaining;
} else {
// Case 3: The right and left orders are fully filled
matchedFillResults = _calculateCompleteFillBoth(
leftMakerAssetAmountRemaining,
leftTakerAssetAmountRemaining,
rightMakerAssetAmountRemaining,
rightTakerAssetAmountRemaining
);
}
// Calculate amount given to taker in the left order's maker asset if the left spread will be part of the profit.
if (doesLeftMakerAssetProfitExist) {
matchedFillResults.profitInLeftMakerAsset = matchedFillResults.left.makerAssetFilledAmount.safeSub(
matchedFillResults.right.takerAssetFilledAmount
);
}
// Calculate amount given to taker in the right order's maker asset if the right spread will be part of the profit.
if (doesRightMakerAssetProfitExist) {
matchedFillResults.profitInRightMakerAsset = matchedFillResults.right.makerAssetFilledAmount.safeSub(
matchedFillResults.left.takerAssetFilledAmount
);
}
return matchedFillResults;
}
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results
/// to the fillResults that are being collected on the order. Both orders will be fully filled in this
/// case.
/// @param leftMakerAssetAmountRemaining The amount of the left maker asset that is remaining to be filled.
/// @param leftTakerAssetAmountRemaining The amount of the left taker asset that is remaining to be filled.
/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.
/// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteFillBoth(
uint256 leftMakerAssetAmountRemaining,
uint256 leftTakerAssetAmountRemaining,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
// Calculate the fully filled results for both orders.
matchedFillResults.left.makerAssetFilledAmount = leftMakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = leftTakerAssetAmountRemaining;
matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;
matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;
return matchedFillResults;
}
/// @dev Calculates the fill results for the maker and taker in the order matching and writes the results
/// to the fillResults that are being collected on the order.
/// @param leftOrder The left order that is being maximally filled. All of the information about fill amounts
/// can be derived from this order and the right asset remaining fields.
/// @param rightMakerAssetAmountRemaining The amount of the right maker asset that is remaining to be filled.
/// @param rightTakerAssetAmountRemaining The amount of the right taker asset that is remaining to be filled.
/// @return MatchFillResults struct that does not include fees paid or spreads taken.
function _calculateCompleteRightFill(
LibOrder.Order memory leftOrder,
uint256 rightMakerAssetAmountRemaining,
uint256 rightTakerAssetAmountRemaining
)
private
pure
returns (MatchedFillResults memory matchedFillResults)
{
matchedFillResults.right.makerAssetFilledAmount = rightMakerAssetAmountRemaining;
matchedFillResults.right.takerAssetFilledAmount = rightTakerAssetAmountRemaining;
matchedFillResults.left.takerAssetFilledAmount = rightMakerAssetAmountRemaining;
// Round down to ensure the left maker's exchange rate does not exceed the price specified by the order.
// We favor the left maker when the exchange rate must be rounded and the profit is being paid in the
// left maker asset.
matchedFillResults.left.makerAssetFilledAmount = LibMath.safeGetPartialAmountFloor(
leftOrder.makerAssetAmount,
leftOrder.takerAssetAmount,
rightMakerAssetAmountRemaining
);
return matchedFillResults;
}
}
// File: @0x/contracts-exchange/contracts/src/interfaces/IExchangeCore.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IExchangeCore {
// Fill event is emitted whenever an order is filled.
event Fill(
address indexed makerAddress, // Address that created the order.
address indexed feeRecipientAddress, // Address that received fees.
bytes makerAssetData, // Encoded data specific to makerAsset.
bytes takerAssetData, // Encoded data specific to takerAsset.
bytes makerFeeAssetData, // Encoded data specific to makerFeeAsset.
bytes takerFeeAssetData, // Encoded data specific to takerFeeAsset.
bytes32 indexed orderHash, // EIP712 hash of order (see LibOrder.getTypedDataHash).
address takerAddress, // Address that filled the order.
address senderAddress, // Address that called the Exchange contract (msg.sender).
uint256 makerAssetFilledAmount, // Amount of makerAsset sold by maker and bought by taker.
uint256 takerAssetFilledAmount, // Amount of takerAsset sold by taker and bought by maker.
uint256 makerFeePaid, // Amount of makerFeeAssetData paid to feeRecipient by maker.
uint256 takerFeePaid, // Amount of takerFeeAssetData paid to feeRecipient by taker.
uint256 protocolFeePaid // Amount of eth or weth paid to the staking contract.
);
// Cancel event is emitted whenever an individual order is cancelled.
event Cancel(
address indexed makerAddress, // Address that created the order.
address indexed feeRecipientAddress, // Address that would have recieved fees if order was filled.
bytes makerAssetData, // Encoded data specific to makerAsset.
bytes takerAssetData, // Encoded data specific to takerAsset.
address senderAddress, // Address that called the Exchange contract (msg.sender).
bytes32 indexed orderHash // EIP712 hash of order (see LibOrder.getTypedDataHash).
);
// CancelUpTo event is emitted whenever `cancelOrdersUpTo` is executed succesfully.
event CancelUpTo(
address indexed makerAddress, // Orders cancelled must have been created by this address.
address indexed orderSenderAddress, // Orders cancelled must have a `senderAddress` equal to this address.
uint256 orderEpoch // Orders with specified makerAddress and senderAddress with a salt less than this value are considered cancelled.
);
/// @dev Cancels all orders created by makerAddress with a salt less than or equal to the targetOrderEpoch
/// and senderAddress equal to msg.sender (or null address if msg.sender == makerAddress).
/// @param targetOrderEpoch Orders created with a salt less or equal to this value will be cancelled.
function cancelOrdersUpTo(uint256 targetOrderEpoch)
external
payable;
/// @dev Fills the input order.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
/// @return Amounts filled and fees paid by maker and taker.
function fillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev After calling, the order can not be filled anymore.
/// @param order Order struct containing order specifications.
function cancelOrder(LibOrder.Order memory order)
public
payable;
/// @dev Gets information about an order: status, hash, and amount filled.
/// @param order Order to gather information on.
/// @return OrderInfo Information about the order and its state.
/// See LibOrder.OrderInfo for a complete description.
function getOrderInfo(LibOrder.Order memory order)
public
view
returns (LibOrder.OrderInfo memory orderInfo);
}
// File: @0x/contracts-exchange/contracts/src/interfaces/IProtocolFees.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IProtocolFees {
// Logs updates to the protocol fee multiplier.
event ProtocolFeeMultiplier(uint256 oldProtocolFeeMultiplier, uint256 updatedProtocolFeeMultiplier);
// Logs updates to the protocolFeeCollector address.
event ProtocolFeeCollectorAddress(address oldProtocolFeeCollector, address updatedProtocolFeeCollector);
/// @dev Allows the owner to update the protocol fee multiplier.
/// @param updatedProtocolFeeMultiplier The updated protocol fee multiplier.
function setProtocolFeeMultiplier(uint256 updatedProtocolFeeMultiplier)
external;
/// @dev Allows the owner to update the protocolFeeCollector address.
/// @param updatedProtocolFeeCollector The updated protocolFeeCollector contract address.
function setProtocolFeeCollectorAddress(address updatedProtocolFeeCollector)
external;
/// @dev Returns the protocolFeeMultiplier
function protocolFeeMultiplier()
external
view
returns (uint256);
/// @dev Returns the protocolFeeCollector address
function protocolFeeCollector()
external
view
returns (address);
}
// File: @0x/contracts-exchange/contracts/src/interfaces/IMatchOrders.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IMatchOrders {
/// @dev Match complementary orders that have a profitable spread.
/// Each order is filled at their respective price point, and
/// the matcher receives a profit denominated in the left maker asset.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrders(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults);
/// @dev Match complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrders Set of orders with the same maker / taker asset.
/// @param rightOrders Set of orders to match against `leftOrders`
/// @param leftSignatures Proof that left orders were created by the left makers.
/// @param rightSignatures Proof that right orders were created by the right makers.
/// @return batchMatchedFillResults Amounts filled and profit generated.
function batchMatchOrdersWithMaximalFill(
LibOrder.Order[] memory leftOrders,
LibOrder.Order[] memory rightOrders,
bytes[] memory leftSignatures,
bytes[] memory rightSignatures
)
public
payable
returns (LibFillResults.BatchMatchedFillResults memory batchMatchedFillResults);
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is filled at their respective price point. However, the calculations are
/// carried out as though the orders are both being filled at the right order's price point.
/// The profit made by the left order goes to the taker (who matched the two orders).
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled and fees paid by maker and taker of matched orders.
function matchOrders(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
returns (LibFillResults.MatchedFillResults memory matchedFillResults);
/// @dev Match two complementary orders that have a profitable spread.
/// Each order is maximally filled at their respective price point, and
/// the matcher receives a profit denominated in either the left maker asset,
/// right maker asset, or a combination of both.
/// @param leftOrder First order to match.
/// @param rightOrder Second order to match.
/// @param leftSignature Proof that order was created by the left maker.
/// @param rightSignature Proof that order was created by the right maker.
/// @return matchedFillResults Amounts filled by maker and taker of matched orders.
function matchOrdersWithMaximalFill(
LibOrder.Order memory leftOrder,
LibOrder.Order memory rightOrder,
bytes memory leftSignature,
bytes memory rightSignature
)
public
payable
returns (LibFillResults.MatchedFillResults memory matchedFillResults);
}
// File: @0x/contracts-exchange-libs/contracts/src/LibZeroExTransaction.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
library LibZeroExTransaction {
using LibZeroExTransaction for ZeroExTransaction;
// Hash for the EIP712 0x transaction schema
// keccak256(abi.encodePacked(
// "ZeroExTransaction(",
// "uint256 salt,",
// "uint256 expirationTimeSeconds,",
// "uint256 gasPrice,",
// "address signerAddress,",
// "bytes data",
// ")"
// ));
bytes32 constant internal _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH = 0xec69816980a3a3ca4554410e60253953e9ff375ba4536a98adfa15cc71541508;
struct ZeroExTransaction {
uint256 salt; // Arbitrary number to ensure uniqueness of transaction hash.
uint256 expirationTimeSeconds; // Timestamp in seconds at which transaction expires.
uint256 gasPrice; // gasPrice that transaction is required to be executed with.
address signerAddress; // Address of transaction signer.
bytes data; // AbiV2 encoded calldata.
}
/// @dev Calculates the EIP712 typed data hash of a transaction with a given domain separator.
/// @param transaction 0x transaction structure.
/// @return EIP712 typed data hash of the transaction.
function getTypedDataHash(ZeroExTransaction memory transaction, bytes32 eip712ExchangeDomainHash)
internal
pure
returns (bytes32 transactionHash)
{
// Hash the transaction with the domain separator of the Exchange contract.
transactionHash = LibEIP712.hashEIP712Message(
eip712ExchangeDomainHash,
transaction.getStructHash()
);
return transactionHash;
}
/// @dev Calculates EIP712 hash of the 0x transaction struct.
/// @param transaction 0x transaction structure.
/// @return EIP712 hash of the transaction struct.
function getStructHash(ZeroExTransaction memory transaction)
internal
pure
returns (bytes32 result)
{
bytes32 schemaHash = _EIP712_ZEROEX_TRANSACTION_SCHEMA_HASH;
bytes memory data = transaction.data;
uint256 salt = transaction.salt;
uint256 expirationTimeSeconds = transaction.expirationTimeSeconds;
uint256 gasPrice = transaction.gasPrice;
address signerAddress = transaction.signerAddress;
// Assembly for more efficiently computing:
// result = keccak256(abi.encodePacked(
// schemaHash,
// salt,
// expirationTimeSeconds,
// gasPrice,
// uint256(signerAddress),
// keccak256(data)
// ));
assembly {
// Compute hash of data
let dataHash := keccak256(add(data, 32), mload(data))
// Load free memory pointer
let memPtr := mload(64)
mstore(memPtr, schemaHash) // hash of schema
mstore(add(memPtr, 32), salt) // salt
mstore(add(memPtr, 64), expirationTimeSeconds) // expirationTimeSeconds
mstore(add(memPtr, 96), gasPrice) // gasPrice
mstore(add(memPtr, 128), and(signerAddress, 0xffffffffffffffffffffffffffffffffffffffff)) // signerAddress
mstore(add(memPtr, 160), dataHash) // hash of data
// Compute hash
result := keccak256(memPtr, 192)
}
return result;
}
}
// File: @0x/contracts-exchange/contracts/src/interfaces/ISignatureValidator.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract ISignatureValidator {
// Allowed signature types.
enum SignatureType {
Illegal, // 0x00, default value
Invalid, // 0x01
EIP712, // 0x02
EthSign, // 0x03
Wallet, // 0x04
Validator, // 0x05
PreSigned, // 0x06
EIP1271Wallet, // 0x07
NSignatureTypes // 0x08, number of signature types. Always leave at end.
}
event SignatureValidatorApproval(
address indexed signerAddress, // Address that approves or disapproves a contract to verify signatures.
address indexed validatorAddress, // Address of signature validator contract.
bool isApproved // Approval or disapproval of validator contract.
);
/// @dev Approves a hash on-chain.
/// After presigning a hash, the preSign signature type will become valid for that hash and signer.
/// @param hash Any 32-byte hash.
function preSign(bytes32 hash)
external
payable;
/// @dev Approves/unnapproves a Validator contract to verify signatures on signer's behalf.
/// @param validatorAddress Address of Validator contract.
/// @param approval Approval or disapproval of Validator contract.
function setSignatureValidatorApproval(
address validatorAddress,
bool approval
)
external
payable;
/// @dev Verifies that a hash has been signed by the given signer.
/// @param hash Any 32-byte hash.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid `true` if the signature is valid for the given hash and signer.
function isValidHashSignature(
bytes32 hash,
address signerAddress,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that a signature for an order is valid.
/// @param order The order.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid true if the signature is valid for the given order and signer.
function isValidOrderSignature(
LibOrder.Order memory order,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that a signature for a transaction is valid.
/// @param transaction The transaction.
/// @param signature Proof that the order has been signed by signer.
/// @return isValid true if the signature is valid for the given transaction and signer.
function isValidTransactionSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
view
returns (bool isValid);
/// @dev Verifies that an order, with provided order hash, has been signed
/// by the given signer.
/// @param order The order.
/// @param orderHash The hash of the order.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given order and signer.
function _isValidOrderWithHashSignature(
LibOrder.Order memory order,
bytes32 orderHash,
bytes memory signature
)
internal
view
returns (bool isValid);
/// @dev Verifies that a transaction, with provided order hash, has been signed
/// by the given signer.
/// @param transaction The transaction.
/// @param transactionHash The hash of the transaction.
/// @param signature Proof that the hash has been signed by signer.
/// @return isValid True if the signature is valid for the given transaction and signer.
function _isValidTransactionWithHashSignature(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes32 transactionHash,
bytes memory signature
)
internal
view
returns (bool isValid);
}
// File: @0x/contracts-exchange/contracts/src/interfaces/ITransactions.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract ITransactions {
// TransactionExecution event is emitted when a ZeroExTransaction is executed.
event TransactionExecution(bytes32 indexed transactionHash);
/// @dev Executes an Exchange method call in the context of signer.
/// @param transaction 0x transaction containing salt, signerAddress, and data.
/// @param signature Proof that transaction has been signed by signer.
/// @return ABI encoded return data of the underlying Exchange function call.
function executeTransaction(
LibZeroExTransaction.ZeroExTransaction memory transaction,
bytes memory signature
)
public
payable
returns (bytes memory);
/// @dev Executes a batch of Exchange method calls in the context of signer(s).
/// @param transactions Array of 0x transactions containing salt, signerAddress, and data.
/// @param signatures Array of proofs that transactions have been signed by signer(s).
/// @return Array containing ABI encoded return data for each of the underlying Exchange function calls.
function batchExecuteTransactions(
LibZeroExTransaction.ZeroExTransaction[] memory transactions,
bytes[] memory signatures
)
public
payable
returns (bytes[] memory);
/// @dev The current function will be called in the context of this address (either 0x transaction signer or `msg.sender`).
/// If calling a fill function, this address will represent the taker.
/// If calling a cancel function, this address will represent the maker.
/// @return Signer of 0x transaction if entry point is `executeTransaction`.
/// `msg.sender` if entry point is any other function.
function _getCurrentContextAddress()
internal
view
returns (address);
}
// File: @0x/contracts-exchange/contracts/src/interfaces/IAssetProxyDispatcher.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IAssetProxyDispatcher {
// Logs registration of new asset proxy
event AssetProxyRegistered(
bytes4 id, // Id of new registered AssetProxy.
address assetProxy // Address of new registered AssetProxy.
);
/// @dev Registers an asset proxy to its asset proxy id.
/// Once an asset proxy is registered, it cannot be unregistered.
/// @param assetProxy Address of new asset proxy to register.
function registerAssetProxy(address assetProxy)
external;
/// @dev Gets an asset proxy.
/// @param assetProxyId Id of the asset proxy.
/// @return The asset proxy registered to assetProxyId. Returns 0x0 if no proxy is registered.
function getAssetProxy(bytes4 assetProxyId)
external
view
returns (address);
}
// File: @0x/contracts-exchange/contracts/src/interfaces/IWrapperFunctions.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract IWrapperFunctions {
/// @dev Fills the input order. Reverts if exact takerAssetFillAmount not filled.
/// @param order Order struct containing order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signature Proof that order has been created by maker.
function fillOrKillOrder(
LibOrder.Order memory order,
uint256 takerAssetFillAmount,
bytes memory signature
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of fillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrKillOrder.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrKillOrders(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrder. If any fill reverts, the error is caught and ignored.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmounts Array of desired amounts of takerAsset to sell in orders.
/// @param signatures Proofs that orders have been created by makers.
/// @return Array of amounts filled and fees paid by makers and taker.
function batchFillOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256[] memory takerAssetFillAmounts,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults[] memory fillResults);
/// @dev Executes multiple calls of fillOrder until total amount of takerAsset is sold by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Desired amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of fillOrder until total amount of makerAsset is bought by taker.
/// If any fill reverts, the error is caught and ignored.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Desired amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersNoThrow(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Calls marketSellOrdersNoThrow then reverts if < takerAssetFillAmount has been sold.
/// NOTE: This function does not enforce that the takerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param takerAssetFillAmount Minimum amount of takerAsset to sell.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketSellOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 takerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Calls marketBuyOrdersNoThrow then reverts if < makerAssetFillAmount has been bought.
/// NOTE: This function does not enforce that the makerAsset is the same for each order.
/// @param orders Array of order specifications.
/// @param makerAssetFillAmount Minimum amount of makerAsset to buy.
/// @param signatures Proofs that orders have been signed by makers.
/// @return Amounts filled and fees paid by makers and taker.
function marketBuyOrdersFillOrKill(
LibOrder.Order[] memory orders,
uint256 makerAssetFillAmount,
bytes[] memory signatures
)
public
payable
returns (LibFillResults.FillResults memory fillResults);
/// @dev Executes multiple calls of cancelOrder.
/// @param orders Array of order specifications.
function batchCancelOrders(LibOrder.Order[] memory orders)
public
payable;
}
// File: @0x/contracts-exchange/contracts/src/interfaces/ITransferSimulator.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
contract ITransferSimulator {
/// @dev This function may be used to simulate any amount of transfers
/// As they would occur through the Exchange contract. Note that this function
/// will always revert, even if all transfers are successful. However, it may
/// be used with eth_call or with a try/catch pattern in order to simulate
/// the results of the transfers.
/// @param assetData Array of asset details, each encoded per the AssetProxy contract specification.
/// @param fromAddresses Array containing the `from` addresses that correspond with each transfer.
/// @param toAddresses Array containing the `to` addresses that correspond with each transfer.
/// @param amounts Array containing the amounts that correspond to each transfer.
/// @return This function does not return a value. However, it will always revert with
/// `Error("TRANSFERS_SUCCESSFUL")` if all of the transfers were successful.
function simulateDispatchTransferFromCalls(
bytes[] memory assetData,
address[] memory fromAddresses,
address[] memory toAddresses,
uint256[] memory amounts
)
public;
}
// File: @0x/contracts-exchange/contracts/src/interfaces/IExchange.sol
/*
Copyright 2019 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.5.9;
// solhint-disable no-empty-blocks
contract IExchange is
IProtocolFees,
IExchangeCore,
IMatchOrders,
ISignatureValidator,
ITransactions,
IAssetProxyDispatcher,
ITransferSimulator,
IWrapperFunctions
{}
// File: contracts/lib/exchanges/ZeroExExchangeController.sol
/**
* COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title ZeroExExchangeController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @dev This library handles exchanges via 0x.
*/
library ZeroExExchangeController {
using SafeMath for uint256;
using SafeERC20 for IERC20;
address constant private EXCHANGE_CONTRACT = 0x61935CbDd02287B511119DDb11Aeb42F1593b7Ef;
IExchange constant private _exchange = IExchange(EXCHANGE_CONTRACT);
address constant private ERC20_PROXY_CONTRACT = 0x95E6F48254609A6ee006F7D493c8e5fB97094ceF;
/**
* @dev Gets allowance of the specified token to 0x.
* @param erc20Contract The ERC20 contract address of the token.
*/
function allowance(address erc20Contract) internal view returns (uint256) {
return IERC20(erc20Contract).allowance(address(this), ERC20_PROXY_CONTRACT);
}
/**
* @dev Approves tokens to 0x without spending gas on every deposit.
* @param erc20Contract The ERC20 contract address of the token.
* @param amount Amount of the specified token to approve to dYdX.
* @return Boolean indicating success.
*/
function approve(address erc20Contract, uint256 amount) internal returns (bool) {
IERC20 token = IERC20(erc20Contract);
uint256 _allowance = token.allowance(address(this), ERC20_PROXY_CONTRACT);
if (_allowance == amount) return true;
if (amount > 0 && _allowance > 0) token.safeApprove(ERC20_PROXY_CONTRACT, 0);
token.safeApprove(ERC20_PROXY_CONTRACT, amount);
return true;
}
/**
* @dev Market sells to 0x exchange orders up to a certain amount of input.
* @param orders The limit orders to be filled in ascending order of price.
* @param signatures The signatures for the orders.
* @param takerAssetFillAmount The amount of the taker asset to sell (excluding taker fees).
* @param protocolFee The protocol fee in ETH to pay to 0x.
* @return Array containing the taker asset filled amount (sold) and maker asset filled amount (bought).
*/
function marketSellOrdersFillOrKill(LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 takerAssetFillAmount, uint256 protocolFee) internal returns (uint256[2] memory) {
require(orders.length > 0, "At least one order and matching signature is required.");
require(orders.length == signatures.length, "Mismatch between number of orders and signatures.");
require(takerAssetFillAmount > 0, "Taker asset fill amount must be greater than 0.");
LibFillResults.FillResults memory fillResults = _exchange.marketSellOrdersFillOrKill.value(protocolFee)(orders, takerAssetFillAmount, signatures);
return [fillResults.takerAssetFilledAmount, fillResults.makerAssetFilledAmount];
}
/**
* @dev Market buys from 0x exchange orders up to a certain amount of output.
* @param orders The limit orders to be filled in ascending order of price.
* @param signatures The signatures for the orders.
* @param makerAssetFillAmount The amount of the maker asset to buy.
* @param protocolFee The protocol fee in ETH to pay to 0x.
* @return Array containing the taker asset filled amount (sold) and maker asset filled amount (bought).
*/
function marketBuyOrdersFillOrKill(LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 makerAssetFillAmount, uint256 protocolFee) internal returns (uint256[2] memory) {
require(orders.length > 0, "At least one order and matching signature is required.");
require(orders.length == signatures.length, "Mismatch between number of orders and signatures.");
require(makerAssetFillAmount > 0, "Maker asset fill amount must be greater than 0.");
LibFillResults.FillResults memory fillResults = _exchange.marketBuyOrdersFillOrKill.value(protocolFee)(orders, makerAssetFillAmount, signatures);
return [fillResults.takerAssetFilledAmount, fillResults.makerAssetFilledAmount];
}
}
// File: contracts/RariFundController.sol
/**
* COPYRIGHT © 2020 RARI CAPITAL, INC. ALL RIGHTS RESERVED.
* Anyone is free to integrate the public (i.e., non-administrative) application programming interfaces (APIs) of the official Ethereum smart contract instances deployed by Rari Capital, Inc. in any application (commercial or noncommercial and under any license), provided that the application does not abuse the APIs or act against the interests of Rari Capital, Inc.
* Anyone is free to study, review, and analyze the source code contained in this package.
* Reuse (including deployment of smart contracts other than private testing on a private network), modification, redistribution, or sublicensing of any source code contained in this package is not permitted without the explicit permission of David Lucid of Rari Capital, Inc.
* No one is permitted to use the software for any purpose other than those allowed by this license.
* This license is liable to change at any time at the sole discretion of David Lucid of Rari Capital, Inc.
*/
pragma solidity 0.5.17;
/**
* @title RariFundController
* @author David Lucid <david@rari.capital> (https://github.com/davidlucid)
* @author Richter Brzeski <richter@rari.capital> (https://github.com/richtermb)
* @dev This contract handles deposits to and withdrawals from the liquidity pools that power the Rari Ethereum Pool as well as currency exchanges via 0x.
*/
contract RariFundController is Ownable {
using SafeMath for uint256;
using SignedSafeMath for int256;
using SafeERC20 for IERC20;
/**
* @dev Boolean to be checked on `upgradeFundController`.
*/
bool public constant IS_RARI_FUND_CONTROLLER = true;
/**
* @dev Boolean that, if true, disables the primary functionality of this RariFundController.
*/
bool private _fundDisabled;
/**
* @dev Address of the RariFundManager.
*/
address payable private _rariFundManagerContract;
/**
* @dev Address of the rebalancer.
*/
address private _rariFundRebalancerAddress;
/**
* @dev Enum for liqudity pools supported by Rari.
*/
enum LiquidityPool { dYdX, Compound, KeeperDAO, Aave, Alpha, Enzyme }
/**
* @dev Maps arrays of supported pools to currency codes.
*/
uint8[] private _supportedPools;
/**
* @dev COMP token address.
*/
address constant private COMP_TOKEN = 0xc00e94Cb662C3520282E6f5717214004A7f26888;
/**
* @dev ROOK token address.
*/
address constant private ROOK_TOKEN = 0xfA5047c9c78B8877af97BDcb85Db743fD7313d4a;
/**
* @dev WETH token contract.
*/
IEtherToken constant private _weth = IEtherToken(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
/**
* @dev Caches the balances for each pool, with the sum cached at the end
*/
uint256[] private _cachedBalances;
/**
* @dev Constructor that sets supported ERC20 token contract addresses and supported pools for each supported token.
*/
constructor () public {
Ownable.initialize(msg.sender);
// Add supported pools
addPool(0); // dYdX
addPool(1); // Compound
addPool(2); // KeeperDAO
addPool(3); // Aave
addPool(4); // Alpha
addPool(5); // Enzyme
}
/**
* @dev Adds a supported pool for a token.
* @param pool Pool ID to be supported.
*/
function addPool(uint8 pool) internal {
_supportedPools.push(pool);
}
/**
* @dev Payable fallback function called by 0x exchange to refund unspent protocol fee.
*/
function () external payable { }
/**
* @dev Emitted when the RariFundManager of the RariFundController is set.
*/
event FundManagerSet(address newAddress);
/**
* @dev Sets or upgrades the RariFundManager of the RariFundController.
* @param newContract The address of the new RariFundManager contract.
*/
function setFundManager(address payable newContract) external onlyOwner {
_rariFundManagerContract = newContract;
emit FundManagerSet(newContract);
}
/**
* @dev Throws if called by any account other than the RariFundManager.
*/
modifier onlyManager() {
require(_rariFundManagerContract == msg.sender, "Caller is not the fund manager.");
_;
}
/**
* @dev Emitted when the rebalancer of the RariFundController is set.
*/
event FundRebalancerSet(address newAddress);
/**
* @dev Sets or upgrades the rebalancer of the RariFundController.
* @param newAddress The Ethereum address of the new rebalancer server.
*/
function setFundRebalancer(address newAddress) external onlyOwner {
_rariFundRebalancerAddress = newAddress;
emit FundRebalancerSet(newAddress);
}
/**
* @dev Throws if called by any account other than the rebalancer.
*/
modifier onlyRebalancer() {
require(_rariFundRebalancerAddress == msg.sender, "Caller is not the rebalancer.");
_;
}
/**
* @dev Emitted when the primary functionality of this RariFundController contract has been disabled.
*/
event FundDisabled();
/**
* @dev Emitted when the primary functionality of this RariFundController contract has been enabled.
*/
event FundEnabled();
/**
* @dev Disables primary functionality of this RariFundController so contract(s) can be upgraded.
*/
function disableFund() external onlyOwner {
require(!_fundDisabled, "Fund already disabled.");
_fundDisabled = true;
emit FundDisabled();
}
/**
* @dev Enables primary functionality of this RariFundController once contract(s) are upgraded.
*/
function enableFund() external onlyOwner {
require(_fundDisabled, "Fund already enabled.");
_fundDisabled = false;
emit FundEnabled();
}
/**
* @dev Throws if fund is disabled.
*/
modifier fundEnabled() {
require(!_fundDisabled, "This fund controller contract is disabled. This may be due to an upgrade.");
_;
}
/**
* @dev Sets or upgrades RariFundController by forwarding immediate balance of ETH from the old to the new.
* @param newContract The address of the new RariFundController contract.
*/
function _upgradeFundController(address payable newContract) public onlyOwner {
// Verify fund is disabled + verify new fund controller contract
require(_fundDisabled, "This fund controller contract must be disabled before it can be upgraded.");
require(RariFundController(newContract).IS_RARI_FUND_CONTROLLER(), "New contract does not have IS_RARI_FUND_CONTROLLER set to true.");
// Transfer all ETH to new fund controller
uint256 balance = address(this).balance;
if (balance > 0) {
(bool success, ) = newContract.call.value(balance)("");
require(success, "Failed to transfer ETH.");
}
}
/**
* @dev Sets or upgrades RariFundController by withdrawing all ETH from all pools and forwarding them from the old to the new.
* @param newContract The address of the new RariFundController contract.
*/
function upgradeFundController(address payable newContract) external onlyOwner {
// Withdraw all from Enzyme first because they output other LP tokens
if (hasETHInPool(5))
_withdrawAllFromPool(5);
// Then withdraw all from all other pools
for (uint256 i = 0; i < _supportedPools.length; i++)
if (hasETHInPool(_supportedPools[i]))
_withdrawAllFromPool(_supportedPools[i]);
// Transfer all ETH to new fund controller
_upgradeFundController(newContract);
}
/**
* @dev Returns the fund controller's balance of the specified currency in the specified pool.
* @dev Ideally, we can add the view modifier, but Compound's `getUnderlyingBalance` function (called by `CompoundPoolController.getBalance`) potentially modifies the state.
* @param pool The index of the pool.
*/
function _getPoolBalance(uint8 pool) public returns (uint256) {
if (pool == 0) return DydxPoolController.getBalance();
else if (pool == 1) return CompoundPoolController.getBalance();
else if (pool == 2) return KeeperDaoPoolController.getBalance();
else if (pool == 3) return AavePoolController.getBalance();
else if (pool == 4) return AlphaPoolController.getBalance();
else if (pool == 5) return EnzymePoolController.getBalance(_enzymeComptroller);
else revert("Invalid pool index.");
}
/**
* @dev Returns the fund controller's balance of the specified currency in the specified pool.
* @dev Ideally, we can add the view modifier, but Compound's `getUnderlyingBalance` function (called by `CompoundPoolController.getBalance`) potentially modifies the state.
* @param pool The index of the pool.
*/
function getPoolBalance(uint8 pool) public returns (uint256) {
if (!_poolsWithFunds[pool]) return 0;
return _getPoolBalance(pool);
}
/**
* @notice Returns the fund controller's balance of each pool of the specified currency.
* @dev Ideally, we can add the view modifier, but Compound's `getUnderlyingBalance` function (called by `getPoolBalance`) potentially modifies the state.
* @return An array of pool indexes and an array of corresponding balances.
*/
function getEntireBalance() public returns (uint256) {
uint256 sum = address(this).balance; // start with immediate eth balance
for (uint256 i = 0; i < _supportedPools.length; i++) {
sum = getPoolBalance(_supportedPools[i]).add(sum);
}
return sum;
}
/**
* @dev Approves WETH to pool without spending gas on every deposit.
* @param pool The index of the pool.
* @param amount The amount of WETH to be approved.
*/
function approveWethToPool(uint8 pool, uint256 amount) external fundEnabled onlyRebalancer {
if (pool == 0) return DydxPoolController.approve(amount);
else if (pool == 5) return EnzymePoolController.approve(_enzymeComptroller, amount);
else revert("Invalid pool index.");
}
/**
* @dev Approves kEther to the specified pool without spending gas on every deposit.
* @param amount The amount of kEther to be approved.
*/
function approvekEtherToKeeperDaoPool(uint256 amount) external fundEnabled onlyRebalancer {
KeeperDaoPoolController.approve(amount);
}
/**
* @dev Mapping of bools indicating the presence of funds to pools.
*/
mapping(uint8 => bool) _poolsWithFunds;
/**
* @dev Return a boolean indicating if the fund controller has funds in `currencyCode` in `pool`.
* @param pool The index of the pool to check.
*/
function hasETHInPool(uint8 pool) public view returns (bool) {
return _poolsWithFunds[pool];
}
/**
* @dev Referral code for Aave deposits.
*/
uint16 _aaveReferralCode;
/**
* @dev Sets the referral code for Aave deposits.
* @param referralCode The referral code.
*/
function setAaveReferralCode(uint16 referralCode) external onlyOwner {
_aaveReferralCode = referralCode;
}
/**
* @dev The Enzyme pool Comptroller contract address.
*/
address _enzymeComptroller;
/**
* @dev Sets the Enzyme pool Comptroller contract address.
* @param comptroller The Enzyme pool Comptroller contract address.
*/
function setEnzymeComptroller(address comptroller) external onlyOwner {
_enzymeComptroller = comptroller;
}
/**
* @dev Enum for pool allocation action types supported by Rari.
*/
enum PoolAllocationAction { Deposit, Withdraw, WithdrawAll }
/**
* @dev Emitted when a deposit or withdrawal is made.
* Note that `amount` is not set for `WithdrawAll` actions.
*/
event PoolAllocation(PoolAllocationAction indexed action, LiquidityPool indexed pool, uint256 amount);
/**
* @dev Deposits funds to the specified pool.
* @param pool The index of the pool.
*/
function depositToPool(uint8 pool, uint256 amount) external fundEnabled onlyRebalancer {
require(amount > 0, "Amount must be greater than 0.");
if (pool == 0) DydxPoolController.deposit(amount);
else if (pool == 1) CompoundPoolController.deposit(amount);
else if (pool == 2) KeeperDaoPoolController.deposit(amount);
else if (pool == 3) AavePoolController.deposit(amount, _aaveReferralCode);
else if (pool == 4) AlphaPoolController.deposit(amount);
else if (pool == 5) EnzymePoolController.deposit(_enzymeComptroller, amount);
else revert("Invalid pool index.");
_poolsWithFunds[pool] = true;
emit PoolAllocation(PoolAllocationAction.Deposit, LiquidityPool(pool), amount);
}
/**
* @dev Internal function to withdraw funds from the specified pool.
* @param pool The index of the pool.
* @param amount The amount of tokens to be withdrawn.
*/
function _withdrawFromPool(uint8 pool, uint256 amount) internal {
if (pool == 0) DydxPoolController.withdraw(amount);
else if (pool == 1) CompoundPoolController.withdraw(amount);
else if (pool == 2) KeeperDaoPoolController.withdraw(amount);
else if (pool == 3) AavePoolController.withdraw(amount);
else if (pool == 4) AlphaPoolController.withdraw(amount);
else if (pool == 5) EnzymePoolController.withdraw(_enzymeComptroller, amount);
else revert("Invalid pool index.");
emit PoolAllocation(PoolAllocationAction.Withdraw, LiquidityPool(pool), amount);
}
/**
* @dev Withdraws funds from the specified pool.
* @param pool The index of the pool.
* @param amount The amount of tokens to be withdrawn.
*/
function withdrawFromPool(uint8 pool, uint256 amount) external fundEnabled onlyRebalancer {
require(amount > 0, "Amount must be greater than 0.");
_withdrawFromPool(pool, amount);
_poolsWithFunds[pool] = _getPoolBalance(pool) > 0;
}
/**
* @dev Withdraws funds from the specified pool (caching the `initialBalance` parameter).
* @param pool The index of the pool.
* @param amount The amount of tokens to be withdrawn.
* @param initialBalance The fund's balance of the specified currency in the specified pool before the withdrawal.
*/
function withdrawFromPoolKnowingBalance(uint8 pool, uint256 amount, uint256 initialBalance) public fundEnabled onlyManager {
_withdrawFromPool(pool, amount);
if (amount == initialBalance) _poolsWithFunds[pool] = false;
}
/**
* @dev Internal function that withdraws all funds from the specified pool.
* @param pool The index of the pool.
*/
function _withdrawAllFromPool(uint8 pool) internal {
if (pool == 0) DydxPoolController.withdrawAll();
else if (pool == 1) require(CompoundPoolController.withdrawAll(), "No Compound balance to withdraw from.");
else if (pool == 2) require(KeeperDaoPoolController.withdrawAll(), "No KeeperDAO balance to withdraw from.");
else if (pool == 3) AavePoolController.withdrawAll();
else if (pool == 4) require(AlphaPoolController.withdrawAll(), "No Alpha Homora balance to withdraw from.");
else if (pool == 5) EnzymePoolController.withdrawAll(_enzymeComptroller);
else revert("Invalid pool index.");
_poolsWithFunds[pool] = false;
emit PoolAllocation(PoolAllocationAction.WithdrawAll, LiquidityPool(pool), 0);
}
/**
* @dev Withdraws all funds from the specified pool.
* @param pool The index of the pool.
* @return Boolean indicating success.
*/
function withdrawAllFromPool(uint8 pool) external fundEnabled onlyRebalancer {
_withdrawAllFromPool(pool);
}
/**
* @dev Withdraws all funds from the specified pool (without requiring the fund to be enabled).
* @param pool The index of the pool.
* @return Boolean indicating success.
*/
function withdrawAllFromPoolOnUpgrade(uint8 pool) external onlyOwner {
_withdrawAllFromPool(pool);
}
/**
* @dev Withdraws ETH and sends amount to the manager.
* @param amount Amount of ETH to withdraw.
*/
function withdrawToManager(uint256 amount) external onlyManager {
// Input validation
require(amount > 0, "Withdrawal amount must be greater than 0.");
// Check contract balance and withdraw from pools if necessary
uint256 contractBalance = address(this).balance; // get ETH balance
if (contractBalance < amount) {
uint256 poolBalance = getPoolBalance(5);
if (poolBalance > 0) {
uint256 amountLeft = amount.sub(contractBalance);
uint256 poolAmount = amountLeft < poolBalance ? amountLeft : poolBalance;
withdrawFromPoolKnowingBalance(5, poolAmount, poolBalance);
contractBalance = address(this).balance;
}
}
for (uint256 i = 0; i < _supportedPools.length; i++) {
if (contractBalance >= amount) break;
uint8 pool = _supportedPools[i];
if (pool == 5) continue;
uint256 poolBalance = getPoolBalance(pool);
if (poolBalance <= 0) continue;
uint256 amountLeft = amount.sub(contractBalance);
uint256 poolAmount = amountLeft < poolBalance ? amountLeft : poolBalance;
withdrawFromPoolKnowingBalance(pool, poolAmount, poolBalance);
contractBalance = contractBalance.add(poolAmount);
}
require(address(this).balance >= amount, "Too little ETH to transfer.");
(bool success, ) = _rariFundManagerContract.call.value(amount)("");
require(success, "Failed to transfer ETH to RariFundManager.");
}
/**
* @dev Emitted when COMP is exchanged to ETH via 0x.
*/
event CurrencyTrade(address inputErc20Contract, uint256 inputAmount, uint256 outputAmount);
/**
* @dev Approves tokens (COMP or ROOK) to 0x without spending gas on every deposit.
* @param erc20Contract The ERC20 contract address of the token to be approved (must be COMP or ROOK).
* @param amount The amount of tokens to be approved.
*/
function approveTo0x(address erc20Contract, uint256 amount) external fundEnabled onlyRebalancer {
require(erc20Contract == COMP_TOKEN || erc20Contract == ROOK_TOKEN, "Supplied token address is not COMP or ROOK.");
ZeroExExchangeController.approve(erc20Contract, amount);
}
/**
* @dev Market sell (COMP or ROOK) to 0x exchange orders (reverting if `takerAssetFillAmount` is not filled).
* We should be able to make this function external and use calldata for all parameters, but Solidity does not support calldata structs (https://github.com/ethereum/solidity/issues/5479).
* @param inputErc20Contract The input ERC20 token contract address (must be COMP or ROOK).
* @param orders The limit orders to be filled in ascending order of price.
* @param signatures The signatures for the orders.
* @param takerAssetFillAmount The amount of the taker asset to sell (excluding taker fees).
*/
function marketSell0xOrdersFillOrKill(address inputErc20Contract, LibOrder.Order[] memory orders, bytes[] memory signatures, uint256 takerAssetFillAmount) public payable fundEnabled onlyRebalancer {
// Exchange COMP/ROOK to ETH
uint256 ethBalanceBefore = address(this).balance;
uint256[2] memory filledAmounts = ZeroExExchangeController.marketSellOrdersFillOrKill(orders, signatures, takerAssetFillAmount, msg.value);
uint256 ethBalanceAfter = address(this).balance;
emit CurrencyTrade(inputErc20Contract, filledAmounts[0], filledAmounts[1]);
// Unwrap outputted WETH
uint256 wethBalance = _weth.balanceOf(address(this));
require(wethBalance > 0, "No WETH outputted.");
_weth.withdraw(wethBalance);
// Refund unspent ETH protocol fee
uint256 refund = ethBalanceAfter.sub(ethBalanceBefore.sub(msg.value));
if (refund > 0) {
(bool success, ) = msg.sender.call.value(refund)("");
require(success, "Failed to refund unspent ETH protocol fee.");
}
}
/**
* Unwraps all WETH currently owned by the fund controller.
*/
function unwrapAllWeth() external fundEnabled onlyRebalancer {
uint256 wethBalance = _weth.balanceOf(address(this));
require(wethBalance > 0, "No WETH to withdraw.");
_weth.withdraw(wethBalance);
}
/**
* @notice Returns the fund controller's contract ETH balance and balance of each pool (checking `_poolsWithFunds` first to save gas).
* @dev Ideally, we can add the `view` modifier, but Compound's `getUnderlyingBalance` function (called by `getPoolBalance`) potentially modifies the state.
* @return The fund controller ETH contract balance, an array of pool indexes, and an array of corresponding balances for each pool.
*/
function getRawFundBalances() external returns (uint256, uint8[] memory, uint256[] memory) {
uint8[] memory pools = new uint8[](_supportedPools.length);
uint256[] memory poolBalances = new uint256[](_supportedPools.length);
for (uint256 i = 0; i < _supportedPools.length; i++) {
pools[i] = _supportedPools[i];
poolBalances[i] = getPoolBalance(_supportedPools[i]);
}
return (address(this).balance, pools, poolBalances);
}
}
|
Alpha Homora ibETH token contract address./ Alpha Homora ibETH token contract object./ Returns the fund's balance of the specified currency in the ibETH pool./
|
function getBalance() external view returns (uint256) {
return _ibEth.balanceOf(address(this)).mul(_ibEth.totalETH()).div(_ibEth.totalSupply());
}
| 12,084,379
|
./partial_match/3/0x0A7105fFdC6E07129822664659246eFCb591DC85/sources/ethmax.sol
|
Invest Function. If no referrer, referrer = 0x0000000000000000000000000000000000000000
|
function invest(address referrer) public payable {
require(msg.value >= INVEST_MIN_AMOUNT);
PR_Address.transfer(msg.value.mul(PL_SHARE).div(PERCENTS_DIVIDER));
emit FeePayed(msg.sender, msg.value.mul(PL_SHARE).div(PERCENTS_DIVIDER));
User storage user = users[msg.sender];
if (user.referrer == address(0) && users[referrer].deposits.length > 0 && referrer != msg.sender) {
user.referrer = referrer;
}
if (user.referrer != address(0)) {
address upline = user.referrer;
for (uint256 i = 0; i < 3; i++) {
if (upline != address(0)) {
uint256 amount = msg.value.mul(REFERRAL_PERCENTS[i]).div(PERCENTS_DIVIDER);
users[upline].bonus = users[upline].bonus.add(amount);
emit RefBonus(upline, msg.sender, i, amount);
upline = users[upline].referrer;
} else break;
}
}
if (user.deposits.length == 0) {
user.checkpoint = block.timestamp;
totalUsers = totalUsers.add(1);
emit Newbie(msg.sender);
}
user.deposits.push(Deposit(msg.value, 0, block.timestamp));
totalInvested = totalInvested.add(msg.value);
totalDeposits = totalDeposits.add(1);
emit NewDeposit(msg.sender, msg.value);
msg.sender.transfer(GAS_FEE_SUBSIDE);
}
| 5,084,518
|
/**
*Submitted for verification at Etherscan.io on 2022-03-20
*/
// SPDX-License-Identifier: MIT
pragma experimental ABIEncoderV2;
pragma solidity 0.6.11;
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
interface AggregatorV3Interface {
function decimals() external view returns (uint8);
function description() external view returns (string memory);
function version() external view returns (uint256);
// getRoundData and latestRoundData should both raise "No data present"
// if they do not have data to report, instead of returning unset values
// which could be misinterpreted as actual reported values.
function getRoundData(uint80 _roundId)
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
function latestRoundData()
external
view
returns (
uint80 roundId,
int256 answer,
uint256 startedAt,
uint256 updatedAt,
uint80 answeredInRound
);
//not actually in AggregatorV3Interface but implemented by said contracts
function latestTimestamp() external view returns (uint256);
}
contract BaseMath {
uint constant public DECIMAL_PRECISION = 1e18;
}
contract CheckContract {
/**
* Check that the account is an already deployed non-destroyed contract.
* See: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol#L12
*/
function checkContract(address _account) internal view {
require(_account != address(0), "Account cannot be zero address");
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(_account) }
require(size > 0, "Account code size cannot be zero");
}
}
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);
function increaseAllowance(address spender, uint256 addedValue) external returns (bool);
function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
interface IERC2612 {
/**
* @dev Sets `amount` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 amount,
uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current ERC2612 nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases `owner`'s nonce by one. This
* prevents a signature from being used multiple times.
*
* `owner` can limit the time a Permit is valid for by setting `deadline` to
* a value in the near future. The deadline argument can be set to uint(-1) to
* create Permits that effectively never expire.
*/
function nonces(address owner) external view returns (uint256);
function version() external view returns (string memory);
function permitTypeHash() external view returns (bytes32);
function domainSeparator() external view returns (bytes32);
}
interface ITellor {
/**
* @dev Helps initialize a dispute by assigning it a disputeId
* when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the
* invalidated value information to POS voting
* @param _requestId being disputed
* @param _timestamp being disputed
* @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value
* requires 5 miners to submit a value.
*/
function beginDispute(
uint256 _requestId,
uint256 _timestamp,
uint256 _minerIndex
) external;
/**
* @dev Allows token holders to vote
* @param _disputeId is the dispute id
* @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute)
*/
function vote(uint256 _disputeId, bool _supportsDispute) external;
/**
* @dev tallies the votes.
* @param _disputeId is the dispute id
*/
function tallyVotes(uint256 _disputeId) external;
/**
* @dev Allows for a fork to be proposed
* @param _propNewTellorAddress address for new proposed Tellor
*/
function proposeFork(address _propNewTellorAddress) external;
/**
* @dev Add tip to Request value from oracle
* @param _requestId being requested to be mined
* @param _tip amount the requester is willing to pay to be get on queue. Miners
* mine the onDeckQueryHash, or the api with the highest payout pool
*/
function addTip(uint256 _requestId, uint256 _tip) external;
/**
* @dev This is called by the miner when they submit the PoW solution (proof of work and value)
* @param _nonce uint submitted by miner
* @param _requestId the apiId being mined
* @param _value of api query
*
*/
function submitMiningSolution(
string calldata _nonce,
uint256 _requestId,
uint256 _value
) external;
/**
* @dev This is called by the miner when they submit the PoW solution (proof of work and value)
* @param _nonce uint submitted by miner
* @param _requestId is the array of the 5 PSR's being mined
* @param _value is an array of 5 values
*/
function submitMiningSolution(
string calldata _nonce,
uint256[5] calldata _requestId,
uint256[5] calldata _value
) external;
/**
* @dev Allows the current owner to propose transfer control of the contract to a
* newOwner and the ownership is pending until the new owner calls the claimOwnership
* function
* @param _pendingOwner The address to transfer ownership to.
*/
function proposeOwnership(address payable _pendingOwner) external;
/**
* @dev Allows the new owner to claim control of the contract
*/
function claimOwnership() external;
/**
* @dev This function allows miners to deposit their stake.
*/
function depositStake() external;
/**
* @dev This function allows stakers to request to withdraw their stake (no longer stake)
* once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they
* can withdraw the stake
*/
function requestStakingWithdraw() external;
/**
* @dev This function allows users to withdraw their stake after a 7 day waiting period from request
*/
function withdrawStake() external;
/**
* @dev This function approves a _spender an _amount of tokens to use
* @param _spender address
* @param _amount amount the spender is being approved for
* @return true if spender appproved successfully
*/
function approve(address _spender, uint256 _amount) external returns (bool);
/**
* @dev Allows for a transfer of tokens to _to
* @param _to The address to send tokens to
* @param _amount The amount of tokens to send
* @return true if transfer is successful
*/
function transfer(address _to, uint256 _amount) external returns (bool);
/**
* @dev Sends _amount tokens to _to from _from on the condition it
* is approved by _from
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _amount The amount of tokens to be transferred
* @return True if the transfer was successful
*/
function transferFrom(
address _from,
address _to,
uint256 _amount
) external returns (bool);
/**
* @dev Allows users to access the token's name
*/
function name() external pure returns (string memory);
/**
* @dev Allows users to access the token's symbol
*/
function symbol() external pure returns (string memory);
/**
* @dev Allows users to access the number of decimals
*/
function decimals() external pure returns (uint8);
/**
* @dev Getter for the current variables that include the 5 requests Id's
* @return _challenge _requestIds _difficultky _tip the challenge, 5 requestsId, difficulty and tip
*/
function getNewCurrentVariables()
external
view
returns (
bytes32 _challenge,
uint256[5] memory _requestIds,
uint256 _difficutly,
uint256 _tip
);
/**
* @dev Getter for the top tipped 5 requests Id's
* @return _requestIds the 5 requestsId
*/
function getTopRequestIDs()
external
view
returns (uint256[5] memory _requestIds);
/**
* @dev Getter for the 5 requests Id's next in line to get mined
* @return idsOnDeck tipsOnDeck the 5 requestsId
*/
function getNewVariablesOnDeck()
external
view
returns (uint256[5] memory idsOnDeck, uint256[5] memory tipsOnDeck);
/**
* @dev Updates the Tellor address after a proposed fork has
* passed the vote and day has gone by without a dispute
* @param _disputeId the disputeId for the proposed fork
*/
function updateTellor(uint256 _disputeId) external;
/**
* @dev Allows disputer to unlock the dispute fee
* @param _disputeId to unlock fee from
*/
function unlockDisputeFee(uint256 _disputeId) external;
/**
* @param _user address
* @param _spender address
* @return Returns the remaining allowance of tokens granted to the _spender from the _user
*/
function allowance(address _user, address _spender)
external
view
returns (uint256);
/**
* @dev This function returns whether or not a given user is allowed to trade a given amount
* @param _user address
* @param _amount uint of amount
* @return true if the user is alloed to trade the amount specified
*/
function allowedToTrade(address _user, uint256 _amount)
external
view
returns (bool);
/**
* @dev Gets balance of owner specified
* @param _user is the owner address used to look up the balance
* @return Returns the balance associated with the passed in _user
*/
function balanceOf(address _user) external view returns (uint256);
/**
* @dev Queries the balance of _user at a specific _blockNumber
* @param _user The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at _blockNumber
*/
function balanceOfAt(address _user, uint256 _blockNumber)
external
view
returns (uint256);
/**
* @dev This function tells you if a given challenge has been completed by a given miner
* @param _challenge the challenge to search for
* @param _miner address that you want to know if they solved the challenge
* @return true if the _miner address provided solved the
*/
function didMine(bytes32 _challenge, address _miner)
external
view
returns (bool);
/**
* @dev Checks if an address voted in a given dispute
* @param _disputeId to look up
* @param _address to look up
* @return bool of whether or not party voted
*/
function didVote(uint256 _disputeId, address _address)
external
view
returns (bool);
/**
* @dev allows Tellor to read data from the addressVars mapping
* @param _data is the keccak256("variable_name") of the variable that is being accessed.
* These are examples of how the variables are saved within other functions:
* addressVars[keccak256("_owner")]
* addressVars[keccak256("tellorContract")]
* return address
*/
function getAddressVars(bytes32 _data) external view returns (address);
/**
* @dev Gets all dispute variables
* @param _disputeId to look up
* @return bytes32 hash of dispute
* @return bool executed where true if it has been voted on
* @return bool disputeVotePassed
* @return bool isPropFork true if the dispute is a proposed fork
* @return address of reportedMiner
* @return address of reportingParty
* @return address of proposedForkAddress
* uint of requestId
* uint of timestamp
* uint of value
* uint of minExecutionDate
* uint of numberOfVotes
* uint of blocknumber
* uint of minerSlot
* uint of quorum
* uint of fee
* @return int count of the current tally
*/
function getAllDisputeVars(uint256 _disputeId)
external
view
returns (
bytes32,
bool,
bool,
bool,
address,
address,
address,
uint256[9] memory,
int256
);
/**
* @dev Getter function for variables for the requestId being currently mined(currentRequestId)
* @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request
*/
function getCurrentVariables()
external
view
returns (
bytes32,
uint256,
uint256,
string memory,
uint256,
uint256
);
/**
* @dev Checks if a given hash of miner,requestId has been disputed
* @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId));
* @return uint disputeId
*/
function getDisputeIdByDisputeHash(bytes32 _hash)
external
view
returns (uint256);
/**
* @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId
* @param _disputeId is the dispute id;
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the disputeUintVars under the Dispute struct
* @return uint value for the bytes32 data submitted
*/
function getDisputeUintVars(uint256 _disputeId, bytes32 _data)
external
view
returns (uint256);
/**
* @dev Gets the a value for the latest timestamp available
* @return value for timestamp of last proof of work submited
* @return true if the is a timestamp for the lastNewValue
*/
function getLastNewValue() external view returns (uint256, bool);
/**
* @dev Gets the a value for the latest timestamp available
* @param _requestId being requested
* @return value for timestamp of last proof of work submited and if true if it exist or 0 and false if it doesn't
*/
function getLastNewValueById(uint256 _requestId)
external
view
returns (uint256, bool);
/**
* @dev Gets blocknumber for mined timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up blocknumber
* @return uint of the blocknumber which the dispute was mined
*/
function getMinedBlockNum(uint256 _requestId, uint256 _timestamp)
external
view
returns (uint256);
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return the 5 miners' addresses
*/
function getMinersByRequestIdAndTimestamp(
uint256 _requestId,
uint256 _timestamp
) external view returns (address[5] memory);
/**
* @dev Counts the number of values that have been submited for the request
* if called for the currentRequest being mined it can tell you how many miners have submitted a value for that
* request so far
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(uint256 _requestId)
external
view
returns (uint256);
/**
* @dev Getter function for the specified requestQ index
* @param _index to look up in the requestQ array
* @return uint of reqeuestId
*/
function getRequestIdByRequestQIndex(uint256 _index)
external
view
returns (uint256);
/**
* @dev Getter function for requestId based on timestamp
* @param _timestamp to check requestId
* @return uint of reqeuestId
*/
function getRequestIdByTimestamp(uint256 _timestamp)
external
view
returns (uint256);
/**
* @dev Getter function for requestId based on the queryHash
* @param _request is the hash(of string api and granularity) to check if a request already exists
* @return uint requestId
*/
function getRequestIdByQueryHash(bytes32 _request)
external
view
returns (uint256);
/**
* @dev Getter function for the requestQ array
* @return the requestQ arrray
*/
function getRequestQ() external view returns (uint256[51] memory);
/**
* @dev Allowes access to the uint variables saved in the apiUintVars under the requestDetails struct
* for the requestId specified
* @param _requestId to look up
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the apiUintVars under the requestDetails struct
* @return uint value of the apiUintVars specified in _data for the requestId specified
*/
function getRequestUintVars(uint256 _requestId, bytes32 _data)
external
view
returns (uint256);
/**
* @dev Gets the API struct variables that are not mappings
* @param _requestId to look up
* @return string of api to query
* @return string of symbol of api to query
* @return bytes32 hash of string
* @return bytes32 of the granularity(decimal places) requested
* @return uint of index in requestQ array
* @return uint of current payout/tip for this requestId
*/
function getRequestVars(uint256 _requestId)
external
view
returns (
string memory,
string memory,
bytes32,
uint256,
uint256,
uint256
);
/**
* @dev This function allows users to retireve all information about a staker
* @param _staker address of staker inquiring about
* @return uint current state of staker
* @return uint startDate of staking
*/
function getStakerInfo(address _staker)
external
view
returns (uint256, uint256);
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestampt to look up miners for
* @return address[5] array of 5 addresses ofminers that mined the requestId
*/
function getSubmissionsByTimestamp(uint256 _requestId, uint256 _timestamp)
external
view
returns (uint256[5] memory);
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestID is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(uint256 _requestID, uint256 _index)
external
view
returns (uint256);
/**
* @dev Getter for the variables saved under the TellorStorageStruct uintVars variable
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the uintVars under the TellorStorageStruct struct
* This is an example of how data is saved into the mapping within other functions:
* self.uintVars[keccak256("stakerCount")]
* @return uint of specified variable
*/
function getUintVar(bytes32 _data) external view returns (uint256);
/**
* @dev Getter function for next requestId on queue/request with highest payout at time the function is called
* @return onDeck/info on request with highest payout-- RequestId, Totaltips, and API query string
*/
function getVariablesOnDeck()
external
view
returns (
uint256,
uint256,
string memory
);
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestamp to look up miners for
* @return bool true if requestId/timestamp is under dispute
*/
function isInDispute(uint256 _requestId, uint256 _timestamp)
external
view
returns (bool);
/**
* @dev Retreive value from oracle based on timestamp
* @param _requestId being requested
* @param _timestamp to retreive data/value from
* @return value for timestamp submitted
*/
function retrieveData(uint256 _requestId, uint256 _timestamp)
external
view
returns (uint256);
/**
* @dev Getter for the total_supply of oracle tokens
* @return uint total supply
*/
function totalSupply() external view returns (uint256);
}
library LiquityMath {
using SafeMath for uint;
uint internal constant DECIMAL_PRECISION = 1e18;
/* Precision for Nominal ICR (independent of price). Rationale for the value:
*
* - Making it “too high” could lead to overflows.
* - Making it “too low” could lead to an ICR equal to zero, due to truncation from Solidity floor division.
*
* This value of 1e20 is chosen for safety: the NICR will only overflow for numerator > ~1e39 ETH,
* and will only truncate to 0 if the denominator is at least 1e20 times greater than the numerator.
*
*/
uint internal constant NICR_PRECISION = 1e20;
function _min(uint _a, uint _b) internal pure returns (uint) {
return (_a < _b) ? _a : _b;
}
function _max(uint _a, uint _b) internal pure returns (uint) {
return (_a >= _b) ? _a : _b;
}
/*
* Multiply two decimal numbers and use normal rounding rules:
* -round product up if 19'th mantissa digit >= 5
* -round product down if 19'th mantissa digit < 5
*
* Used only inside the exponentiation, _decPow().
*/
function decMul(uint x, uint y) internal pure returns (uint decProd) {
uint prod_xy = x.mul(y);
decProd = prod_xy.add(DECIMAL_PRECISION / 2).div(DECIMAL_PRECISION);
}
/*
* _decPow: Exponentiation function for 18-digit decimal base, and integer exponent n.
*
* Uses the efficient "exponentiation by squaring" algorithm. O(log(n)) complexity.
*
* Called by two functions that represent time in units of minutes:
* 1) TroveManager._calcDecayedBaseRate
* 2) CommunityIssuance._getCumulativeIssuanceFraction
*
* The exponent is capped to avoid reverting due to overflow. The cap 525600000 equals
* "minutes in 1000 years": 60 * 24 * 365 * 1000
*
* If a period of > 1000 years is ever used as an exponent in either of the above functions, the result will be
* negligibly different from just passing the cap, since:
*
* In function 1), the decayed base rate will be 0 for 1000 years or > 1000 years
* In function 2), the difference in tokens issued at 1000 years and any time > 1000 years, will be negligible
*/
function _decPow(uint _base, uint _minutes) internal pure returns (uint) {
if (_minutes > 525600000) {_minutes = 525600000;} // cap to avoid overflow
if (_minutes == 0) {return DECIMAL_PRECISION;}
uint y = DECIMAL_PRECISION;
uint x = _base;
uint n = _minutes;
// Exponentiation-by-squaring
while (n > 1) {
if (n % 2 == 0) {
x = decMul(x, x);
n = n.div(2);
} else { // if (n % 2 != 0)
y = decMul(x, y);
x = decMul(x, x);
n = (n.sub(1)).div(2);
}
}
return decMul(x, y);
}
function _getAbsoluteDifference(uint _a, uint _b) internal pure returns (uint) {
return (_a >= _b) ? _a.sub(_b) : _b.sub(_a);
}
function _computeNominalCR(uint _coll, uint _debt) internal pure returns (uint) {
if (_debt > 0) {
return _coll.mul(NICR_PRECISION).div(_debt);
}
// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR.
else { // if (_debt == 0)
return 2**256 - 1;
}
}
function _computeCR(uint _coll, uint _debt, uint _price) internal pure returns (uint) {
if (_debt > 0) {
uint newCollRatio = _coll.mul(_price).div(_debt);
return newCollRatio;
}
// Return the maximal value for uint256 if the Trove has a debt of 0. Represents "infinite" CR.
else { // if (_debt == 0)
return 2**256 - 1;
}
}
}
library LiquitySafeMath128 {
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 c = a + b;
require(c >= a, "LiquitySafeMath128: addition overflow");
return c;
}
function sub(uint128 a, uint128 b) internal pure returns (uint128) {
require(b <= a, "LiquitySafeMath128: subtraction overflow");
uint128 c = a - b;
return c;
}
}
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), msg.sender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*
* NOTE: This function is not safe, as it doesn’t check owner is calling it.
* Make sure you check it before calling it.
*/
function _renounceOwnership() internal {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
}
interface IBorrowerOperations {
// --- Events ---
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event RUBCAddressChanged(address _rubcAddress);
event RBSTStakingAddressChanged(address _rbstStakingAddress);
event TroveCreated(address indexed _borrower, uint arrayIndex);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event RUBCBorrowingFeePaid(address indexed _borrower, uint _RUBCFee);
// --- Functions ---
function setAddresses(
address _troveManagerAddress,
address _activePoolAddress,
address _defaultPoolAddress,
address _stabilityPoolAddress,
address _gasPoolAddress,
address _collSurplusPoolAddress,
address _priceFeedAddress,
address _sortedTrovesAddress,
address _rubcAddress,
address _rbstStakingAddress
) external;
function openTrove(uint _maxFee, uint _RUBCAmount, address _upperHint, address _lowerHint) external payable;
function addColl(address _upperHint, address _lowerHint) external payable;
function moveETHGainToTrove(address _user, address _upperHint, address _lowerHint) external payable;
function withdrawColl(uint _amount, address _upperHint, address _lowerHint) external;
function withdrawRUBC(uint _maxFee, uint _amount, address _upperHint, address _lowerHint) external;
function repayRUBC(uint _amount, address _upperHint, address _lowerHint) external;
function closeTrove() external;
function adjustTrove(uint _maxFee, uint _collWithdrawal, uint _debtChange, bool isDebtIncrease, address _upperHint, address _lowerHint) external payable;
function claimCollateral() external;
function getCompositeDebt(uint _debt) external pure returns (uint);
}
interface ICollSurplusPool {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event CollBalanceUpdated(address indexed _account, uint _newBalance);
event EtherSent(address _to, uint _amount);
// --- Contract setters ---
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress
) external;
function getETH() external view returns (uint);
function getCollateral(address _account) external view returns (uint);
function accountSurplus(address _account, uint _amount) external;
function claimColl(address _account) external;
}
interface ICommunityIssuance {
// --- Events ---
event RBSTAddressSet(address _rbstAddress);
event StabilityPoolAddressSet(address _stabilityPoolAddress);
event TotalRBSTIssuedUpdated(uint _totalRBSTIssued);
// --- Functions ---
function setAddresses(address _rbstAddress, address _stabilityPoolAddress) external;
function issueRBST() external returns (uint);
function sendRBST(address _account, uint _RBSTamount) external;
}
interface ILockupContractFactory {
// --- Events ---
event RBSTAddressSet(address _rbstAddress);
event LockupContractDeployedThroughFactory(address _lockupContractAddress, address _beneficiary, uint _unlockTime, address _deployer);
// --- Functions ---
function setRBSTAddress(address _rbstAddress) external;
function deployLockupContract(address _beneficiary, uint _unlockTime) external;
function isRegisteredLockup(address _addr) external view returns (bool);
}
// Common interface for the Pools.
interface IPool {
// --- Events ---
event ETHBalanceUpdated(uint _newBalance);
event RUBCBalanceUpdated(uint _newBalance);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
event StabilityPoolAddressChanged(address _newStabilityPoolAddress);
event EtherSent(address _to, uint _amount);
// --- Functions ---
function getETH() external view returns (uint);
function getRUBCDebt() external view returns (uint);
function increaseRUBCDebt(uint _amount) external;
function decreaseRUBCDebt(uint _amount) external;
}
interface IPriceFeed {
// --- Events ---
event LastGoodPriceUpdated(uint _lastGoodPrice);
// --- Function ---
function fetchPrice() external returns (uint);
function fetchRUBPriceFeedUpdateTimestamp() external returns(uint256);
}
interface IRBST is IERC20, IERC2612 {
// --- Events ---
event CommunityIssuanceAddressSet(address _communityIssuanceAddress);
event RBSTStakingAddressSet(address _rbstStakingAddress);
event LockupContractFactoryAddressSet(address _lockupContractFactoryAddress);
// --- Functions ---
function sendToRBSTStaking(address _sender, uint256 _amount) external;
function getDeploymentStartTime() external view returns (uint256);
function getLpRewardsEntitlement() external view returns (uint256);
}
interface IRBSTStaking {
// --- Events --
event RBSTAddressSet(address _rbstAddress);
event RUBCAddressSet(address _rubcAddress);
event TroveManagerAddressSet(address _troveManager);
event BorrowerOperationsAddressSet(address _borrowerOperationsAddress);
event ActivePoolAddressSet(address _activePoolAddress);
event StakeChanged(address indexed staker, uint newStake);
event StakingGainsWithdrawn(address indexed staker, uint RUBCGain, uint ETHGain);
event F_ETHUpdated(uint _F_ETH);
event F_RUBCUpdated(uint _F_RUBC);
event TotalRBSTStakedUpdated(uint _totalRBSTStaked);
event EtherSent(address _account, uint _amount);
event StakerSnapshotsUpdated(address _staker, uint _F_ETH, uint _F_RUBC);
// --- Functions ---
function setAddresses
(
address _rbstAddress,
address _rubcAddress,
address _troveManagerAddress,
address _borrowerOperationsAddress,
address _activePoolAddress
) external;
function stake(uint _RBSTamount) external;
function unstake(uint _RBSTamount) external;
function increaseF_ETH(uint _ETHFee) external;
function increaseF_RUBC(uint _RBSTFee) external;
function getPendingETHGain(address _user) external view returns (uint);
function getPendingRUBCGain(address _user) external view returns (uint);
}
interface IRUBC is IERC20, IERC2612 {
// --- Events ---
event TroveManagerAddressChanged(address _troveManagerAddress);
event StabilityPoolAddressChanged(address _newStabilityPoolAddress);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event RUBCBalanceUpdated(address _user, uint _amount);
// --- Functions ---
function mint(address _account, uint256 _amount) external;
function burn(address _account, uint256 _amount) external;
function sendToPool(address _sender, address poolAddress, uint256 _amount) external;
function returnFromPool(address poolAddress, address user, uint256 _amount ) external;
}
interface ISortedTroves {
// --- Events ---
event SortedTrovesAddressChanged(address _sortedDoublyLLAddress);
event BorrowerOperationsAddressChanged(address _borrowerOperationsAddress);
event NodeAdded(address _id, uint _NICR);
event NodeRemoved(address _id);
// --- Functions ---
function setParams(uint256 _size, address _TroveManagerAddress, address _borrowerOperationsAddress) external;
function insert(address _id, uint256 _ICR, address _prevId, address _nextId) external;
function remove(address _id) external;
function reInsert(address _id, uint256 _newICR, address _prevId, address _nextId) external;
function contains(address _id) external view returns (bool);
function isFull() external view returns (bool);
function isEmpty() external view returns (bool);
function getSize() external view returns (uint256);
function getMaxSize() external view returns (uint256);
function getFirst() external view returns (address);
function getLast() external view returns (address);
function getNext(address _id) external view returns (address);
function getPrev(address _id) external view returns (address);
function validInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (bool);
function findInsertPosition(uint256 _ICR, address _prevId, address _nextId) external view returns (address, address);
}
interface IStabilityPool {
// --- Events ---
event StabilityPoolETHBalanceUpdated(uint _newBalance);
event StabilityPoolRUBCBalanceUpdated(uint _newBalance);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
event RUBCAddressChanged(address _newRUBCAddress);
event SortedTrovesAddressChanged(address _newSortedTrovesAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress);
event P_Updated(uint _P);
event S_Updated(uint _S, uint128 _epoch, uint128 _scale);
event G_Updated(uint _G, uint128 _epoch, uint128 _scale);
event EpochUpdated(uint128 _currentEpoch);
event ScaleUpdated(uint128 _currentScale);
event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate);
event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd);
event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G);
event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G);
event UserDepositChanged(address indexed _depositor, uint _newDeposit);
event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor);
event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss);
event RBSTPaidToDepositor(address indexed _depositor, uint _RBST);
event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST);
event EtherSent(address _to, uint _amount);
// --- Functions ---
/*
* Called only once on init, to set addresses of other Liquity contracts
* Callable only by owner, renounces ownership at the end
*/
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress,
address _rubcAddress,
address _sortedTrovesAddress,
address _priceFeedAddress,
address _communityIssuanceAddress
) external;
/*
* Initial checks:
* - Frontend is registered or zero address
* - Sender is not a registered frontend
* - _amount is not zero
* ---
* - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends
* - Tags the deposit with the provided front end tag param, if it's a new deposit
* - Sends depositor's accumulated gains (RBST, ETH) to depositor
* - Sends the tagged front end's accumulated RBST gains to the tagged front end
* - Increases deposit and tagged front end's stake, and takes new snapshots for each.
*/
function provideToSP(uint _amount, address _frontEndTag) external;
/*
* Initial checks:
* - _amount is zero or there are no under collateralized troves left in the system
* - User has a non zero deposit
* ---
* - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends
* - Removes the deposit's front end tag if it is a full withdrawal
* - Sends all depositor's accumulated gains (RBST, ETH) to depositor
* - Sends the tagged front end's accumulated RBST gains to the tagged front end
* - Decreases deposit and tagged front end's stake, and takes new snapshots for each.
*
* If _amount > userDeposit, the user withdraws all of their compounded deposit.
*/
function withdrawFromSP(uint _amount) external;
/*
* Initial checks:
* - User has a non zero deposit
* - User has an open trove
* - User has some ETH gain
* ---
* - Triggers a RBST issuance, based on time passed since the last issuance. The RBST issuance is shared between *all* depositors and front ends
* - Sends all depositor's RBST gain to depositor
* - Sends all tagged front end's RBST gain to the tagged front end
* - Transfers the depositor's entire ETH gain from the Stability Pool to the caller's trove
* - Leaves their compounded deposit in the Stability Pool
* - Updates snapshots for deposit and tagged front end stake
*/
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external;
/*
* Initial checks:
* - Frontend (sender) not already registered
* - User (sender) has no deposit
* - _kickbackRate is in the range [0, 100%]
* ---
* Front end makes a one-time selection of kickback rate upon registering
*/
function registerFrontEnd(uint _kickbackRate) external;
/*
* Initial checks:
* - Caller is TroveManager
* ---
* Cancels out the specified debt against the RUBC contained in the Stability Pool (as far as possible)
* and transfers the Trove's ETH collateral from ActivePool to StabilityPool.
* Only called by liquidation functions in the TroveManager.
*/
function offset(uint _debt, uint _coll) external;
/*
* Returns the total amount of ETH held by the pool, accounted in an internal variable instead of `balance`,
* to exclude edge cases like ETH received from a self-destruct.
*/
function getETH() external view returns (uint);
/*
* Returns RUBC held in the pool. Changes when users deposit/withdraw, and when Trove debt is offset.
*/
function getTotalRUBCDeposits() external view returns (uint);
/*
* Calculates the ETH gain earned by the deposit since its last snapshots were taken.
*/
function getDepositorETHGain(address _depositor) external view returns (uint);
/*
* Calculate the RBST gain earned by a deposit since its last snapshots were taken.
* If not tagged with a front end, the depositor gets a 100% cut of what their deposit earned.
* Otherwise, their cut of the deposit's earnings is equal to the kickbackRate, set by the front end through
* which they made their deposit.
*/
function getDepositorRBSTGain(address _depositor) external view returns (uint);
/*
* Return the RBST gain earned by the front end.
*/
function getFrontEndRBSTGain(address _frontEnd) external view returns (uint);
/*
* Return the user's compounded deposit.
*/
function getCompoundedRUBCDeposit(address _depositor) external view returns (uint);
/*
* Return the front end's compounded stake.
*
* The front end's compounded stake is equal to the sum of its depositors' compounded deposits.
*/
function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint);
/*
* Fallback function
* Only callable by Active Pool, it just accounts for ETH received
* receive() external payable;
*/
}
interface ITellorCaller {
function getTellorCurrentValue(uint256 _requestId) external view returns (bool, uint256, uint256);
}
contract TellorCaller is ITellorCaller {
using SafeMath for uint256;
ITellor public tellor;
constructor (address _tellorMasterAddress) public {
tellor = ITellor(_tellorMasterAddress);
}
/*
* getTellorCurrentValue(): identical to getCurrentValue() in UsingTellor.sol
*
* @dev Allows the user to get the latest value for the requestId specified
* @param _requestId is the requestId to look up the value for
* @return ifRetrieve bool true if it is able to retrieve a value, the value, and the value's timestamp
* @return value the value retrieved
* @return _timestampRetrieved the value's timestamp
*/
function getTellorCurrentValue(uint256 _requestId)
external
view
override
returns (
bool ifRetrieve,
uint256 value,
uint256 _timestampRetrieved
)
{
uint256 _count = tellor.getNewValueCountbyRequestId(_requestId);
uint256 _time =
tellor.getTimestampbyRequestIDandIndex(_requestId, _count.sub(1));
uint256 _value = tellor.retrieveData(_requestId, _time);
if (_value > 0) return (true, _value, _time);
return (false, 0, _time);
}
}
interface IActivePool is IPool {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolRUBCDebtUpdated(uint _RUBCDebt);
event ActivePoolETHBalanceUpdated(uint _ETH);
// --- Functions ---
function sendETH(address _account, uint _amount) external;
}
interface IDefaultPool is IPool {
// --- Events ---
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event DefaultPoolRUBCDebtUpdated(uint _RUBCDebt);
event DefaultPoolETHBalanceUpdated(uint _ETH);
// --- Functions ---
function sendETHToActivePool(uint _amount) external;
}
interface ILiquityBase {
function priceFeed() external view returns (IPriceFeed);
}
interface ITroveManager is ILiquityBase {
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event RUBCAddressChanged(address _newRUBCAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event RBSTAddressChanged(address _rbstAddress);
event RBSTStakingAddressChanged(address _rbstStakingAddress);
event Liquidation(uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _RUBCGasCompensation);
event Redemption(uint _attemptedRUBCAmount, uint _actualRUBCAmount, uint _ETHSent, uint _ETHFee);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint stake, uint8 operation);
event TroveLiquidated(address indexed _borrower, uint _debt, uint _coll, uint8 operation);
event BaseRateUpdated(uint _baseRate);
event LastFeeOpTimeUpdated(uint _lastFeeOpTime);
event TotalStakesUpdated(uint _newTotalStakes);
event SystemSnapshotsUpdated(uint _totalStakesSnapshot, uint _totalCollateralSnapshot);
event LTermsUpdated(uint _L_ETH, uint _L_RUBCDebt);
event TroveSnapshotsUpdated(uint _L_ETH, uint _L_RUBCDebt);
event TroveIndexUpdated(address _borrower, uint _newIndex);
// --- Functions ---
function setAddresses(
address _borrowerOperationsAddress,
address _activePoolAddress,
address _defaultPoolAddress,
address _stabilityPoolAddress,
address _gasPoolAddress,
address _collSurplusPoolAddress,
address _priceFeedAddress,
address _rubcAddress,
address _sortedTrovesAddress,
address _rbstAddress,
address _rbstStakingAddress
) external;
function stabilityPool() external view returns (IStabilityPool);
function rubc() external view returns (IRUBC);
function rbst() external view returns (IRBST);
function rbstStaking() external view returns (IRBSTStaking);
function getTroveOwnersCount() external view returns (uint);
function getTroveFromTroveOwnersArray(uint _index) external view returns (address);
function getNominalICR(address _borrower) external view returns (uint);
function getCurrentICR(address _borrower, uint _price) external view returns (uint);
function liquidate(address _borrower) external;
function liquidateTroves(uint _n) external;
function batchLiquidateTroves(address[] calldata _troveArray) external;
function redeemCollateral(
uint _RUBCAmount,
address _firstRedemptionHint,
address _upperPartialRedemptionHint,
address _lowerPartialRedemptionHint,
uint _partialRedemptionHintNICR,
uint _maxIterations,
uint _maxFee
) external;
function updateStakeAndTotalStakes(address _borrower) external returns (uint);
function updateTroveRewardSnapshots(address _borrower) external;
function addTroveOwnerToArray(address _borrower) external returns (uint index);
function applyPendingRewards(address _borrower) external;
function getPendingETHReward(address _borrower) external view returns (uint);
function getPendingRUBCDebtReward(address _borrower) external view returns (uint);
function hasPendingRewards(address _borrower) external view returns (bool);
function getEntireDebtAndColl(address _borrower) external view returns (
uint debt,
uint coll,
uint pendingRUBCDebtReward,
uint pendingETHReward
);
function closeTrove(address _borrower) external;
function removeStake(address _borrower) external;
function getRedemptionRate() external view returns (uint);
function getRedemptionRateWithDecay() external view returns (uint);
function getRedemptionFeeWithDecay(uint _ETHDrawn) external view returns (uint);
function getBorrowingRate() external view returns (uint);
function getBorrowingRateWithDecay() external view returns (uint);
function getBorrowingFee(uint RUBCDebt) external view returns (uint);
function getBorrowingFeeWithDecay(uint _RUBCDebt) external view returns (uint);
function decayBaseRateFromBorrowing() external;
function getTroveStatus(address _borrower) external view returns (uint);
function getTroveStake(address _borrower) external view returns (uint);
function getTroveDebt(address _borrower) external view returns (uint);
function getTroveColl(address _borrower) external view returns (uint);
function setTroveStatus(address _borrower, uint num) external;
function increaseTroveColl(address _borrower, uint _collIncrease) external returns (uint);
function decreaseTroveColl(address _borrower, uint _collDecrease) external returns (uint);
function increaseTroveDebt(address _borrower, uint _debtIncrease) external returns (uint);
function decreaseTroveDebt(address _borrower, uint _collDecrease) external returns (uint);
function getTCR(uint _price) external view returns (uint);
function checkRecoveryMode(uint _price) external view returns (bool);
}
contract LiquityBase is BaseMath, ILiquityBase {
using SafeMath for uint;
uint constant public _100pct = 1000000000000000000; // 1e18 == 100%
// Minimum collateral ratio for individual troves
uint constant public MCR = 1100000000000000000; // 110%
// Critical system collateral ratio. If the system's total collateral ratio (TCR) falls below the CCR, Recovery Mode is triggered.
uint constant public CCR = 1500000000000000000; // 150%
// Amount of RUBC to be locked in gas pool on opening troves
uint constant public RUBC_GAS_COMPENSATION = 20_000e18;
// Minimum amount of net RUBC debt a trove must have
uint constant public MIN_NET_DEBT = 100_000e18;
uint constant public PERCENT_DIVISOR = 200; // dividing by 200 yields 0.5%
uint constant public BORROWING_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 5; // 0.5%
IActivePool public activePool;
IDefaultPool public defaultPool;
IPriceFeed public override priceFeed;
// --- Gas compensation functions ---
// Returns the composite debt (drawn debt + gas compensation) of a trove, for the purpose of ICR calculation
function _getCompositeDebt(uint _debt) internal pure returns (uint) {
return _debt.add(RUBC_GAS_COMPENSATION);
}
function _getNetDebt(uint _debt) internal pure returns (uint) {
return _debt.sub(RUBC_GAS_COMPENSATION);
}
// Return the amount of ETH to be drawn from a trove's collateral and sent as gas compensation.
function _getCollGasCompensation(uint _entireColl) internal pure returns (uint) {
return _entireColl / PERCENT_DIVISOR;
}
function getEntireSystemColl() public view returns (uint entireSystemColl) {
uint activeColl = activePool.getETH();
uint liquidatedColl = defaultPool.getETH();
return activeColl.add(liquidatedColl);
}
function getEntireSystemDebt() public view returns (uint entireSystemDebt) {
uint activeDebt = activePool.getRUBCDebt();
uint closedDebt = defaultPool.getRUBCDebt();
return activeDebt.add(closedDebt);
}
function _getTCR(uint _price) internal view returns (uint TCR) {
uint entireSystemColl = getEntireSystemColl();
uint entireSystemDebt = getEntireSystemDebt();
TCR = LiquityMath._computeCR(entireSystemColl, entireSystemDebt, _price);
return TCR;
}
function _checkRecoveryMode(uint _price) internal view returns (bool) {
uint TCR = _getTCR(_price);
return TCR < CCR;
}
function _requireUserAcceptsFee(uint _fee, uint _amount, uint _maxFeePercentage) internal pure {
uint feePercentage = _fee.mul(DECIMAL_PRECISION).div(_amount);
require(feePercentage <= _maxFeePercentage, "Fee exceeded provided maximum");
}
}
contract TroveManager is LiquityBase, Ownable, CheckContract, ITroveManager {
string constant public NAME = "TroveManager";
// --- Connected contract declarations ---
address public borrowerOperationsAddress;
IStabilityPool public override stabilityPool;
address gasPoolAddress;
ICollSurplusPool collSurplusPool;
IRUBC public override rubc;
IRBST public override rbst;
IRBSTStaking public override rbstStaking;
// A doubly linked list of Troves, sorted by their sorted by their collateral ratios
ISortedTroves public sortedTroves;
// --- Data structures ---
uint constant public SECONDS_IN_ONE_MINUTE = 60;
/*
* Half-life of 12h. 12h = 720 min
* (1/2) = d^720 => d = (1/2)^(1/720)
*/
uint constant public MINUTE_DECAY_FACTOR = 999037758833783000;
uint constant public REDEMPTION_FEE_FLOOR = DECIMAL_PRECISION / 1000 * 25; // 2.5%
uint constant public MAX_BORROWING_FEE = DECIMAL_PRECISION / 100 * 5; // 5%
// amount of time from an oracle update where a redemption may take place
//uint constant public REDEMPTION_WINDOW_SECONDS = 10 minutes;
uint constant public REDEMPTION_WINDOW_SECONDS = 1 days;
// During bootsrap period redemptions are not allowed
uint constant public BOOTSTRAP_PERIOD = 10 days;
/*
* BETA: 18 digit decimal. Parameter by which to divide the redeemed fraction, in order to calc the new base rate from a redemption.
* Corresponds to (1 / ALPHA) in the white paper.
*/
uint constant public BETA = 2;
uint public baseRate;
// The timestamp of the latest fee operation (redemption or new RUBC issuance)
uint public lastFeeOperationTime;
enum Status {
nonExistent,
active,
closedByOwner,
closedByLiquidation,
closedByRedemption
}
// Store the necessary data for a trove
struct Trove {
uint debt;
uint coll;
uint stake;
Status status;
uint128 arrayIndex;
}
mapping (address => Trove) public Troves;
uint public totalStakes;
// Snapshot of the value of totalStakes, taken immediately after the latest liquidation
uint public totalStakesSnapshot;
// Snapshot of the total collateral across the ActivePool and DefaultPool, immediately after the latest liquidation.
uint public totalCollateralSnapshot;
/*
* L_ETH and L_RUBCDebt track the sums of accumulated liquidation rewards per unit staked. During its lifetime, each stake earns:
*
* An ETH gain of ( stake * [L_ETH - L_ETH(0)] )
* A RUBCDebt increase of ( stake * [L_RUBCDebt - L_RUBCDebt(0)] )
*
* Where L_ETH(0) and L_RUBCDebt(0) are snapshots of L_ETH and L_RUBCDebt for the active Trove taken at the instant the stake was made
*/
uint public L_ETH;
uint public L_RUBCDebt;
// Map addresses with active troves to their RewardSnapshot
mapping (address => RewardSnapshot) public rewardSnapshots;
// Object containing the ETH and RUBC snapshots for a given active trove
struct RewardSnapshot { uint ETH; uint RUBCDebt;}
// Array of all active trove addresses - used to to compute an approximate hint off-chain, for the sorted list insertion
address[] public TroveOwners;
// Error trackers for the trove redistribution calculation
uint public lastETHError_Redistribution;
uint public lastRUBCDebtError_Redistribution;
/*
* --- Variable container structs for liquidations ---
*
* These structs are used to hold, return and assign variables inside the liquidation functions,
* in order to avoid the error: "CompilerError: Stack too deep".
**/
struct LocalVariables_OuterLiquidationFunction {
uint price;
uint RUBCInStabPool;
bool recoveryModeAtStart;
uint liquidatedDebt;
uint liquidatedColl;
}
struct LocalVariables_InnerSingleLiquidateFunction {
uint collToLiquidate;
uint pendingDebtReward;
uint pendingCollReward;
}
struct LocalVariables_LiquidationSequence {
uint remainingRUBCInStabPool;
uint i;
uint ICR;
address user;
bool backToNormalMode;
uint entireSystemDebt;
uint entireSystemColl;
}
struct LiquidationValues {
uint entireTroveDebt;
uint entireTroveColl;
uint collGasCompensation;
uint RUBCGasCompensation;
uint debtToOffset;
uint collToSendToSP;
uint debtToRedistribute;
uint collToRedistribute;
uint collSurplus;
}
struct LiquidationTotals {
uint totalCollInSequence;
uint totalDebtInSequence;
uint totalCollGasCompensation;
uint totalRUBCGasCompensation;
uint totalDebtToOffset;
uint totalCollToSendToSP;
uint totalDebtToRedistribute;
uint totalCollToRedistribute;
uint totalCollSurplus;
}
struct ContractsCache {
IActivePool activePool;
IDefaultPool defaultPool;
IRUBC rubc;
IRBSTStaking rbstStaking;
ISortedTroves sortedTroves;
ICollSurplusPool collSurplusPool;
address gasPoolAddress;
}
// --- Variable container structs for redemptions ---
struct RedemptionTotals {
uint remainingRUBC;
uint totalRUBCToRedeem;
uint totalETHDrawn;
uint ETHFee;
uint ETHToSendToRedeemer;
uint decayedBaseRate;
uint price;
uint totalRUBCSupplyAtStart;
}
struct SingleRedemptionValues {
uint RUBCLot;
uint ETHLot;
bool cancelledPartial;
}
// --- Events ---
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event RUBCAddressChanged(address _newRUBCAddress);
event ActivePoolAddressChanged(address _activePoolAddress);
event DefaultPoolAddressChanged(address _defaultPoolAddress);
event StabilityPoolAddressChanged(address _stabilityPoolAddress);
event GasPoolAddressChanged(address _gasPoolAddress);
event CollSurplusPoolAddressChanged(address _collSurplusPoolAddress);
event SortedTrovesAddressChanged(address _sortedTrovesAddress);
event RBSTAddressChanged(address _rbstAddress);
event RBSTStakingAddressChanged(address _rbstStakingAddress);
event Liquidation(uint _liquidatedDebt, uint _liquidatedColl, uint _collGasCompensation, uint _RUBCGasCompensation);
event Redemption(uint _attemptedRUBCAmount, uint _actualRUBCAmount, uint _ETHSent, uint _ETHFee);
event TroveUpdated(address indexed _borrower, uint _debt, uint _coll, uint _stake, TroveManagerOperation _operation);
event TroveLiquidated(address indexed _borrower, uint _debt, uint _coll, TroveManagerOperation _operation);
event BaseRateUpdated(uint _baseRate);
event LastFeeOpTimeUpdated(uint _lastFeeOpTime);
event TotalStakesUpdated(uint _newTotalStakes);
event SystemSnapshotsUpdated(uint _totalStakesSnapshot, uint _totalCollateralSnapshot);
event LTermsUpdated(uint _L_ETH, uint _L_RUBCDebt);
event TroveSnapshotsUpdated(uint _L_ETH, uint _L_RUBCDebt);
event TroveIndexUpdated(address _borrower, uint _newIndex);
enum TroveManagerOperation {
applyPendingRewards,
liquidateInNormalMode,
liquidateInRecoveryMode,
redeemCollateral
}
// --- Dependency setter ---
function setAddresses(
address _borrowerOperationsAddress,
address _activePoolAddress,
address _defaultPoolAddress,
address _stabilityPoolAddress,
address _gasPoolAddress,
address _collSurplusPoolAddress,
address _priceFeedAddress,
address _rubcAddress,
address _sortedTrovesAddress,
address _rbstAddress,
address _rbstStakingAddress
)
external
override
onlyOwner
{
checkContract(_borrowerOperationsAddress);
checkContract(_activePoolAddress);
checkContract(_defaultPoolAddress);
checkContract(_stabilityPoolAddress);
checkContract(_gasPoolAddress);
checkContract(_collSurplusPoolAddress);
checkContract(_priceFeedAddress);
checkContract(_rubcAddress);
checkContract(_sortedTrovesAddress);
checkContract(_rbstAddress);
checkContract(_rbstStakingAddress);
borrowerOperationsAddress = _borrowerOperationsAddress;
activePool = IActivePool(_activePoolAddress);
defaultPool = IDefaultPool(_defaultPoolAddress);
stabilityPool = IStabilityPool(_stabilityPoolAddress);
gasPoolAddress = _gasPoolAddress;
collSurplusPool = ICollSurplusPool(_collSurplusPoolAddress);
priceFeed = IPriceFeed(_priceFeedAddress);
rubc = IRUBC(_rubcAddress);
sortedTroves = ISortedTroves(_sortedTrovesAddress);
rbst = IRBST(_rbstAddress);
rbstStaking = IRBSTStaking(_rbstStakingAddress);
emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress);
emit ActivePoolAddressChanged(_activePoolAddress);
emit DefaultPoolAddressChanged(_defaultPoolAddress);
emit StabilityPoolAddressChanged(_stabilityPoolAddress);
emit GasPoolAddressChanged(_gasPoolAddress);
emit CollSurplusPoolAddressChanged(_collSurplusPoolAddress);
emit PriceFeedAddressChanged(_priceFeedAddress);
emit RUBCAddressChanged(_rubcAddress);
emit SortedTrovesAddressChanged(_sortedTrovesAddress);
emit RBSTAddressChanged(_rbstAddress);
emit RBSTStakingAddressChanged(_rbstStakingAddress);
_renounceOwnership();
}
// --- Getters ---
function getTroveOwnersCount() external view override returns (uint) {
return TroveOwners.length;
}
function getTroveFromTroveOwnersArray(uint _index) external view override returns (address) {
return TroveOwners[_index];
}
// --- Trove Liquidation functions ---
// Single liquidation function. Closes the trove if its ICR is lower than the minimum collateral ratio.
function liquidate(address _borrower) external override {
_requireTroveIsActive(_borrower);
address[] memory borrowers = new address[](1);
borrowers[0] = _borrower;
batchLiquidateTroves(borrowers);
}
// --- Inner single liquidation functions ---
// Liquidate one trove, in Normal Mode.
function _liquidateNormalMode(
IActivePool _activePool,
IDefaultPool _defaultPool,
address _borrower,
uint _RUBCInStabPool
)
internal
returns (LiquidationValues memory singleLiquidation)
{
LocalVariables_InnerSingleLiquidateFunction memory vars;
(singleLiquidation.entireTroveDebt,
singleLiquidation.entireTroveColl,
vars.pendingDebtReward,
vars.pendingCollReward) = getEntireDebtAndColl(_borrower);
_movePendingTroveRewardsToActivePool(_activePool, _defaultPool, vars.pendingDebtReward, vars.pendingCollReward);
_removeStake(_borrower);
singleLiquidation.collGasCompensation = _getCollGasCompensation(singleLiquidation.entireTroveColl);
singleLiquidation.RUBCGasCompensation = RUBC_GAS_COMPENSATION;
uint collToLiquidate = singleLiquidation.entireTroveColl.sub(singleLiquidation.collGasCompensation);
(singleLiquidation.debtToOffset,
singleLiquidation.collToSendToSP,
singleLiquidation.debtToRedistribute,
singleLiquidation.collToRedistribute) = _getOffsetAndRedistributionVals(singleLiquidation.entireTroveDebt, collToLiquidate, _RUBCInStabPool);
_closeTrove(_borrower, Status.closedByLiquidation);
emit TroveLiquidated(_borrower, singleLiquidation.entireTroveDebt, singleLiquidation.entireTroveColl, TroveManagerOperation.liquidateInNormalMode);
emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.liquidateInNormalMode);
return singleLiquidation;
}
// Liquidate one trove, in Recovery Mode.
function _liquidateRecoveryMode(
IActivePool _activePool,
IDefaultPool _defaultPool,
address _borrower,
uint _ICR,
uint _RUBCInStabPool,
uint _TCR,
uint _price
)
internal
returns (LiquidationValues memory singleLiquidation)
{
LocalVariables_InnerSingleLiquidateFunction memory vars;
if (TroveOwners.length <= 1) {return singleLiquidation;} // don't liquidate if last trove
(singleLiquidation.entireTroveDebt,
singleLiquidation.entireTroveColl,
vars.pendingDebtReward,
vars.pendingCollReward) = getEntireDebtAndColl(_borrower);
singleLiquidation.collGasCompensation = _getCollGasCompensation(singleLiquidation.entireTroveColl);
singleLiquidation.RUBCGasCompensation = RUBC_GAS_COMPENSATION;
vars.collToLiquidate = singleLiquidation.entireTroveColl.sub(singleLiquidation.collGasCompensation);
// If ICR <= 100%, purely redistribute the Trove across all active Troves
if (_ICR <= _100pct) {
_movePendingTroveRewardsToActivePool(_activePool, _defaultPool, vars.pendingDebtReward, vars.pendingCollReward);
_removeStake(_borrower);
singleLiquidation.debtToOffset = 0;
singleLiquidation.collToSendToSP = 0;
singleLiquidation.debtToRedistribute = singleLiquidation.entireTroveDebt;
singleLiquidation.collToRedistribute = vars.collToLiquidate;
_closeTrove(_borrower, Status.closedByLiquidation);
emit TroveLiquidated(_borrower, singleLiquidation.entireTroveDebt, singleLiquidation.entireTroveColl, TroveManagerOperation.liquidateInRecoveryMode);
emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.liquidateInRecoveryMode);
// If 100% < ICR < MCR, offset as much as possible, and redistribute the remainder
} else if ((_ICR > _100pct) && (_ICR < MCR)) {
_movePendingTroveRewardsToActivePool(_activePool, _defaultPool, vars.pendingDebtReward, vars.pendingCollReward);
_removeStake(_borrower);
(singleLiquidation.debtToOffset,
singleLiquidation.collToSendToSP,
singleLiquidation.debtToRedistribute,
singleLiquidation.collToRedistribute) = _getOffsetAndRedistributionVals(singleLiquidation.entireTroveDebt, vars.collToLiquidate, _RUBCInStabPool);
_closeTrove(_borrower, Status.closedByLiquidation);
emit TroveLiquidated(_borrower, singleLiquidation.entireTroveDebt, singleLiquidation.entireTroveColl, TroveManagerOperation.liquidateInRecoveryMode);
emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.liquidateInRecoveryMode);
/*
* If 110% <= ICR < current TCR (accounting for the preceding liquidations in the current sequence)
* and there is RUBC in the Stability Pool, only offset, with no redistribution,
* but at a capped rate of 1.1 and only if the whole debt can be liquidated.
* The remainder due to the capped rate will be claimable as collateral surplus.
*/
} else if ((_ICR >= MCR) && (_ICR < _TCR) && (singleLiquidation.entireTroveDebt <= _RUBCInStabPool)) {
_movePendingTroveRewardsToActivePool(_activePool, _defaultPool, vars.pendingDebtReward, vars.pendingCollReward);
assert(_RUBCInStabPool != 0);
_removeStake(_borrower);
singleLiquidation = _getCappedOffsetVals(singleLiquidation.entireTroveDebt, singleLiquidation.entireTroveColl, _price);
_closeTrove(_borrower, Status.closedByLiquidation);
if (singleLiquidation.collSurplus > 0) {
collSurplusPool.accountSurplus(_borrower, singleLiquidation.collSurplus);
}
emit TroveLiquidated(_borrower, singleLiquidation.entireTroveDebt, singleLiquidation.collToSendToSP, TroveManagerOperation.liquidateInRecoveryMode);
emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.liquidateInRecoveryMode);
} else { // if (_ICR >= MCR && ( _ICR >= _TCR || singleLiquidation.entireTroveDebt > _RUBCInStabPool))
LiquidationValues memory zeroVals;
return zeroVals;
}
return singleLiquidation;
}
/* In a full liquidation, returns the values for a trove's coll and debt to be offset, and coll and debt to be
* redistributed to active troves.
*/
function _getOffsetAndRedistributionVals
(
uint _debt,
uint _coll,
uint _RUBCInStabPool
)
internal
pure
returns (uint debtToOffset, uint collToSendToSP, uint debtToRedistribute, uint collToRedistribute)
{
if (_RUBCInStabPool > 0) {
/*
* Offset as much debt & collateral as possible against the Stability Pool, and redistribute the remainder
* between all active troves.
*
* If the trove's debt is larger than the deposited RUBC in the Stability Pool:
*
* - Offset an amount of the trove's debt equal to the RUBC in the Stability Pool
* - Send a fraction of the trove's collateral to the Stability Pool, equal to the fraction of its offset debt
*
*/
debtToOffset = LiquityMath._min(_debt, _RUBCInStabPool);
collToSendToSP = _coll.mul(debtToOffset).div(_debt);
debtToRedistribute = _debt.sub(debtToOffset);
collToRedistribute = _coll.sub(collToSendToSP);
} else {
debtToOffset = 0;
collToSendToSP = 0;
debtToRedistribute = _debt;
collToRedistribute = _coll;
}
}
/*
* Get its offset coll/debt and ETH gas comp, and close the trove.
*/
function _getCappedOffsetVals
(
uint _entireTroveDebt,
uint _entireTroveColl,
uint _price
)
internal
pure
returns (LiquidationValues memory singleLiquidation)
{
singleLiquidation.entireTroveDebt = _entireTroveDebt;
singleLiquidation.entireTroveColl = _entireTroveColl;
uint cappedCollPortion = _entireTroveDebt.mul(MCR).div(_price);
singleLiquidation.collGasCompensation = _getCollGasCompensation(cappedCollPortion);
singleLiquidation.RUBCGasCompensation = RUBC_GAS_COMPENSATION;
singleLiquidation.debtToOffset = _entireTroveDebt;
singleLiquidation.collToSendToSP = cappedCollPortion.sub(singleLiquidation.collGasCompensation);
singleLiquidation.collSurplus = _entireTroveColl.sub(cappedCollPortion);
singleLiquidation.debtToRedistribute = 0;
singleLiquidation.collToRedistribute = 0;
}
/*
* Liquidate a sequence of troves. Closes a maximum number of n under-collateralized Troves,
* starting from the one with the lowest collateral ratio in the system, and moving upwards
*/
function liquidateTroves(uint _n) external override {
ContractsCache memory contractsCache = ContractsCache(
activePool,
defaultPool,
IRUBC(address(0)),
IRBSTStaking(address(0)),
sortedTroves,
ICollSurplusPool(address(0)),
address(0)
);
IStabilityPool stabilityPoolCached = stabilityPool;
LocalVariables_OuterLiquidationFunction memory vars;
LiquidationTotals memory totals;
vars.price = priceFeed.fetchPrice();
vars.RUBCInStabPool = stabilityPoolCached.getTotalRUBCDeposits();
vars.recoveryModeAtStart = _checkRecoveryMode(vars.price);
// Perform the appropriate liquidation sequence - tally the values, and obtain their totals
if (vars.recoveryModeAtStart) {
totals = _getTotalsFromLiquidateTrovesSequence_RecoveryMode(contractsCache, vars.price, vars.RUBCInStabPool, _n);
} else { // if !vars.recoveryModeAtStart
totals = _getTotalsFromLiquidateTrovesSequence_NormalMode(contractsCache.activePool, contractsCache.defaultPool, vars.price, vars.RUBCInStabPool, _n);
}
require(totals.totalDebtInSequence > 0, "TroveManager: nothing to liquidate");
// Move liquidated ETH and RUBC to the appropriate pools
stabilityPoolCached.offset(totals.totalDebtToOffset, totals.totalCollToSendToSP);
_redistributeDebtAndColl(contractsCache.activePool, contractsCache.defaultPool, totals.totalDebtToRedistribute, totals.totalCollToRedistribute);
if (totals.totalCollSurplus > 0) {
contractsCache.activePool.sendETH(address(collSurplusPool), totals.totalCollSurplus);
}
// Update system snapshots
_updateSystemSnapshots_excludeCollRemainder(contractsCache.activePool, totals.totalCollGasCompensation);
vars.liquidatedDebt = totals.totalDebtInSequence;
vars.liquidatedColl = totals.totalCollInSequence.sub(totals.totalCollGasCompensation).sub(totals.totalCollSurplus);
emit Liquidation(vars.liquidatedDebt, vars.liquidatedColl, totals.totalCollGasCompensation, totals.totalRUBCGasCompensation);
// Send gas compensation to caller
_sendGasCompensation(contractsCache.activePool, msg.sender, totals.totalRUBCGasCompensation, totals.totalCollGasCompensation);
}
/*
* This function is used when the liquidateTroves sequence starts during Recovery Mode. However, it
* handle the case where the system *leaves* Recovery Mode, part way through the liquidation sequence
*/
function _getTotalsFromLiquidateTrovesSequence_RecoveryMode
(
ContractsCache memory _contractsCache,
uint _price,
uint _RUBCInStabPool,
uint _n
)
internal
returns(LiquidationTotals memory totals)
{
LocalVariables_LiquidationSequence memory vars;
LiquidationValues memory singleLiquidation;
vars.remainingRUBCInStabPool = _RUBCInStabPool;
vars.backToNormalMode = false;
vars.entireSystemDebt = getEntireSystemDebt();
vars.entireSystemColl = getEntireSystemColl();
vars.user = _contractsCache.sortedTroves.getLast();
address firstUser = _contractsCache.sortedTroves.getFirst();
for (vars.i = 0; vars.i < _n && vars.user != firstUser; vars.i++) {
// we need to cache it, because current user is likely going to be deleted
address nextUser = _contractsCache.sortedTroves.getPrev(vars.user);
vars.ICR = getCurrentICR(vars.user, _price);
if (!vars.backToNormalMode) {
// Break the loop if ICR is greater than MCR and Stability Pool is empty
if (vars.ICR >= MCR && vars.remainingRUBCInStabPool == 0) { break; }
uint TCR = LiquityMath._computeCR(vars.entireSystemColl, vars.entireSystemDebt, _price);
singleLiquidation = _liquidateRecoveryMode(_contractsCache.activePool, _contractsCache.defaultPool, vars.user, vars.ICR, vars.remainingRUBCInStabPool, TCR, _price);
// Update aggregate trackers
vars.remainingRUBCInStabPool = vars.remainingRUBCInStabPool.sub(singleLiquidation.debtToOffset);
vars.entireSystemDebt = vars.entireSystemDebt.sub(singleLiquidation.debtToOffset);
vars.entireSystemColl = vars.entireSystemColl.
sub(singleLiquidation.collToSendToSP).
sub(singleLiquidation.collGasCompensation).
sub(singleLiquidation.collSurplus);
// Add liquidation values to their respective running totals
totals = _addLiquidationValuesToTotals(totals, singleLiquidation);
vars.backToNormalMode = !_checkPotentialRecoveryMode(vars.entireSystemColl, vars.entireSystemDebt, _price);
}
else if (vars.backToNormalMode && vars.ICR < MCR) {
singleLiquidation = _liquidateNormalMode(_contractsCache.activePool, _contractsCache.defaultPool, vars.user, vars.remainingRUBCInStabPool);
vars.remainingRUBCInStabPool = vars.remainingRUBCInStabPool.sub(singleLiquidation.debtToOffset);
// Add liquidation values to their respective running totals
totals = _addLiquidationValuesToTotals(totals, singleLiquidation);
} else break; // break if the loop reaches a Trove with ICR >= MCR
vars.user = nextUser;
}
}
function _getTotalsFromLiquidateTrovesSequence_NormalMode
(
IActivePool _activePool,
IDefaultPool _defaultPool,
uint _price,
uint _RUBCInStabPool,
uint _n
)
internal
returns(LiquidationTotals memory totals)
{
LocalVariables_LiquidationSequence memory vars;
LiquidationValues memory singleLiquidation;
ISortedTroves sortedTrovesCached = sortedTroves;
vars.remainingRUBCInStabPool = _RUBCInStabPool;
for (vars.i = 0; vars.i < _n; vars.i++) {
vars.user = sortedTrovesCached.getLast();
vars.ICR = getCurrentICR(vars.user, _price);
if (vars.ICR < MCR) {
singleLiquidation = _liquidateNormalMode(_activePool, _defaultPool, vars.user, vars.remainingRUBCInStabPool);
vars.remainingRUBCInStabPool = vars.remainingRUBCInStabPool.sub(singleLiquidation.debtToOffset);
// Add liquidation values to their respective running totals
totals = _addLiquidationValuesToTotals(totals, singleLiquidation);
} else break; // break if the loop reaches a Trove with ICR >= MCR
}
}
/*
* Attempt to liquidate a custom list of troves provided by the caller.
*/
function batchLiquidateTroves(address[] memory _troveArray) public override {
require(_troveArray.length != 0, "TroveManager: Calldata address array must not be empty");
IActivePool activePoolCached = activePool;
IDefaultPool defaultPoolCached = defaultPool;
IStabilityPool stabilityPoolCached = stabilityPool;
LocalVariables_OuterLiquidationFunction memory vars;
LiquidationTotals memory totals;
vars.price = priceFeed.fetchPrice();
vars.RUBCInStabPool = stabilityPoolCached.getTotalRUBCDeposits();
vars.recoveryModeAtStart = _checkRecoveryMode(vars.price);
// Perform the appropriate liquidation sequence - tally values and obtain their totals.
if (vars.recoveryModeAtStart) {
totals = _getTotalFromBatchLiquidate_RecoveryMode(activePoolCached, defaultPoolCached, vars.price, vars.RUBCInStabPool, _troveArray);
} else { // if !vars.recoveryModeAtStart
totals = _getTotalsFromBatchLiquidate_NormalMode(activePoolCached, defaultPoolCached, vars.price, vars.RUBCInStabPool, _troveArray);
}
require(totals.totalDebtInSequence > 0, "TroveManager: nothing to liquidate");
// Move liquidated ETH and RUBC to the appropriate pools
stabilityPoolCached.offset(totals.totalDebtToOffset, totals.totalCollToSendToSP);
_redistributeDebtAndColl(activePoolCached, defaultPoolCached, totals.totalDebtToRedistribute, totals.totalCollToRedistribute);
if (totals.totalCollSurplus > 0) {
activePoolCached.sendETH(address(collSurplusPool), totals.totalCollSurplus);
}
// Update system snapshots
_updateSystemSnapshots_excludeCollRemainder(activePoolCached, totals.totalCollGasCompensation);
vars.liquidatedDebt = totals.totalDebtInSequence;
vars.liquidatedColl = totals.totalCollInSequence.sub(totals.totalCollGasCompensation).sub(totals.totalCollSurplus);
emit Liquidation(vars.liquidatedDebt, vars.liquidatedColl, totals.totalCollGasCompensation, totals.totalRUBCGasCompensation);
// Send gas compensation to caller
_sendGasCompensation(activePoolCached, msg.sender, totals.totalRUBCGasCompensation, totals.totalCollGasCompensation);
}
/*
* This function is used when the batch liquidation sequence starts during Recovery Mode. However, it
* handle the case where the system *leaves* Recovery Mode, part way through the liquidation sequence
*/
function _getTotalFromBatchLiquidate_RecoveryMode
(
IActivePool _activePool,
IDefaultPool _defaultPool,
uint _price,
uint _RUBCInStabPool,
address[] memory _troveArray
)
internal
returns(LiquidationTotals memory totals)
{
LocalVariables_LiquidationSequence memory vars;
LiquidationValues memory singleLiquidation;
vars.remainingRUBCInStabPool = _RUBCInStabPool;
vars.backToNormalMode = false;
vars.entireSystemDebt = getEntireSystemDebt();
vars.entireSystemColl = getEntireSystemColl();
for (vars.i = 0; vars.i < _troveArray.length; vars.i++) {
vars.user = _troveArray[vars.i];
// Skip non-active troves
if (Troves[vars.user].status != Status.active) { continue; }
vars.ICR = getCurrentICR(vars.user, _price);
if (!vars.backToNormalMode) {
// Skip this trove if ICR is greater than MCR and Stability Pool is empty
if (vars.ICR >= MCR && vars.remainingRUBCInStabPool == 0) { continue; }
uint TCR = LiquityMath._computeCR(vars.entireSystemColl, vars.entireSystemDebt, _price);
singleLiquidation = _liquidateRecoveryMode(_activePool, _defaultPool, vars.user, vars.ICR, vars.remainingRUBCInStabPool, TCR, _price);
// Update aggregate trackers
vars.remainingRUBCInStabPool = vars.remainingRUBCInStabPool.sub(singleLiquidation.debtToOffset);
vars.entireSystemDebt = vars.entireSystemDebt.sub(singleLiquidation.debtToOffset);
vars.entireSystemColl = vars.entireSystemColl.
sub(singleLiquidation.collToSendToSP).
sub(singleLiquidation.collGasCompensation).
sub(singleLiquidation.collSurplus);
// Add liquidation values to their respective running totals
totals = _addLiquidationValuesToTotals(totals, singleLiquidation);
vars.backToNormalMode = !_checkPotentialRecoveryMode(vars.entireSystemColl, vars.entireSystemDebt, _price);
}
else if (vars.backToNormalMode && vars.ICR < MCR) {
singleLiquidation = _liquidateNormalMode(_activePool, _defaultPool, vars.user, vars.remainingRUBCInStabPool);
vars.remainingRUBCInStabPool = vars.remainingRUBCInStabPool.sub(singleLiquidation.debtToOffset);
// Add liquidation values to their respective running totals
totals = _addLiquidationValuesToTotals(totals, singleLiquidation);
} else continue; // In Normal Mode skip troves with ICR >= MCR
}
}
function _getTotalsFromBatchLiquidate_NormalMode
(
IActivePool _activePool,
IDefaultPool _defaultPool,
uint _price,
uint _RUBCInStabPool,
address[] memory _troveArray
)
internal
returns(LiquidationTotals memory totals)
{
LocalVariables_LiquidationSequence memory vars;
LiquidationValues memory singleLiquidation;
vars.remainingRUBCInStabPool = _RUBCInStabPool;
for (vars.i = 0; vars.i < _troveArray.length; vars.i++) {
vars.user = _troveArray[vars.i];
vars.ICR = getCurrentICR(vars.user, _price);
if (vars.ICR < MCR) {
singleLiquidation = _liquidateNormalMode(_activePool, _defaultPool, vars.user, vars.remainingRUBCInStabPool);
vars.remainingRUBCInStabPool = vars.remainingRUBCInStabPool.sub(singleLiquidation.debtToOffset);
// Add liquidation values to their respective running totals
totals = _addLiquidationValuesToTotals(totals, singleLiquidation);
}
}
}
// --- Liquidation helper functions ---
function _addLiquidationValuesToTotals(LiquidationTotals memory oldTotals, LiquidationValues memory singleLiquidation)
internal pure returns(LiquidationTotals memory newTotals) {
// Tally all the values with their respective running totals
newTotals.totalCollGasCompensation = oldTotals.totalCollGasCompensation.add(singleLiquidation.collGasCompensation);
newTotals.totalRUBCGasCompensation = oldTotals.totalRUBCGasCompensation.add(singleLiquidation.RUBCGasCompensation);
newTotals.totalDebtInSequence = oldTotals.totalDebtInSequence.add(singleLiquidation.entireTroveDebt);
newTotals.totalCollInSequence = oldTotals.totalCollInSequence.add(singleLiquidation.entireTroveColl);
newTotals.totalDebtToOffset = oldTotals.totalDebtToOffset.add(singleLiquidation.debtToOffset);
newTotals.totalCollToSendToSP = oldTotals.totalCollToSendToSP.add(singleLiquidation.collToSendToSP);
newTotals.totalDebtToRedistribute = oldTotals.totalDebtToRedistribute.add(singleLiquidation.debtToRedistribute);
newTotals.totalCollToRedistribute = oldTotals.totalCollToRedistribute.add(singleLiquidation.collToRedistribute);
newTotals.totalCollSurplus = oldTotals.totalCollSurplus.add(singleLiquidation.collSurplus);
return newTotals;
}
function _sendGasCompensation(IActivePool _activePool, address _liquidator, uint _RUBC, uint _ETH) internal {
if (_RUBC > 0) {
rubc.returnFromPool(gasPoolAddress, _liquidator, _RUBC);
}
if (_ETH > 0) {
_activePool.sendETH(_liquidator, _ETH);
}
}
// Move a Trove's pending debt and collateral rewards from distributions, from the Default Pool to the Active Pool
function _movePendingTroveRewardsToActivePool(IActivePool _activePool, IDefaultPool _defaultPool, uint _RUBC, uint _ETH) internal {
_defaultPool.decreaseRUBCDebt(_RUBC);
_activePool.increaseRUBCDebt(_RUBC);
_defaultPool.sendETHToActivePool(_ETH);
}
// --- Redemption functions ---
// Redeem as much collateral as possible from _borrower's Trove in exchange for RUBC up to _maxRUBCamount
function _redeemCollateralFromTrove(
ContractsCache memory _contractsCache,
address _borrower,
uint _maxRUBCamount,
uint _price,
address _upperPartialRedemptionHint,
address _lowerPartialRedemptionHint,
uint _partialRedemptionHintNICR
)
internal returns (SingleRedemptionValues memory singleRedemption)
{
// Determine the remaining amount (lot) to be redeemed, capped by the entire debt of the Trove minus the liquidation reserve
singleRedemption.RUBCLot = LiquityMath._min(_maxRUBCamount, Troves[_borrower].debt.sub(RUBC_GAS_COMPENSATION));
// Get the ETHLot of equivalent value in USD
singleRedemption.ETHLot = singleRedemption.RUBCLot.mul(DECIMAL_PRECISION).div(_price);
// Decrease the debt and collateral of the current Trove according to the RUBC lot and corresponding ETH to send
uint newDebt = (Troves[_borrower].debt).sub(singleRedemption.RUBCLot);
uint newColl = (Troves[_borrower].coll).sub(singleRedemption.ETHLot);
if (newDebt == RUBC_GAS_COMPENSATION) {
// No debt left in the Trove (except for the liquidation reserve), therefore the trove gets closed
_removeStake(_borrower);
_closeTrove(_borrower, Status.closedByRedemption);
_redeemCloseTrove(_contractsCache, _borrower, RUBC_GAS_COMPENSATION, newColl);
emit TroveUpdated(_borrower, 0, 0, 0, TroveManagerOperation.redeemCollateral);
} else {
uint newNICR = LiquityMath._computeNominalCR(newColl, newDebt);
/*
* If the provided hint is out of date, we bail since trying to reinsert without a good hint will almost
* certainly result in running out of gas.
*
* If the resultant net debt of the partial is less than the minimum, net debt we bail.
*/
if (newNICR != _partialRedemptionHintNICR || _getNetDebt(newDebt) < MIN_NET_DEBT) {
singleRedemption.cancelledPartial = true;
return singleRedemption;
}
_contractsCache.sortedTroves.reInsert(_borrower, newNICR, _upperPartialRedemptionHint, _lowerPartialRedemptionHint);
Troves[_borrower].debt = newDebt;
Troves[_borrower].coll = newColl;
_updateStakeAndTotalStakes(_borrower);
emit TroveUpdated(
_borrower,
newDebt, newColl,
Troves[_borrower].stake,
TroveManagerOperation.redeemCollateral
);
}
return singleRedemption;
}
/*
* Called when a full redemption occurs, and closes the trove.
* The redeemer swaps (debt - liquidation reserve) RUBC for (debt - liquidation reserve) worth of ETH, so the RUBC liquidation reserve left corresponds to the remaining debt.
* In order to close the trove, the RUBC liquidation reserve is burned, and the corresponding debt is removed from the active pool.
* The debt recorded on the trove's struct is zero'd elswhere, in _closeTrove.
* Any surplus ETH left in the trove, is sent to the Coll surplus pool, and can be later claimed by the borrower.
*/
function _redeemCloseTrove(ContractsCache memory _contractsCache, address _borrower, uint _RUBC, uint _ETH) internal {
_contractsCache.rubc.burn(gasPoolAddress, _RUBC);
// Update Active Pool RUBC, and send ETH to account
_contractsCache.activePool.decreaseRUBCDebt(_RUBC);
// send ETH from Active Pool to CollSurplus Pool
_contractsCache.collSurplusPool.accountSurplus(_borrower, _ETH);
_contractsCache.activePool.sendETH(address(_contractsCache.collSurplusPool), _ETH);
}
function _isValidFirstRedemptionHint(ISortedTroves _sortedTroves, address _firstRedemptionHint, uint _price) internal view returns (bool) {
if (_firstRedemptionHint == address(0) ||
!_sortedTroves.contains(_firstRedemptionHint) ||
getCurrentICR(_firstRedemptionHint, _price) < MCR
) {
return false;
}
address nextTrove = _sortedTroves.getNext(_firstRedemptionHint);
return nextTrove == address(0) || getCurrentICR(nextTrove, _price) < MCR;
}
/* Send _RUBCamount RUBC to the system and redeem the corresponding amount of collateral from as many Troves as are needed to fill the redemption
* request. Applies pending rewards to a Trove before reducing its debt and coll.
*
* Note that if _amount is very large, this function can run out of gas, specially if traversed troves are small. This can be easily avoided by
* splitting the total _amount in appropriate chunks and calling the function multiple times.
*
* Param `_maxIterations` can also be provided, so the loop through Troves is capped (if it’s zero, it will be ignored).This makes it easier to
* avoid OOG for the frontend, as only knowing approximately the average cost of an iteration is enough, without needing to know the “topology”
* of the trove list. It also avoids the need to set the cap in stone in the contract, nor doing gas calculations, as both gas price and opcode
* costs can vary.
*
* All Troves that are redeemed from -- with the likely exception of the last one -- will end up with no debt left, therefore they will be closed.
* If the last Trove does have some remaining debt, it has a finite ICR, and the reinsertion could be anywhere in the list, therefore it requires a hint.
* A frontend should use getRedemptionHints() to calculate what the ICR of this Trove will be after redemption, and pass a hint for its position
* in the sortedTroves list along with the ICR value that the hint was found for.
*
* If another transaction modifies the list between calling getRedemptionHints() and passing the hints to redeemCollateral(), it
* is very likely that the last (partially) redeemed Trove would end up with a different ICR than what the hint is for. In this case the
* redemption will stop after the last completely redeemed Trove and the sender will keep the remaining RUBC amount, which they can attempt
* to redeem later.
*/
function redeemCollateral(
uint _RUBCamount,
address _firstRedemptionHint,
address _upperPartialRedemptionHint,
address _lowerPartialRedemptionHint,
uint _partialRedemptionHintNICR,
uint _maxIterations,
uint _maxFeePercentage
)
external
override
{
ContractsCache memory contractsCache = ContractsCache(
activePool,
defaultPool,
rubc,
rbstStaking,
sortedTroves,
collSurplusPool,
gasPoolAddress
);
RedemptionTotals memory totals;
_requireValidMaxFeePercentage(_maxFeePercentage);
_requireAfterBootstrapPeriod();
{
//new scope to prevent stack too deep
IPriceFeed _priceFeed = priceFeed;
totals.price = _priceFeed.fetchPrice();
require(_priceFeed.fetchRUBPriceFeedUpdateTimestamp() < block.timestamp + REDEMPTION_WINDOW_SECONDS);
}
_requireTCRoverMCR(totals.price);
_requireAmountGreaterThanZero(_RUBCamount);
_requireRUBCBalanceCoversRedemption(contractsCache.rubc, msg.sender, _RUBCamount);
totals.totalRUBCSupplyAtStart = getEntireSystemDebt();
// Confirm redeemer's balance is less than total RUBC supply
assert(contractsCache.rubc.balanceOf(msg.sender) <= totals.totalRUBCSupplyAtStart);
totals.remainingRUBC = _RUBCamount;
address currentBorrower;
if (_isValidFirstRedemptionHint(contractsCache.sortedTroves, _firstRedemptionHint, totals.price)) {
currentBorrower = _firstRedemptionHint;
} else {
currentBorrower = contractsCache.sortedTroves.getLast();
// Find the first trove with ICR >= MCR
while (currentBorrower != address(0) && getCurrentICR(currentBorrower, totals.price) < MCR) {
currentBorrower = contractsCache.sortedTroves.getPrev(currentBorrower);
}
}
// Loop through the Troves starting from the one with lowest collateral ratio until _amount of RUBC is exchanged for collateral
if (_maxIterations == 0) { _maxIterations = uint(-1); }
while (currentBorrower != address(0) && totals.remainingRUBC > 0 && _maxIterations > 0) {
_maxIterations--;
// Save the address of the Trove preceding the current one, before potentially modifying the list
address nextUserToCheck = contractsCache.sortedTroves.getPrev(currentBorrower);
_applyPendingRewards(contractsCache.activePool, contractsCache.defaultPool, currentBorrower);
SingleRedemptionValues memory singleRedemption = _redeemCollateralFromTrove(
contractsCache,
currentBorrower,
totals.remainingRUBC,
totals.price,
_upperPartialRedemptionHint,
_lowerPartialRedemptionHint,
_partialRedemptionHintNICR
);
if (singleRedemption.cancelledPartial) break; // Partial redemption was cancelled (out-of-date hint, or new net debt < minimum), therefore we could not redeem from the last Trove
totals.totalRUBCToRedeem = totals.totalRUBCToRedeem.add(singleRedemption.RUBCLot);
totals.totalETHDrawn = totals.totalETHDrawn.add(singleRedemption.ETHLot);
totals.remainingRUBC = totals.remainingRUBC.sub(singleRedemption.RUBCLot);
currentBorrower = nextUserToCheck;
}
require(totals.totalETHDrawn > 0, "TroveManager: Unable to redeem any amount");
// Decay the baseRate due to time passed, and then increase it according to the size of this redemption.
// Use the saved total RUBC supply value, from before it was reduced by the redemption.
_updateBaseRateFromRedemption(totals.totalETHDrawn, totals.price, totals.totalRUBCSupplyAtStart);
// Calculate the ETH fee
totals.ETHFee = _getRedemptionFee(totals.totalETHDrawn);
_requireUserAcceptsFee(totals.ETHFee, totals.totalETHDrawn, _maxFeePercentage);
// Send the ETH fee to the RBST staking contract
contractsCache.activePool.sendETH(address(contractsCache.rbstStaking), totals.ETHFee);
contractsCache.rbstStaking.increaseF_ETH(totals.ETHFee);
totals.ETHToSendToRedeemer = totals.totalETHDrawn.sub(totals.ETHFee);
emit Redemption(_RUBCamount, totals.totalRUBCToRedeem, totals.totalETHDrawn, totals.ETHFee);
// Burn the total RUBC that is cancelled with debt, and send the redeemed ETH to msg.sender
contractsCache.rubc.burn(msg.sender, totals.totalRUBCToRedeem);
// Update Active Pool RUBC, and send ETH to account
contractsCache.activePool.decreaseRUBCDebt(totals.totalRUBCToRedeem);
contractsCache.activePool.sendETH(msg.sender, totals.ETHToSendToRedeemer);
}
// --- Helper functions ---
// Return the nominal collateral ratio (ICR) of a given Trove, without the price. Takes a trove's pending coll and debt rewards from redistributions into account.
function getNominalICR(address _borrower) public view override returns (uint) {
(uint currentETH, uint currentRUBCDebt) = _getCurrentTroveAmounts(_borrower);
uint NICR = LiquityMath._computeNominalCR(currentETH, currentRUBCDebt);
return NICR;
}
// Return the current collateral ratio (ICR) of a given Trove. Takes a trove's pending coll and debt rewards from redistributions into account.
function getCurrentICR(address _borrower, uint _price) public view override returns (uint) {
(uint currentETH, uint currentRUBCDebt) = _getCurrentTroveAmounts(_borrower);
uint ICR = LiquityMath._computeCR(currentETH, currentRUBCDebt, _price);
return ICR;
}
function _getCurrentTroveAmounts(address _borrower) internal view returns (uint, uint) {
uint pendingETHReward = getPendingETHReward(_borrower);
uint pendingRUBCDebtReward = getPendingRUBCDebtReward(_borrower);
uint currentETH = Troves[_borrower].coll.add(pendingETHReward);
uint currentRUBCDebt = Troves[_borrower].debt.add(pendingRUBCDebtReward);
return (currentETH, currentRUBCDebt);
}
function applyPendingRewards(address _borrower) external override {
_requireCallerIsBorrowerOperations();
return _applyPendingRewards(activePool, defaultPool, _borrower);
}
// Add the borrowers's coll and debt rewards earned from redistributions, to their Trove
function _applyPendingRewards(IActivePool _activePool, IDefaultPool _defaultPool, address _borrower) internal {
if (hasPendingRewards(_borrower)) {
_requireTroveIsActive(_borrower);
// Compute pending rewards
uint pendingETHReward = getPendingETHReward(_borrower);
uint pendingRUBCDebtReward = getPendingRUBCDebtReward(_borrower);
// Apply pending rewards to trove's state
Troves[_borrower].coll = Troves[_borrower].coll.add(pendingETHReward);
Troves[_borrower].debt = Troves[_borrower].debt.add(pendingRUBCDebtReward);
_updateTroveRewardSnapshots(_borrower);
// Transfer from DefaultPool to ActivePool
_movePendingTroveRewardsToActivePool(_activePool, _defaultPool, pendingRUBCDebtReward, pendingETHReward);
emit TroveUpdated(
_borrower,
Troves[_borrower].debt,
Troves[_borrower].coll,
Troves[_borrower].stake,
TroveManagerOperation.applyPendingRewards
);
}
}
// Update borrower's snapshots of L_ETH and L_RUBCDebt to reflect the current values
function updateTroveRewardSnapshots(address _borrower) external override {
_requireCallerIsBorrowerOperations();
return _updateTroveRewardSnapshots(_borrower);
}
function _updateTroveRewardSnapshots(address _borrower) internal {
rewardSnapshots[_borrower].ETH = L_ETH;
rewardSnapshots[_borrower].RUBCDebt = L_RUBCDebt;
emit TroveSnapshotsUpdated(L_ETH, L_RUBCDebt);
}
// Get the borrower's pending accumulated ETH reward, earned by their stake
function getPendingETHReward(address _borrower) public view override returns (uint) {
uint snapshotETH = rewardSnapshots[_borrower].ETH;
uint rewardPerUnitStaked = L_ETH.sub(snapshotETH);
if ( rewardPerUnitStaked == 0 || Troves[_borrower].status != Status.active) { return 0; }
uint stake = Troves[_borrower].stake;
uint pendingETHReward = stake.mul(rewardPerUnitStaked).div(DECIMAL_PRECISION);
return pendingETHReward;
}
// Get the borrower's pending accumulated RUBC reward, earned by their stake
function getPendingRUBCDebtReward(address _borrower) public view override returns (uint) {
uint snapshotRUBCDebt = rewardSnapshots[_borrower].RUBCDebt;
uint rewardPerUnitStaked = L_RUBCDebt.sub(snapshotRUBCDebt);
if ( rewardPerUnitStaked == 0 || Troves[_borrower].status != Status.active) { return 0; }
uint stake = Troves[_borrower].stake;
uint pendingRUBCDebtReward = stake.mul(rewardPerUnitStaked).div(DECIMAL_PRECISION);
return pendingRUBCDebtReward;
}
function hasPendingRewards(address _borrower) public view override returns (bool) {
/*
* A Trove has pending rewards if its snapshot is less than the current rewards per-unit-staked sum:
* this indicates that rewards have occured since the snapshot was made, and the user therefore has
* pending rewards
*/
if (Troves[_borrower].status != Status.active) {return false;}
return (rewardSnapshots[_borrower].ETH < L_ETH);
}
// Return the Troves entire debt and coll, including pending rewards from redistributions.
function getEntireDebtAndColl(
address _borrower
)
public
view
override
returns (uint debt, uint coll, uint pendingRUBCDebtReward, uint pendingETHReward)
{
debt = Troves[_borrower].debt;
coll = Troves[_borrower].coll;
pendingRUBCDebtReward = getPendingRUBCDebtReward(_borrower);
pendingETHReward = getPendingETHReward(_borrower);
debt = debt.add(pendingRUBCDebtReward);
coll = coll.add(pendingETHReward);
}
function removeStake(address _borrower) external override {
_requireCallerIsBorrowerOperations();
return _removeStake(_borrower);
}
// Remove borrower's stake from the totalStakes sum, and set their stake to 0
function _removeStake(address _borrower) internal {
uint stake = Troves[_borrower].stake;
totalStakes = totalStakes.sub(stake);
Troves[_borrower].stake = 0;
}
function updateStakeAndTotalStakes(address _borrower) external override returns (uint) {
_requireCallerIsBorrowerOperations();
return _updateStakeAndTotalStakes(_borrower);
}
// Update borrower's stake based on their latest collateral value
function _updateStakeAndTotalStakes(address _borrower) internal returns (uint) {
uint newStake = _computeNewStake(Troves[_borrower].coll);
uint oldStake = Troves[_borrower].stake;
Troves[_borrower].stake = newStake;
totalStakes = totalStakes.sub(oldStake).add(newStake);
emit TotalStakesUpdated(totalStakes);
return newStake;
}
// Calculate a new stake based on the snapshots of the totalStakes and totalCollateral taken at the last liquidation
function _computeNewStake(uint _coll) internal view returns (uint) {
uint stake;
if (totalCollateralSnapshot == 0) {
stake = _coll;
} else {
/*
* The following assert() holds true because:
* - The system always contains >= 1 trove
* - When we close or liquidate a trove, we redistribute the pending rewards, so if all troves were closed/liquidated,
* rewards would’ve been emptied and totalCollateralSnapshot would be zero too.
*/
assert(totalStakesSnapshot > 0);
stake = _coll.mul(totalStakesSnapshot).div(totalCollateralSnapshot);
}
return stake;
}
function _redistributeDebtAndColl(IActivePool _activePool, IDefaultPool _defaultPool, uint _debt, uint _coll) internal {
if (_debt == 0) { return; }
/*
* Add distributed coll and debt rewards-per-unit-staked to the running totals. Division uses a "feedback"
* error correction, to keep the cumulative error low in the running totals L_ETH and L_RUBCDebt:
*
* 1) Form numerators which compensate for the floor division errors that occurred the last time this
* function was called.
* 2) Calculate "per-unit-staked" ratios.
* 3) Multiply each ratio back by its denominator, to reveal the current floor division error.
* 4) Store these errors for use in the next correction when this function is called.
* 5) Note: static analysis tools complain about this "division before multiplication", however, it is intended.
*/
uint ETHNumerator = _coll.mul(DECIMAL_PRECISION).add(lastETHError_Redistribution);
uint RUBCDebtNumerator = _debt.mul(DECIMAL_PRECISION).add(lastRUBCDebtError_Redistribution);
// Get the per-unit-staked terms
uint ETHRewardPerUnitStaked = ETHNumerator.div(totalStakes);
uint RUBCDebtRewardPerUnitStaked = RUBCDebtNumerator.div(totalStakes);
lastETHError_Redistribution = ETHNumerator.sub(ETHRewardPerUnitStaked.mul(totalStakes));
lastRUBCDebtError_Redistribution = RUBCDebtNumerator.sub(RUBCDebtRewardPerUnitStaked.mul(totalStakes));
// Add per-unit-staked terms to the running totals
L_ETH = L_ETH.add(ETHRewardPerUnitStaked);
L_RUBCDebt = L_RUBCDebt.add(RUBCDebtRewardPerUnitStaked);
emit LTermsUpdated(L_ETH, L_RUBCDebt);
// Transfer coll and debt from ActivePool to DefaultPool
_activePool.decreaseRUBCDebt(_debt);
_defaultPool.increaseRUBCDebt(_debt);
_activePool.sendETH(address(_defaultPool), _coll);
}
function closeTrove(address _borrower) external override {
_requireCallerIsBorrowerOperations();
return _closeTrove(_borrower, Status.closedByOwner);
}
function _closeTrove(address _borrower, Status closedStatus) internal {
assert(closedStatus != Status.nonExistent && closedStatus != Status.active);
uint TroveOwnersArrayLength = TroveOwners.length;
_requireMoreThanOneTroveInSystem(TroveOwnersArrayLength);
Troves[_borrower].status = closedStatus;
Troves[_borrower].coll = 0;
Troves[_borrower].debt = 0;
rewardSnapshots[_borrower].ETH = 0;
rewardSnapshots[_borrower].RUBCDebt = 0;
_removeTroveOwner(_borrower, TroveOwnersArrayLength);
sortedTroves.remove(_borrower);
}
/*
* Updates snapshots of system total stakes and total collateral, excluding a given collateral remainder from the calculation.
* Used in a liquidation sequence.
*
* The calculation excludes a portion of collateral that is in the ActivePool:
*
* the total ETH gas compensation from the liquidation sequence
*
* The ETH as compensation must be excluded as it is always sent out at the very end of the liquidation sequence.
*/
function _updateSystemSnapshots_excludeCollRemainder(IActivePool _activePool, uint _collRemainder) internal {
totalStakesSnapshot = totalStakes;
uint activeColl = _activePool.getETH();
uint liquidatedColl = defaultPool.getETH();
totalCollateralSnapshot = activeColl.sub(_collRemainder).add(liquidatedColl);
emit SystemSnapshotsUpdated(totalStakesSnapshot, totalCollateralSnapshot);
}
// Push the owner's address to the Trove owners list, and record the corresponding array index on the Trove struct
function addTroveOwnerToArray(address _borrower) external override returns (uint index) {
_requireCallerIsBorrowerOperations();
return _addTroveOwnerToArray(_borrower);
}
function _addTroveOwnerToArray(address _borrower) internal returns (uint128 index) {
/* Max array size is 2**128 - 1, i.e. ~3e30 troves. No risk of overflow, since troves have minimum RUBC
debt of liquidation reserve plus MIN_NET_DEBT. 3e30 RUBC dwarfs the value of all wealth in the world ( which is < 1e15 USD). */
// Push the Troveowner to the array
TroveOwners.push(_borrower);
// Record the index of the new Troveowner on their Trove struct
index = uint128(TroveOwners.length.sub(1));
Troves[_borrower].arrayIndex = index;
return index;
}
/*
* Remove a Trove owner from the TroveOwners array, not preserving array order. Removing owner 'B' does the following:
* [A B C D E] => [A E C D], and updates E's Trove struct to point to its new array index.
*/
function _removeTroveOwner(address _borrower, uint TroveOwnersArrayLength) internal {
Status troveStatus = Troves[_borrower].status;
// It’s set in caller function `_closeTrove`
assert(troveStatus != Status.nonExistent && troveStatus != Status.active);
uint128 index = Troves[_borrower].arrayIndex;
uint length = TroveOwnersArrayLength;
uint idxLast = length.sub(1);
assert(index <= idxLast);
address addressToMove = TroveOwners[idxLast];
TroveOwners[index] = addressToMove;
Troves[addressToMove].arrayIndex = index;
emit TroveIndexUpdated(addressToMove, index);
TroveOwners.pop();
}
// --- Recovery Mode and TCR functions ---
function getTCR(uint _price) external view override returns (uint) {
return _getTCR(_price);
}
function checkRecoveryMode(uint _price) external view override returns (bool) {
return _checkRecoveryMode(_price);
}
// Check whether or not the system *would be* in Recovery Mode, given an ETH:USD price, and the entire system coll and debt.
function _checkPotentialRecoveryMode(
uint _entireSystemColl,
uint _entireSystemDebt,
uint _price
)
internal
pure
returns (bool)
{
uint TCR = LiquityMath._computeCR(_entireSystemColl, _entireSystemDebt, _price);
return TCR < CCR;
}
// --- Redemption fee functions ---
/*
* This function has two impacts on the baseRate state variable:
* 1) decays the baseRate based on time passed since last redemption or RUBC borrowing operation.
* then,
* 2) increases the baseRate based on the amount redeemed, as a proportion of total supply
*/
function _updateBaseRateFromRedemption(uint _ETHDrawn, uint _price, uint _totalRUBCSupply) internal returns (uint) {
uint decayedBaseRate = _calcDecayedBaseRate();
/* Convert the drawn ETH back to RUBC at face value rate (1 RUBC:1 USD), in order to get
* the fraction of total supply that was redeemed at face value. */
uint redeemedRUBCFraction = _ETHDrawn.mul(_price).div(_totalRUBCSupply);
uint newBaseRate = decayedBaseRate.add(redeemedRUBCFraction.div(BETA));
newBaseRate = LiquityMath._min(newBaseRate, DECIMAL_PRECISION); // cap baseRate at a maximum of 100%
//assert(newBaseRate <= DECIMAL_PRECISION); // This is already enforced in the line above
assert(newBaseRate > 0); // Base rate is always non-zero after redemption
// Update the baseRate state variable
baseRate = newBaseRate;
emit BaseRateUpdated(newBaseRate);
_updateLastFeeOpTime();
return newBaseRate;
}
function getRedemptionRate() public view override returns (uint) {
return _calcRedemptionRate(baseRate);
}
function getRedemptionRateWithDecay() public view override returns (uint) {
return _calcRedemptionRate(_calcDecayedBaseRate());
}
function _calcRedemptionRate(uint _baseRate) internal pure returns (uint) {
return LiquityMath._min(
REDEMPTION_FEE_FLOOR.add(_baseRate),
DECIMAL_PRECISION // cap at a maximum of 100%
);
}
function _getRedemptionFee(uint _ETHDrawn) internal view returns (uint) {
return _calcRedemptionFee(getRedemptionRate(), _ETHDrawn);
}
function getRedemptionFeeWithDecay(uint _ETHDrawn) external view override returns (uint) {
return _calcRedemptionFee(getRedemptionRateWithDecay(), _ETHDrawn);
}
function _calcRedemptionFee(uint _redemptionRate, uint _ETHDrawn) internal pure returns (uint) {
uint redemptionFee = _redemptionRate.mul(_ETHDrawn).div(DECIMAL_PRECISION);
require(redemptionFee < _ETHDrawn, "TroveManager: Fee would eat up all returned collateral");
return redemptionFee;
}
// --- Borrowing fee functions ---
function getBorrowingRate() public view override returns (uint) {
return _calcBorrowingRate(baseRate);
}
function getBorrowingRateWithDecay() public view override returns (uint) {
return _calcBorrowingRate(_calcDecayedBaseRate());
}
function _calcBorrowingRate(uint _baseRate) internal pure returns (uint) {
return LiquityMath._min(
BORROWING_FEE_FLOOR.add(_baseRate),
MAX_BORROWING_FEE
);
}
function getBorrowingFee(uint _RUBCDebt) external view override returns (uint) {
return _calcBorrowingFee(getBorrowingRate(), _RUBCDebt);
}
function getBorrowingFeeWithDecay(uint _RUBCDebt) external view override returns (uint) {
return _calcBorrowingFee(getBorrowingRateWithDecay(), _RUBCDebt);
}
function _calcBorrowingFee(uint _borrowingRate, uint _RUBCDebt) internal pure returns (uint) {
return _borrowingRate.mul(_RUBCDebt).div(DECIMAL_PRECISION);
}
// Updates the baseRate state variable based on time elapsed since the last redemption or RUBC borrowing operation.
function decayBaseRateFromBorrowing() external override {
_requireCallerIsBorrowerOperations();
uint decayedBaseRate = _calcDecayedBaseRate();
assert(decayedBaseRate <= DECIMAL_PRECISION); // The baseRate can decay to 0
baseRate = decayedBaseRate;
emit BaseRateUpdated(decayedBaseRate);
_updateLastFeeOpTime();
}
// --- Internal fee functions ---
// Update the last fee operation time only if time passed >= decay interval. This prevents base rate griefing.
function _updateLastFeeOpTime() internal {
uint timePassed = block.timestamp.sub(lastFeeOperationTime);
if (timePassed >= SECONDS_IN_ONE_MINUTE) {
lastFeeOperationTime = block.timestamp;
emit LastFeeOpTimeUpdated(block.timestamp);
}
}
function _calcDecayedBaseRate() internal view returns (uint) {
uint minutesPassed = _minutesPassedSinceLastFeeOp();
uint decayFactor = LiquityMath._decPow(MINUTE_DECAY_FACTOR, minutesPassed);
return baseRate.mul(decayFactor).div(DECIMAL_PRECISION);
}
function _minutesPassedSinceLastFeeOp() internal view returns (uint) {
return (block.timestamp.sub(lastFeeOperationTime)).div(SECONDS_IN_ONE_MINUTE);
}
// --- 'require' wrapper functions ---
function _requireCallerIsBorrowerOperations() internal view {
require(msg.sender == borrowerOperationsAddress, "TroveManager: Caller is not the BorrowerOperations contract");
}
function _requireTroveIsActive(address _borrower) internal view {
require(Troves[_borrower].status == Status.active, "TroveManager: Trove does not exist or is closed");
}
function _requireRUBCBalanceCoversRedemption(IRUBC _rubc, address _redeemer, uint _amount) internal view {
require(_rubc.balanceOf(_redeemer) >= _amount, "TroveManager: Requested redemption amount must be <= user's RUBC token balance");
}
function _requireMoreThanOneTroveInSystem(uint TroveOwnersArrayLength) internal view {
require (TroveOwnersArrayLength > 1 && sortedTroves.getSize() > 1, "TroveManager: Only one trove in the system");
}
function _requireAmountGreaterThanZero(uint _amount) internal pure {
require(_amount > 0, "TroveManager: Amount must be greater than zero");
}
function _requireTCRoverMCR(uint _price) internal view {
require(_getTCR(_price) >= MCR, "TroveManager: Cannot redeem when TCR < MCR");
}
function _requireAfterBootstrapPeriod() internal view {
uint systemDeploymentTime = rbst.getDeploymentStartTime();
require(block.timestamp >= systemDeploymentTime.add(BOOTSTRAP_PERIOD), "TroveManager: Redemptions are not allowed during bootstrap phase");
}
function _requireValidMaxFeePercentage(uint _maxFeePercentage) internal pure {
require(_maxFeePercentage >= REDEMPTION_FEE_FLOOR && _maxFeePercentage <= DECIMAL_PRECISION,
"Max fee percentage must be between 0.5% and 100%");
}
// --- Trove property getters ---
function getTroveStatus(address _borrower) external view override returns (uint) {
return uint(Troves[_borrower].status);
}
function getTroveStake(address _borrower) external view override returns (uint) {
return Troves[_borrower].stake;
}
function getTroveDebt(address _borrower) external view override returns (uint) {
return Troves[_borrower].debt;
}
function getTroveColl(address _borrower) external view override returns (uint) {
return Troves[_borrower].coll;
}
// --- Trove property setters, called by BorrowerOperations ---
function setTroveStatus(address _borrower, uint _num) external override {
_requireCallerIsBorrowerOperations();
Troves[_borrower].status = Status(_num);
}
function increaseTroveColl(address _borrower, uint _collIncrease) external override returns (uint) {
_requireCallerIsBorrowerOperations();
uint newColl = Troves[_borrower].coll.add(_collIncrease);
Troves[_borrower].coll = newColl;
return newColl;
}
function decreaseTroveColl(address _borrower, uint _collDecrease) external override returns (uint) {
_requireCallerIsBorrowerOperations();
uint newColl = Troves[_borrower].coll.sub(_collDecrease);
Troves[_borrower].coll = newColl;
return newColl;
}
function increaseTroveDebt(address _borrower, uint _debtIncrease) external override returns (uint) {
_requireCallerIsBorrowerOperations();
uint newDebt = Troves[_borrower].debt.add(_debtIncrease);
Troves[_borrower].debt = newDebt;
return newDebt;
}
function decreaseTroveDebt(address _borrower, uint _debtDecrease) external override returns (uint) {
_requireCallerIsBorrowerOperations();
uint newDebt = Troves[_borrower].debt.sub(_debtDecrease);
Troves[_borrower].debt = newDebt;
return newDebt;
}
}
/*
* A sorted doubly linked list with nodes sorted in descending order.
*
* Nodes map to active Troves in the system - the ID property is the address of a Trove owner.
* Nodes are ordered according to their current nominal individual collateral ratio (NICR),
* which is like the ICR but without the price, i.e., just collateral / debt.
*
* The list optionally accepts insert position hints.
*
* NICRs are computed dynamically at runtime, and not stored on the Node. This is because NICRs of active Troves
* change dynamically as liquidation events occur.
*
* The list relies on the fact that liquidation events preserve ordering: a liquidation decreases the NICRs of all active Troves,
* but maintains their order. A node inserted based on current NICR will maintain the correct position,
* relative to it's peers, as rewards accumulate, as long as it's raw collateral and debt have not changed.
* Thus, Nodes remain sorted by current NICR.
*
* Nodes need only be re-inserted upon a Trove operation - when the owner adds or removes collateral or debt
* to their position.
*
* The list is a modification of the following audited SortedDoublyLinkedList:
* https://github.com/livepeer/protocol/blob/master/contracts/libraries/SortedDoublyLL.sol
*
*
* Changes made in the Liquity implementation:
*
* - Keys have been removed from nodes
*
* - Ordering checks for insertion are performed by comparing an NICR argument to the current NICR, calculated at runtime.
* The list relies on the property that ordering by ICR is maintained as the ETH:USD price varies.
*
* - Public functions with parameters have been made internal to save gas, and given an external wrapper function for external access
*/
contract SortedTroves is Ownable, CheckContract, ISortedTroves {
using SafeMath for uint256;
string constant public NAME = "SortedTroves";
event TroveManagerAddressChanged(address _troveManagerAddress);
event BorrowerOperationsAddressChanged(address _borrowerOperationsAddress);
event NodeAdded(address _id, uint _NICR);
event NodeRemoved(address _id);
address public borrowerOperationsAddress;
ITroveManager public troveManager;
// Information for a node in the list
struct Node {
bool exists;
address nextId; // Id of next node (smaller NICR) in the list
address prevId; // Id of previous node (larger NICR) in the list
}
// Information for the list
struct Data {
address head; // Head of the list. Also the node in the list with the largest NICR
address tail; // Tail of the list. Also the node in the list with the smallest NICR
uint256 maxSize; // Maximum size of the list
uint256 size; // Current size of the list
mapping (address => Node) nodes; // Track the corresponding ids for each node in the list
}
Data public data;
// --- Dependency setters ---
function setParams(uint256 _size, address _troveManagerAddress, address _borrowerOperationsAddress) external override onlyOwner {
require(_size > 0, "SortedTroves: Size can’t be zero");
checkContract(_troveManagerAddress);
checkContract(_borrowerOperationsAddress);
data.maxSize = _size;
troveManager = ITroveManager(_troveManagerAddress);
borrowerOperationsAddress = _borrowerOperationsAddress;
emit TroveManagerAddressChanged(_troveManagerAddress);
emit BorrowerOperationsAddressChanged(_borrowerOperationsAddress);
_renounceOwnership();
}
/*
* @dev Add a node to the list
* @param _id Node's id
* @param _NICR Node's NICR
* @param _prevId Id of previous node for the insert position
* @param _nextId Id of next node for the insert position
*/
function insert (address _id, uint256 _NICR, address _prevId, address _nextId) external override {
ITroveManager troveManagerCached = troveManager;
_requireCallerIsBOorTroveM(troveManagerCached);
_insert(troveManagerCached, _id, _NICR, _prevId, _nextId);
}
function _insert(ITroveManager _troveManager, address _id, uint256 _NICR, address _prevId, address _nextId) internal {
// List must not be full
require(!isFull(), "SortedTroves: List is full");
// List must not already contain node
require(!contains(_id), "SortedTroves: List already contains the node");
// Node id must not be null
require(_id != address(0), "SortedTroves: Id cannot be zero");
// NICR must be non-zero
require(_NICR > 0, "SortedTroves: NICR must be positive");
address prevId = _prevId;
address nextId = _nextId;
if (!_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
// Sender's hint was not a valid insert position
// Use sender's hint to find a valid insert position
(prevId, nextId) = _findInsertPosition(_troveManager, _NICR, prevId, nextId);
}
data.nodes[_id].exists = true;
if (prevId == address(0) && nextId == address(0)) {
// Insert as head and tail
data.head = _id;
data.tail = _id;
} else if (prevId == address(0)) {
// Insert before `prevId` as the head
data.nodes[_id].nextId = data.head;
data.nodes[data.head].prevId = _id;
data.head = _id;
} else if (nextId == address(0)) {
// Insert after `nextId` as the tail
data.nodes[_id].prevId = data.tail;
data.nodes[data.tail].nextId = _id;
data.tail = _id;
} else {
// Insert at insert position between `prevId` and `nextId`
data.nodes[_id].nextId = nextId;
data.nodes[_id].prevId = prevId;
data.nodes[prevId].nextId = _id;
data.nodes[nextId].prevId = _id;
}
data.size = data.size.add(1);
emit NodeAdded(_id, _NICR);
}
function remove(address _id) external override {
_requireCallerIsTroveManager();
_remove(_id);
}
/*
* @dev Remove a node from the list
* @param _id Node's id
*/
function _remove(address _id) internal {
// List must contain the node
require(contains(_id), "SortedTroves: List does not contain the id");
if (data.size > 1) {
// List contains more than a single node
if (_id == data.head) {
// The removed node is the head
// Set head to next node
data.head = data.nodes[_id].nextId;
// Set prev pointer of new head to null
data.nodes[data.head].prevId = address(0);
} else if (_id == data.tail) {
// The removed node is the tail
// Set tail to previous node
data.tail = data.nodes[_id].prevId;
// Set next pointer of new tail to null
data.nodes[data.tail].nextId = address(0);
} else {
// The removed node is neither the head nor the tail
// Set next pointer of previous node to the next node
data.nodes[data.nodes[_id].prevId].nextId = data.nodes[_id].nextId;
// Set prev pointer of next node to the previous node
data.nodes[data.nodes[_id].nextId].prevId = data.nodes[_id].prevId;
}
} else {
// List contains a single node
// Set the head and tail to null
data.head = address(0);
data.tail = address(0);
}
delete data.nodes[_id];
data.size = data.size.sub(1);
NodeRemoved(_id);
}
/*
* @dev Re-insert the node at a new position, based on its new NICR
* @param _id Node's id
* @param _newNICR Node's new NICR
* @param _prevId Id of previous node for the new insert position
* @param _nextId Id of next node for the new insert position
*/
function reInsert(address _id, uint256 _newNICR, address _prevId, address _nextId) external override {
ITroveManager troveManagerCached = troveManager;
_requireCallerIsBOorTroveM(troveManagerCached);
// List must contain the node
require(contains(_id), "SortedTroves: List does not contain the id");
// NICR must be non-zero
require(_newNICR > 0, "SortedTroves: NICR must be positive");
// Remove node from the list
_remove(_id);
_insert(troveManagerCached, _id, _newNICR, _prevId, _nextId);
}
/*
* @dev Checks if the list contains a node
*/
function contains(address _id) public view override returns (bool) {
return data.nodes[_id].exists;
}
/*
* @dev Checks if the list is full
*/
function isFull() public view override returns (bool) {
return data.size == data.maxSize;
}
/*
* @dev Checks if the list is empty
*/
function isEmpty() public view override returns (bool) {
return data.size == 0;
}
/*
* @dev Returns the current size of the list
*/
function getSize() external view override returns (uint256) {
return data.size;
}
/*
* @dev Returns the maximum size of the list
*/
function getMaxSize() external view override returns (uint256) {
return data.maxSize;
}
/*
* @dev Returns the first node in the list (node with the largest NICR)
*/
function getFirst() external view override returns (address) {
return data.head;
}
/*
* @dev Returns the last node in the list (node with the smallest NICR)
*/
function getLast() external view override returns (address) {
return data.tail;
}
/*
* @dev Returns the next node (with a smaller NICR) in the list for a given node
* @param _id Node's id
*/
function getNext(address _id) external view override returns (address) {
return data.nodes[_id].nextId;
}
/*
* @dev Returns the previous node (with a larger NICR) in the list for a given node
* @param _id Node's id
*/
function getPrev(address _id) external view override returns (address) {
return data.nodes[_id].prevId;
}
/*
* @dev Check if a pair of nodes is a valid insertion point for a new node with the given NICR
* @param _NICR Node's NICR
* @param _prevId Id of previous node for the insert position
* @param _nextId Id of next node for the insert position
*/
function validInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view override returns (bool) {
return _validInsertPosition(troveManager, _NICR, _prevId, _nextId);
}
function _validInsertPosition(ITroveManager _troveManager, uint256 _NICR, address _prevId, address _nextId) internal view returns (bool) {
if (_prevId == address(0) && _nextId == address(0)) {
// `(null, null)` is a valid insert position if the list is empty
return isEmpty();
} else if (_prevId == address(0)) {
// `(null, _nextId)` is a valid insert position if `_nextId` is the head of the list
return data.head == _nextId && _NICR >= _troveManager.getNominalICR(_nextId);
} else if (_nextId == address(0)) {
// `(_prevId, null)` is a valid insert position if `_prevId` is the tail of the list
return data.tail == _prevId && _NICR <= _troveManager.getNominalICR(_prevId);
} else {
// `(_prevId, _nextId)` is a valid insert position if they are adjacent nodes and `_NICR` falls between the two nodes' NICRs
return data.nodes[_prevId].nextId == _nextId &&
_troveManager.getNominalICR(_prevId) >= _NICR &&
_NICR >= _troveManager.getNominalICR(_nextId);
}
}
/*
* @dev Descend the list (larger NICRs to smaller NICRs) to find a valid insert position
* @param _troveManager TroveManager contract, passed in as param to save SLOAD’s
* @param _NICR Node's NICR
* @param _startId Id of node to start descending the list from
*/
function _descendList(ITroveManager _troveManager, uint256 _NICR, address _startId) internal view returns (address, address) {
// If `_startId` is the head, check if the insert position is before the head
if (data.head == _startId && _NICR >= _troveManager.getNominalICR(_startId)) {
return (address(0), _startId);
}
address prevId = _startId;
address nextId = data.nodes[prevId].nextId;
// Descend the list until we reach the end or until we find a valid insert position
while (prevId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
prevId = data.nodes[prevId].nextId;
nextId = data.nodes[prevId].nextId;
}
return (prevId, nextId);
}
/*
* @dev Ascend the list (smaller NICRs to larger NICRs) to find a valid insert position
* @param _troveManager TroveManager contract, passed in as param to save SLOAD’s
* @param _NICR Node's NICR
* @param _startId Id of node to start ascending the list from
*/
function _ascendList(ITroveManager _troveManager, uint256 _NICR, address _startId) internal view returns (address, address) {
// If `_startId` is the tail, check if the insert position is after the tail
if (data.tail == _startId && _NICR <= _troveManager.getNominalICR(_startId)) {
return (_startId, address(0));
}
address nextId = _startId;
address prevId = data.nodes[nextId].prevId;
// Ascend the list until we reach the end or until we find a valid insertion point
while (nextId != address(0) && !_validInsertPosition(_troveManager, _NICR, prevId, nextId)) {
nextId = data.nodes[nextId].prevId;
prevId = data.nodes[nextId].prevId;
}
return (prevId, nextId);
}
/*
* @dev Find the insert position for a new node with the given NICR
* @param _NICR Node's NICR
* @param _prevId Id of previous node for the insert position
* @param _nextId Id of next node for the insert position
*/
function findInsertPosition(uint256 _NICR, address _prevId, address _nextId) external view override returns (address, address) {
return _findInsertPosition(troveManager, _NICR, _prevId, _nextId);
}
function _findInsertPosition(ITroveManager _troveManager, uint256 _NICR, address _prevId, address _nextId) internal view returns (address, address) {
address prevId = _prevId;
address nextId = _nextId;
if (prevId != address(0)) {
if (!contains(prevId) || _NICR > _troveManager.getNominalICR(prevId)) {
// `prevId` does not exist anymore or now has a smaller NICR than the given NICR
prevId = address(0);
}
}
if (nextId != address(0)) {
if (!contains(nextId) || _NICR < _troveManager.getNominalICR(nextId)) {
// `nextId` does not exist anymore or now has a larger NICR than the given NICR
nextId = address(0);
}
}
if (prevId == address(0) && nextId == address(0)) {
// No hint - descend list starting from head
return _descendList(_troveManager, _NICR, data.head);
} else if (prevId == address(0)) {
// No `prevId` for hint - ascend list starting from `nextId`
return _ascendList(_troveManager, _NICR, nextId);
} else if (nextId == address(0)) {
// No `nextId` for hint - descend list starting from `prevId`
return _descendList(_troveManager, _NICR, prevId);
} else {
// Descend list starting from `prevId`
return _descendList(_troveManager, _NICR, prevId);
}
}
// --- 'require' functions ---
function _requireCallerIsTroveManager() internal view {
require(msg.sender == address(troveManager), "SortedTroves: Caller is not the TroveManager");
}
function _requireCallerIsBOorTroveM(ITroveManager _troveManager) internal view {
require(msg.sender == borrowerOperationsAddress || msg.sender == address(_troveManager),
"SortedTroves: Caller is neither BO nor TroveM");
}
}
/* Helper contract for grabbing Trove data for the front end. Not part of the core Liquity system. */
contract MultiTroveGetter {
struct CombinedTroveData {
address owner;
uint debt;
uint coll;
uint stake;
uint snapshotETH;
uint snapshotRUBCDebt;
}
TroveManager public troveManager; // XXX Troves missing from ITroveManager?
ISortedTroves public sortedTroves;
constructor(TroveManager _troveManager, ISortedTroves _sortedTroves) public {
troveManager = _troveManager;
sortedTroves = _sortedTroves;
}
function getMultipleSortedTroves(int _startIdx, uint _count)
external view returns (CombinedTroveData[] memory _troves)
{
uint startIdx;
bool descend;
if (_startIdx >= 0) {
startIdx = uint(_startIdx);
descend = true;
} else {
startIdx = uint(-(_startIdx + 1));
descend = false;
}
uint sortedTrovesSize = sortedTroves.getSize();
if (startIdx >= sortedTrovesSize) {
_troves = new CombinedTroveData[](0);
} else {
uint maxCount = sortedTrovesSize - startIdx;
if (_count > maxCount) {
_count = maxCount;
}
if (descend) {
_troves = _getMultipleSortedTrovesFromHead(startIdx, _count);
} else {
_troves = _getMultipleSortedTrovesFromTail(startIdx, _count);
}
}
}
function _getMultipleSortedTrovesFromHead(uint _startIdx, uint _count)
internal view returns (CombinedTroveData[] memory _troves)
{
address currentTroveowner = sortedTroves.getFirst();
for (uint idx = 0; idx < _startIdx; ++idx) {
currentTroveowner = sortedTroves.getNext(currentTroveowner);
}
_troves = new CombinedTroveData[](_count);
for (uint idx = 0; idx < _count; ++idx) {
_troves[idx].owner = currentTroveowner;
(
_troves[idx].debt,
_troves[idx].coll,
_troves[idx].stake,
/* status */,
/* arrayIndex */
) = troveManager.Troves(currentTroveowner);
(
_troves[idx].snapshotETH,
_troves[idx].snapshotRUBCDebt
) = troveManager.rewardSnapshots(currentTroveowner);
currentTroveowner = sortedTroves.getNext(currentTroveowner);
}
}
function _getMultipleSortedTrovesFromTail(uint _startIdx, uint _count)
internal view returns (CombinedTroveData[] memory _troves)
{
address currentTroveowner = sortedTroves.getLast();
for (uint idx = 0; idx < _startIdx; ++idx) {
currentTroveowner = sortedTroves.getPrev(currentTroveowner);
}
_troves = new CombinedTroveData[](_count);
for (uint idx = 0; idx < _count; ++idx) {
_troves[idx].owner = currentTroveowner;
(
_troves[idx].debt,
_troves[idx].coll,
_troves[idx].stake,
/* status */,
/* arrayIndex */
) = troveManager.Troves(currentTroveowner);
(
_troves[idx].snapshotETH,
_troves[idx].snapshotRUBCDebt
) = troveManager.rewardSnapshots(currentTroveowner);
currentTroveowner = sortedTroves.getPrev(currentTroveowner);
}
}
}
|
--- Events --- --- Functions ---
|
interface IStabilityPool {
event StabilityPoolETHBalanceUpdated(uint _newBalance);
event StabilityPoolRUBCBalanceUpdated(uint _newBalance);
event BorrowerOperationsAddressChanged(address _newBorrowerOperationsAddress);
event TroveManagerAddressChanged(address _newTroveManagerAddress);
event ActivePoolAddressChanged(address _newActivePoolAddress);
event DefaultPoolAddressChanged(address _newDefaultPoolAddress);
event RUBCAddressChanged(address _newRUBCAddress);
event SortedTrovesAddressChanged(address _newSortedTrovesAddress);
event PriceFeedAddressChanged(address _newPriceFeedAddress);
event CommunityIssuanceAddressChanged(address _newCommunityIssuanceAddress);
event P_Updated(uint _P);
event S_Updated(uint _S, uint128 _epoch, uint128 _scale);
event G_Updated(uint _G, uint128 _epoch, uint128 _scale);
event EpochUpdated(uint128 _currentEpoch);
event ScaleUpdated(uint128 _currentScale);
event FrontEndRegistered(address indexed _frontEnd, uint _kickbackRate);
event FrontEndTagSet(address indexed _depositor, address indexed _frontEnd);
event DepositSnapshotUpdated(address indexed _depositor, uint _P, uint _S, uint _G);
event FrontEndSnapshotUpdated(address indexed _frontEnd, uint _P, uint _G);
event UserDepositChanged(address indexed _depositor, uint _newDeposit);
event FrontEndStakeChanged(address indexed _frontEnd, uint _newFrontEndStake, address _depositor);
event ETHGainWithdrawn(address indexed _depositor, uint _ETH, uint _RUBCLoss);
event RBSTPaidToDepositor(address indexed _depositor, uint _RBST);
event RBSTPaidToFrontEnd(address indexed _frontEnd, uint _RBST);
event EtherSent(address _to, uint _amount);
function setAddresses(
address _borrowerOperationsAddress,
address _troveManagerAddress,
address _activePoolAddress,
address _rubcAddress,
address _sortedTrovesAddress,
address _priceFeedAddress,
address _communityIssuanceAddress
) external;
function provideToSP(uint _amount, address _frontEndTag) external;
function withdrawFromSP(uint _amount) external;
function withdrawETHGainToTrove(address _upperHint, address _lowerHint) external;
function registerFrontEnd(uint _kickbackRate) external;
function offset(uint _debt, uint _coll) external;
function getETH() external view returns (uint);
function getTotalRUBCDeposits() external view returns (uint);
function getDepositorETHGain(address _depositor) external view returns (uint);
function getDepositorRBSTGain(address _depositor) external view returns (uint);
function getFrontEndRBSTGain(address _frontEnd) external view returns (uint);
function getCompoundedRUBCDeposit(address _depositor) external view returns (uint);
function getCompoundedFrontEndStake(address _frontEnd) external view returns (uint);
}
| 7,747,159
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.