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/43113/0x8FC9b799E32C645569d750380a0C9E80e8b39B41/sources/project_/contracts/HomiumDeal.sol | at contract creation set h value | function setHValue() public {
hValue = hStore.currentHValue();
}
| 7,168,491 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.11;
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);
}
}
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 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());
}
}
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
interface 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);
}
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);
}
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);
}
}
}
}
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
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 {}
}
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;
}
}
}
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);
}
}
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
contract WarriorMfers is ERC721, Ownable, Pausable, ReentrancyGuard {
using Strings for uint256;
using SafeMath for uint256;
using SafeMath for uint8;
uint256 public constant MAX_SUPPLY = 6500;
uint256 public constant MAX_MINT_PER_TX = 20;
uint256 public constant MAX_MINT_PER_PRESALE = 1;
uint256 public MINT_PRICE_PUBLIC = 0.015 ether;
uint256 public PRE_MINT_PRICE = 0.0 ether;
uint256 public totalSupply = 0;
bool public saleStarted = false;
bool public preSaleStarted = false;
bool public revealed = false;
string public baseExtension = ".json";
string public baseURI;
string public notRevealedURI;
// Merkle Tree Root
bytes32 private _merkleRoot;
mapping(address => uint256) balanceOfAddress;
constructor(
string memory _initBaseURI,
string memory _initNotRevealedURI
) ERC721("Warrior Mfers", "WM") {
setBaseURI(_initBaseURI);
setNotRevealedURI(_initNotRevealedURI);
}
function _baseURI() internal view virtual override returns (string memory) {
return baseURI;
}
function airdrop(uint256 _count, address _account) external onlyOwner {
require(totalSupply + _count <= MAX_SUPPLY, "max airdrop limit exceeded");
for (uint256 i = 1; i <= _count; i++) {
_safeMint(_account, totalSupply + i);
}
totalSupply += _count;
}
function _leaf(address account) private pure returns (bytes32) {
return keccak256(abi.encodePacked(account));
}
function verifyWhitelist(bytes32 leaf, bytes32[] memory proof)
private
view
returns (bool)
{
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash < proofElement) {
computedHash = keccak256(
abi.encodePacked(computedHash, proofElement)
);
} else {
computedHash = keccak256(
abi.encodePacked(proofElement, computedHash)
);
}
}
return computedHash == _merkleRoot;
}
function whitelistMint(uint256 _count, bytes32[] memory _proof)
external
payable
{
require(preSaleStarted, "premint not started yet");
require(!paused(), "contract paused");
require(
verifyWhitelist(_leaf(msg.sender), _proof) == true,
"invalid address"
);
require(
_count > 0 && balanceOfAddress[msg.sender] + _count <= MAX_MINT_PER_PRESALE,
"max mint per trx exceeded"
);
require(totalSupply + _count <= MAX_SUPPLY, "max supply reached");
if (msg.sender != owner()) {
require(msg.value >= PRE_MINT_PRICE * _count);
}
for (uint256 i = 1; i <= _count; i++) {
_safeMint(msg.sender, totalSupply + i);
}
totalSupply += _count;
balanceOfAddress[msg.sender] += _count;
}
function mint(uint256 _count) public payable {
require(saleStarted, "public mint not started yet");
require(!paused(), "contract paused");
require(
_count > 0 && _count <= MAX_MINT_PER_TX,
"max mint per trx exceeded"
);
require(totalSupply + _count <= MAX_SUPPLY, "max supply reached");
if (msg.sender != owner()) {
require(msg.value >= MINT_PRICE_PUBLIC * _count);
}
for (uint256 i = 1; i <= _count; i++) {
_safeMint(msg.sender, totalSupply + i);
}
totalSupply += _count;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(tokenId), "token not exist");
string memory currentBaseURI = _baseURI();
if (revealed == false) {
return notRevealedURI;
}
else {
currentBaseURI = _baseURI();
return
bytes(currentBaseURI).length > 0
? string(
abi.encodePacked(
currentBaseURI,
tokenId.toString(),
baseExtension
)
)
: "";
}
}
function withdraw() external onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
function setSaleStarted(bool _hasStarted) external onlyOwner {
require(saleStarted != _hasStarted, "main sale start already");
saleStarted = _hasStarted;
}
function setPreSaleStarted(bool _hasStarted) external onlyOwner {
require(preSaleStarted != _hasStarted, "presale started already");
preSaleStarted = _hasStarted;
}
function setMintPrice(uint256 newMintPrice) public onlyOwner {
MINT_PRICE_PUBLIC = newMintPrice;
}
function setPreMintPrice(uint256 newMintPrice) public onlyOwner {
PRE_MINT_PRICE = newMintPrice;
}
function setBaseURI(string memory _newBaseURI) public onlyOwner {
baseURI = _newBaseURI;
}
function reveal() public onlyOwner {
revealed = true;
}
function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner {
notRevealedURI = _notRevealedURI;
}
function setMerkleRoot(bytes32 _merkleRootValue)
external
onlyOwner
returns (bytes32)
{
_merkleRoot = _merkleRootValue;
return _merkleRoot;
}
function pause() external onlyOwner {
require(!paused(), "contract already paused");
_pause();
}
function unpause() external onlyOwner {
require(paused(), "contract already unpaused");
_unpause();
}
} | 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, 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");
}
| 175,430 |
// SPDX-License-Identifier: ART
pragma solidity ^0.8.0;
//
// ████████╗██╗ ██╗███████╗
// ╚══██╔══╝██║ ██║██╔════╝
// ██║ ███████║█████╗
// ██║ ██╔══██║██╔══╝
// ██║ ██║ ██║███████╗
// ╚═╝ ╚═╝ ╚═╝╚══════╝
//
// ██████╗ ██████╗ ███╗ ██╗████████╗██████╗ █████╗ ██████╗████████╗
// ██╔════╝██╔═══██╗████╗ ██║╚══██╔══╝██╔══██╗██╔══██╗██╔════╝╚══██╔══╝
// ██║ ██║ ██║██╔██╗ ██║ ██║ ██████╔╝███████║██║ ██║
// ██║ ██║ ██║██║╚██╗██║ ██║ ██╔══██╗██╔══██║██║ ██║
// ╚██████╗╚██████╔╝██║ ╚████║ ██║ ██║ ██║██║ ██║╚██████╗ ██║
// ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚═╝ ╚═╝╚═╝ ╚═╝ ╚═════╝ ╚═╝
// __
// |_ \/ |_ o o __ _| |/ | _ o _ __
// |_) / |__ | \_/ | | |(_| |\ | (/_ | \_/(/_| |
//
//
// @title The Contract by Eivind Kleiven
// @author Eivind Kleiven
// The Contract is a Non-Fungible Token contract.
// The contract itself is the creation and token holder is it's owner.
// The contract is a homage to Fade by Pak: 0x62F5418d9Edbc13b7E07A15e095D7228cD9386c5
contract TheContract {
using Strings for uint256;
using Strings for uint8;
// Artist
string public artist = "Eivind Kleiven";
// 10% Royalty is paid to this account on every sale
address payable private _artistAccount = payable(0x85c0C90946E3e959f537D01CEBd93f97C9B5E372);
// Token name
string public name = "The Contract";
// Token symbol
string public symbol = "THECONTRACT";
// Contract and token owner
address public owner;
// Approved address
address private _tokenApproval;
// Operator approvals
mapping (address => bool) private _operatorApprovals;
// Supported interfaces
mapping(bytes4 => bool) private _supportedInterfaces;
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
bytes4 private constant _INTERFACE_ID_ERC721_RECEIVED = 0x150b7a02;
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a;
// @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);
// SVG parts used to build SVG and url escaped svg strings
string[57] private _svgParts;
/**
* @dev Initializes the contract by setting message sender as token/contract `owner`.
*/
constructor () {
owner = msg.sender;
_supportedInterfaces[_INTERFACE_ID_ERC165] = true;
_supportedInterfaces[_INTERFACE_ID_ERC721] = true;
_supportedInterfaces[_INTERFACE_ID_ERC721_METADATA] = true;
_supportedInterfaces[_INTERFACE_ID_ERC721_ENUMERABLE] = true;
_supportedInterfaces[_INTERFACE_ID_ERC2981] = true;
_svgParts[0]="<svg xmlns='http://www.w3.org/2000/svg' id='TheContractByEivindKleiven' viewBox='0 0 ";
_svgParts[1]="%3Csvg%20xmlns%3D%27http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%27%20id%3D%27TheContractByEivindKleiven%27%20viewBox%3D%270%200%20";
_svgParts[2]="%253Csvg%2520xmlns%253D%2527http%253A%252F%252Fwww.w3.org%252F2000%252Fsvg%2527%2520id%253D%2527TheContractByEivindKleiven%2527%2520viewBox%253D%25270%25200%2520";
_svgParts[3]=" ";
_svgParts[4]="%20";
_svgParts[5]="%2520";
_svgParts[6]="' shape-rendering='crispEdges' style='background-color: #ffffff;'><clipPath id='TheContractClipPath'><rect x='0' y='0' width='100' height='100'/></clipPath><defs><filter id='TheContractFilter'><feColorMatrix type='matrix' values=' 1.430 -0.639 -1.920 0.000 0.934 -0.852 -0.604 0.328 0.000 0.934 0.876 -3.300 1.290 0.000 0.934 0.000 0.000 0.000 1.000 0.000'/><feColorMatrix type='hueRotate' values='0'><animate attributeName='values' values='0; 360; 0' calcMode='spline' keySplines='0.4 0 0.2 1; 0.4 0 0.2 1' dur='30s' repeatCount='indefinite' /></feColorMatrix></filter>";
_svgParts[7]="%27%20shape-rendering%3D%27crispEdges%27%20style%3D%27background-color%3A%20%23ffffff%3B%27>%3CclipPath%20id%3D%27TheContractClipPath%27>%3Crect%20x%3D%270%27%20y%3D%270%27%20width%3D%27100%27%20height%3D%27100%27%2F>%3C%2FclipPath>%3Cdefs>%3Cfilter%20id%3D%27TheContractFilter%27>%3CfeColorMatrix%20type%3D%27matrix%27%20values%3D%27%201.430%20-0.639%20-1.920%200.000%200.934%20-0.852%20-0.604%200.328%200.000%200.934%200.876%20-3.300%201.290%200.000%200.934%200.000%200.000%200.000%201.000%200.000%27%2F>%3CfeColorMatrix%20type%3D%27hueRotate%27%20values%3D%270%27>%3Canimate%20attributeName%3D%27values%27%20values%3D%270%3B%20360%3B%200%27%20calcMode%3D%27spline%27%20keySplines%3D%270.4%200%200.2%201%3B%200.4%200%200.2%201%27%20dur%3D%2730s%27%20repeatCount%3D%27indefinite%27%20%2F>%3C%2FfeColorMatrix>%3C%2Ffilter>";
_svgParts[8]="%2527%2520shape-rendering%253D%2527crispEdges%2527%2520style%253D%2527background-color%253A%2520%2523ffffff%253B%2527>%253CclipPath%2520id%253D%2527TheContractClipPath%2527>%253Crect%2520x%253D%25270%2527%2520y%253D%25270%2527%2520width%253D%2527100%2527%2520height%253D%2527100%2527%252F>%253C%252FclipPath>%253Cdefs>%253Cfilter%2520id%253D%2527TheContractFilter%2527>%253CfeColorMatrix%2520type%253D%2527matrix%2527%2520values%253D%2527%25201.430%2520-0.639%2520-1.920%25200.000%25200.934%2520-0.852%2520-0.604%25200.328%25200.000%25200.934%25200.876%2520-3.300%25201.290%25200.000%25200.934%25200.000%25200.000%25200.000%25201.000%25200.000%2527%252F>%253CfeColorMatrix%2520type%253D%2527hueRotate%2527%2520values%253D%25270%2527>%253Canimate%2520attributeName%253D%2527values%2527%2520values%253D%25270%253B%2520360%253B%25200%2527%2520calcMode%253D%2527spline%2527%2520keySplines%253D%25270.4%25200%25200.2%25201%253B%25200.4%25200%25200.2%25201%2527%2520dur%253D%252730s%2527%2520repeatCount%253D%2527indefinite%2527%2520%252F>%253C%252FfeColorMatrix>%253C%252Ffilter>";
_svgParts[9]="<linearGradient id='TheContractGradient' x1='0' x2='0' y1='0' y2='1'><stop offset='0%' stop-color='#";
_svgParts[10]="%3ClinearGradient%20id%3D%27TheContractGradient%27%20x1%3D%270%27%20x2%3D%270%27%20y1%3D%270%27%20y2%3D%271%27>%3Cstop%20offset%3D%270%25%27%20stop-color%3D%27%23";
_svgParts[11]="%253ClinearGradient%2520id%253D%2527TheContractGradient%2527%2520x1%253D%25270%2527%2520x2%253D%25270%2527%2520y1%253D%25270%2527%2520y2%253D%25271%2527>%253Cstop%2520offset%253D%25270%2525%2527%2520stop-color%253D%2527%2523";
_svgParts[12]="'/><stop offset='50%' stop-color='#";
_svgParts[13]="%27%2F>%3Cstop%20offset%3D%2750%25%27%20stop-color%3D%27%23";
_svgParts[14]="%2527%252F>%253Cstop%2520offset%253D%252750%2525%2527%2520stop-color%253D%2527%2523";
_svgParts[15]="'/><stop offset='100%' stop-color='#";
_svgParts[16]="%27%2F>%3Cstop%20offset%3D%27100%25%27%20stop-color%3D%27%23";
_svgParts[17]="%2527%252F>%253Cstop%2520offset%253D%2527100%2525%2527%2520stop-color%253D%2527%2523";
_svgParts[18]="'/></linearGradient>";
_svgParts[19]="%27%2F>%3C%2FlinearGradient>";
_svgParts[20]="%2527%252F>%253C%252FlinearGradient>";
_svgParts[21]="</defs><g filter='url(#TheContractFilter)' clip-path='url(#TheContractClipPath)'><circle cx='50' cy='50' r='71' fill='url(#TheContractGradient)' fill-opacity='20%'><animateTransform attributeName='transform' type='rotate' from='0 50 50' to='360 50 50' dur='60s' repeatCount='indefinite' /></circle>";
_svgParts[22]="%3C%2Fdefs>%3Cg%20filter%3D%27url%28%23TheContractFilter%29%27%20clip-path%3D%27url%28%23TheContractClipPath%29%27>%3Ccircle%20cx%3D%2750%27%20cy%3D%2750%27%20r%3D%2771%27%20fill%3D%27url%28%23TheContractGradient%29%27%20fill-opacity%3D%2720%25%27>%3CanimateTransform%20attributeName%3D%27transform%27%20type%3D%27rotate%27%20from%3D%270%2050%2050%27%20to%3D%27360%2050%2050%27%20dur%3D%2760s%27%20repeatCount%3D%27indefinite%27%20%2F>%3C%2Fcircle>";
_svgParts[23]="%253C%252Fdefs>%253Cg%2520filter%253D%2527url%2528%2523TheContractFilter%2529%2527%2520clip-path%253D%2527url%2528%2523TheContractClipPath%2529%2527>%253Ccircle%2520cx%253D%252750%2527%2520cy%253D%252750%2527%2520r%253D%252771%2527%2520fill%253D%2527url%2528%2523TheContractGradient%2529%2527%2520fill-opacity%253D%252720%2525%2527>%253CanimateTransform%2520attributeName%253D%2527transform%2527%2520type%253D%2527rotate%2527%2520from%253D%25270%252050%252050%2527%2520to%253D%2527360%252050%252050%2527%2520dur%253D%252760s%2527%2520repeatCount%253D%2527indefinite%2527%2520%252F>%253C%252Fcircle>";
_svgParts[24]="<circle fill='#";
_svgParts[25]="%3Ccircle%20fill%3D%27%23";
_svgParts[26]="%253Ccircle%2520fill%253D%2527%2523";
_svgParts[27]="' cx='";
_svgParts[28]="%27%20cx%3D%27";
_svgParts[29]="%2527%2520cx%253D%2527";
_svgParts[30]="' cy='";
_svgParts[31]="%27%20cy%3D%27";
_svgParts[32]="%2527%2520cy%253D%2527";
_svgParts[33]="' r='4' />";
_svgParts[34]="%27%20r%3D%274%27%20%2F>";
_svgParts[35]="%2527%2520r%253D%25274%2527%2520%252F>";
_svgParts[36]="</g>";
_svgParts[37]="%3C%2Fg>";
_svgParts[38]="%253C%252Fg>";
_svgParts[39]="<text x='";
_svgParts[40]="%3Ctext%20x%3D%27";
_svgParts[41]="%253Ctext%2520x%253D%2527";
_svgParts[42]=".75' y='";
_svgParts[43]=".75%27%20y%3D%27";
_svgParts[44]=".75%2527%2520y%253D%2527";
_svgParts[45]="' fill='#ffffff' font-size='6px'>";
_svgParts[46]="%27%20fill%3D%27%23ffffff%27%20font-size%3D%276px%27>";
_svgParts[47]="%2527%2520fill%253D%2527%2523ffffff%2527%2520font-size%253D%25276px%2527>";
_svgParts[48]="</text>";
_svgParts[49]="%3C%2Ftext>";
_svgParts[50]="%253C%252Ftext>";
_svgParts[51]="</svg>";
_svgParts[52]="%3C%2Fsvg>";
_svgParts[53]="%253C%252Fsvg>";
_svgParts[54]="<g><animate attributeName='fill-opacity' values='1;0;1;1' dur='1s' repeatCount='indefinite'/>";
_svgParts[55]="%3Cg>%3Canimate%20attributeName%3D%27fill-opacity%27%20values%3D%271%3B0%3B1%3B1%27%20dur%3D%271s%27%20repeatCount%3D%27indefinite%27%2F>";
_svgParts[56]="%253Cg>%253Canimate%2520attributeName%253D%2527fill-opacity%2527%2520values%253D%25271%253B0%253B1%253B1%2527%2520dur%253D%25271s%2527%2520repeatCount%253D%2527indefinite%2527%252F>";
emit Transfer(address(0), msg.sender, 1);
}
function setArtistAccount(address artistAccount) public {
require(msg.sender == _artistAccount, "Only current artist account may change artist account");
_artistAccount = payable(artistAccount);
}
function generateSvg(uint8 urlEncodePasses) public view returns (string memory){
require(urlEncodePasses < 3, "Not possible to url encode more than two passes");
bytes memory b = getContractBytecode();
uint maximumNumberOfPixels = b.length/3;
uint rows = 10;
uint displayNumberOfPixels = rows*rows;
uint startAt = (displayNumberOfPixels*block.number) % (maximumNumberOfPixels - displayNumberOfPixels);
uint endAt = startAt + displayNumberOfPixels;
bytes memory data = abi.encodePacked(_svgParts[urlEncodePasses], (rows*10).toString(), _svgParts[3 + urlEncodePasses], (rows*10).toString(), _svgParts[6 + urlEncodePasses], generateLinearGradient(urlEncodePasses), _svgParts[21+urlEncodePasses]);
uint lastBlinkIndex = 0;
if(hasBid && bid >= 1 ether){
data = abi.encodePacked(data, _svgParts[54 + urlEncodePasses]);
lastBlinkIndex = startAt + bid / 1000000000000000000;
}
for (uint i = startAt; i < endAt; i++)
{
if(lastBlinkIndex > 0 && i == lastBlinkIndex){
data = abi.encodePacked(data, _svgParts[36 + urlEncodePasses]);
}
bytes memory hexColor = abi.encodePacked(uint8(b[3*i]).toHexString(), uint8(b[3*i+1]).toHexString(), uint8(b[3*i+2]).toHexString());
data = abi.encodePacked(data, _circleElement(urlEncodePasses, hexColor, (((i-startAt) % rows)*10+5).toString(), (10*((i-startAt) / rows)+5).toString()));
}
if(lastBlinkIndex >= endAt){
data = abi.encodePacked(data, _svgParts[36 + urlEncodePasses]);
}
return string(abi.encodePacked(data, _svgParts[36 + urlEncodePasses], generateBlockNumberElements(urlEncodePasses), _svgParts[51 + urlEncodePasses]));
}
function _circleElement(uint8 urlEncodePasses, bytes memory hexColor, string memory cx, string memory cy) private view returns (bytes memory){
return abi.encodePacked(_svgParts[24 + urlEncodePasses], hexColor, _svgParts[27 + urlEncodePasses], cx, _svgParts[30 + urlEncodePasses], cy, _svgParts[33 + urlEncodePasses]);
}
function generateLinearGradient(uint8 urlEncodePasses) internal view returns (string memory){
bytes memory ownerBytes = abi.encodePacked(owner);
bytes memory hexColor1 = abi.encodePacked(uint8(ownerBytes[0]).toHexString(),uint8(ownerBytes[1]).toHexString(),uint8(ownerBytes[2]).toHexString());
bytes memory hexColor2 = abi.encodePacked(uint8(ownerBytes[3]).toHexString(),uint8(ownerBytes[4]).toHexString(),uint8(ownerBytes[5]).toHexString());
bytes memory hexColor3 = abi.encodePacked(uint8(ownerBytes[6]).toHexString(),uint8(ownerBytes[7]).toHexString(),uint8(ownerBytes[8]).toHexString());
return string(abi.encodePacked(_svgParts[9+urlEncodePasses], hexColor1, _svgParts[12+urlEncodePasses], hexColor2, _svgParts[15+urlEncodePasses],hexColor3, _svgParts[18+urlEncodePasses]));
}
function generateBlockNumberElements(uint8 urlEncodePasses) internal view returns (string memory){
bytes memory blockNumber = bytes(block.number.toString());
uint8 x=93;
uint8 y=97;
bytes memory data;
for(uint i = blockNumber.length; i > 0; i--)
{
data = abi.encodePacked(data, _svgParts[39 + urlEncodePasses],x.toString(),_svgParts[42 + urlEncodePasses],y.toString(),_svgParts[45 + urlEncodePasses],blockNumber[i-1],_svgParts[48 + urlEncodePasses]);
x=x-10;
if(x < 3){
x=93;
y=y-10;
}
}
return string(data);
}
function contentType() public pure returns (string memory){
return "image/svg+xml";
}
function svg() public view returns (string memory){
return generateSvg(0);
}
function svgDataURI() public view returns (string memory){
return string(abi.encodePacked("data:", contentType(),",",generateSvg(1)));
}
function getContractBytecode() public view returns (bytes memory o_code) {
address contractAddress = address(this);
assembly {
// retrieve the size of the code, this needs assembly
let size := extcodesize(contractAddress)
// allocate output byte array - this could also be done without assembly
// by using o_code = new bytes(size)
o_code := mload(0x40)
// new "memory end" including padding
mstore(0x40, add(o_code, and(add(add(size, 0x20), 0x1f), not(0x1f))))
// store length in memory
mstore(o_code, size)
// actually retrieve the code, this needs assembly
extcodecopy(contractAddress, add(o_code, 0x20), 0, size)
}
}
// Implementation of supportsInterface as defined in ERC165 standard
function supportsInterface(bytes4 interfaceId) public view returns (bool) {
return _supportedInterfaces[interfaceId];
}
// Total token supply.
function totalSupply() public pure returns (uint256) {
return 1;
}
// Token by index of all tokens
function tokenByIndex(uint256 index) public pure returns (uint256) {
require(index == 0,"Index out of bound");
return 1;
}
// Token by index of owners tokens
function tokenOfOwnerByIndex(address owner_, uint256 index) public view returns (uint256) {
require(index == 0 && owner == owner_,"Index out of bound");
return 1;
}
// Token uri to creation metadata
function tokenURI(uint256 tokenId) public view returns (string memory) {
require(_exists(tokenId), "tokenURI query for nonexistent token");
return string(abi.encodePacked(
'data:application/json;charset=utf-8,{%22name%22%3A%22The%20Contract%22%2C%20%22description%22%3A%22The%20Contract%20is%20a%20Non-Fungible%20Token%20contract%20and%20the%20contract%20itself%20is%20the%20creation.%20Token%20holder%20is%20its%20owner.%20The%20contract%20is%20a%20homage%20to%20Fade%20by%20Pak%3A%200x62F5418d9Edbc13b7E07A15e095D7228cD9386c5%22%2C%22created_by%22%3A%22Eivind%20Kleiven%22%2C%22image_data%22%3A%22',generateSvg(1),'%22}'
));
}
// @return number of tokens held by owner_
function balanceOf(address owner_) public view returns (uint256) {
require(owner_ != address(0), "Balance query for the zero address");
return owner_ == owner ? 1 : 0;
}
// @return owner of tokenId
function ownerOf(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "Owner query for nonexistent token");
return owner;
}
// Approve to for tokenId. Be aware that an approved address are allowed to transfer tokenId.
function approve(address to, uint256 tokenId) public {
require(_exists(tokenId), "Approve query for nonexistent token");
require(to != owner, "Approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender),
"Approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
// @return tokenId approved address.
function getApproved(uint256 tokenId) public view returns (address) {
require(_exists(tokenId), "getApproved query for nonexistent token");
return _tokenApproval;
}
// Set approval for all. Be aware that if approval is set to true, then operator may transfer tokenId.
function setApprovalForAll(address operator, bool approved) public {
require(owner == msg.sender, "Only owner can set approval for all");
require(operator != msg.sender, "Approve to caller");
_operatorApprovals[operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
// @return approval boolean for an owner operator.
function isApprovedForAll(address owner_, address operator) public view returns (bool) {
if(owner_ == owner){
return _operatorApprovals[operator];
}
return false;
}
function transferFrom(address from, address to, uint256 tokenId) public {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(msg.sender, tokenId), "Transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
function safeTransferFrom(address from, address to, uint256 tokenId) public {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public {
require(_isApprovedOrOwner(msg.sender, tokenId), "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 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(_exists(tokenId), "Transfer of nonexistent token");
require(owner == from, "Transfer of token that is not own");
require(to != address(0), "Transfer to the zero address. Burn instead.");
_approve(address(0), tokenId);
_removeOffer();
owner = to;
emit Transfer(from, to, tokenId);
}
/**
* @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 returns (bool) {
return (tokenId == 1 && owner != address(0));
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) {
require(_exists(tokenId), "Operator query for nonexistent token");
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function burn(uint256 tokenId) public {
require(_exists(tokenId),"Try to burn nonexistent token.");
// Clear approvals
_approve(address(0), tokenId);
owner = address(0);
_removeOffer();
if(bid > 0){
uint amount = bid;
payable(bidder).transfer(amount);
_resetBid();
}
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApproval = to;
emit Approval(owner, 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)
{
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(to) }
if (size > 0) {
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("Transfer to non ERC721Receiver implementer");
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
function destruct() public {
require(msg.sender == owner, "Only owner can destruct contract.");
if(bid > 0){
payable(bidder).transfer(bid);
_resetBid();
}
selfdestruct(payable(msg.sender));
}
// ENTER MARKETPLACE
event Offered(uint indexed price, address indexed offeredTo);
event RecievedBid(uint indexed value, address indexed bidder);
event WithdrawnBid(uint indexed value, address indexed bidder);
event Sold(uint indexed price, address indexed seller, address indexed buyer);
event OfferRemoved();
bool public hasBid;
uint public bid;
address public bidder;
uint public offer;
bool public isForSale;
address public onlySellTo;
address public seller;
function _removeOffer() internal {
isForSale = false;
offer = 0;
seller = address(0);
onlySellTo = address(0);
}
function _resetBid() internal {
hasBid=false;
bid=0;
bidder=address(0);
}
function removeOffer() public {
require(owner == msg.sender, "Only owner can remove offer.");
_removeOffer();
emit OfferRemoved();
}
function offerForSale(uint priceInWei) public {
require(owner == msg.sender, "Only owner can offer for sale.");
offerForSaleToAddress(priceInWei, address(0));
}
function offerForSaleToAddress(uint priceInWei, address toAddress) public {
require(owner == msg.sender, "Only owner can offer for sale.");
require(priceInWei > 0, "Cannot offer for free.");
offer = priceInWei;
seller = msg.sender;
onlySellTo = toAddress;
isForSale = true;
emit Offered(priceInWei, toAddress);
}
function buy() payable public {
require(isForSale, "The Contract is not offered to buy.");
require(onlySellTo == address(0) || onlySellTo == msg.sender,"Not offered to this buyer.");
require(msg.value >= offer, "Sent less than offer.");
require(seller == owner, "Only owner allowed to sell.");
address payable beneficiary = payable(seller);
_safeTransfer(seller, msg.sender, 1, "");
uint amountToArtist = msg.value/10;
if(amountToArtist > 0){
_artistAccount.transfer(amountToArtist);
}
if(amountToArtist < msg.value)
{
beneficiary.transfer(msg.value - amountToArtist);
}
emit Sold(msg.value, seller, msg.sender);
}
function enterBid() public payable {
require(_exists(1), "Nothing exist to bid on");
require(owner != msg.sender, "Owner cannot bid");
require(msg.value > bid, "Not allowed to bid less than current bid");
address payable currentBidder = payable(bidder);
uint currentBid = bid;
hasBid = true;
bidder = msg.sender;
bid = msg.value;
if (currentBid > 0) {
// Refund previous bid
currentBidder.transfer(currentBid);
}
emit RecievedBid(msg.value, msg.sender);
}
function acceptBid(uint minPrice) public {
require(owner == msg.sender, "Only owner can accept bid.");
require(bid >= minPrice, "Bid lower than given minimum price");
uint amount = bid;
address payable beneficiary = payable(owner);
_safeTransfer(msg.sender, bidder, 1, "");
emit Sold(amount, msg.sender, bidder);
_resetBid();
uint amountToArtist = amount/10;
if(amountToArtist > 0){
_artistAccount.transfer(amountToArtist);
}
if(amountToArtist < amount)
{
beneficiary.transfer(amount - amountToArtist);
}
}
function withdrawBid() public {
require(bidder == msg.sender, "Only bidder can withdraw bid");
uint amount = bid;
address payable beneficiary = payable(bidder);
emit WithdrawnBid(bid, msg.sender);
_resetBid();
beneficiary.transfer(amount);
}
/// LEAVE MARKETPLACE
/// BEGIN NFT Royalty Standard (ERC-2981)
/**
* @notice Called with the sale price to determine how much royalty
* is owed and to whom.
* @param _tokenId - the NFT asset queried for royalty information
* @param _salePrice - the sale price of the NFT asset specified by _tokenId
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for _salePrice
*
**/
function royaltyInfo(
uint256 _tokenId,
uint256 _salePrice
) external view returns (
address,
uint256
){
require(_exists(_tokenId), "query for RoyaltyInfo for nonexistent tokenId");
return (_artistAccount, _salePrice/10);
}
/**
* @dev Returns true if implemented
*
* @dev this is how the marketplace can see if the contract has royalties, other than using the supportsInterface() call.
*/
function hasRoyalties() external pure returns (bool){
return true;
}
/**
* @dev Returns uint256 of the amount of percentage the royalty is set to. For example, if 1%, would return "1", if 50%, would return "50"
*
*/
function royaltyAmount() external pure returns (uint256){
return 10;
}
/// END NFT Royalty Standard (ERC-2981)
}
/**
* @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 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 with fixed length.
*/
function toHexString(uint8 value) internal pure returns (string memory) {
if (value == 0) {
return "00";
}
bytes memory buffer = new bytes(2);
buffer[1] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
buffer[0] = _HEX_SYMBOLS[value & 0xf];
return string(buffer);
}
} | Refund previous bid | function enterBid() public payable {
require(_exists(1), "Nothing exist to bid on");
require(owner != msg.sender, "Owner cannot bid");
require(msg.value > bid, "Not allowed to bid less than current bid");
address payable currentBidder = payable(bidder);
uint currentBid = bid;
hasBid = true;
bidder = msg.sender;
bid = msg.value;
if (currentBid > 0) {
currentBidder.transfer(currentBid);
}
emit RecievedBid(msg.value, msg.sender);
}
| 12,198,771 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {AccessControl} from '@openzeppelin/contracts/access/AccessControl.sol';
import {ReentrancyGuard} from '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import {IERC20, SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {EnumerableSet} from '@openzeppelin/contracts/utils/structs/EnumerableSet.sol';
import {FeeSharingSystem} from './FeeSharingSystem.sol';
import {TokenDistributor} from './TokenDistributor.sol';
import {IRewardConvertor} from './IRewardConvertor.sol';
import {IMintableERC20} from './IMintableERC20.sol';
import {ITokenStaked} from './ITokenStaked.sol';
/**
* @title FeeSharingSetter
* @notice It receives exchange fees and owns the FeeSharingSystem contract.
* It can plug to AMMs for converting all received currencies to WETH.
*/
contract FeeSharingSetter is ReentrancyGuard, AccessControl {
using EnumerableSet for EnumerableSet.AddressSet;
using SafeERC20 for IERC20;
// Operator role
bytes32 public constant OPERATOR_ROLE = keccak256('OPERATOR_ROLE');
// Min duration for each fee-sharing period (in blocks)
uint256 public immutable MIN_REWARD_DURATION_IN_BLOCKS;
// Max duration for each fee-sharing period (in blocks)
uint256 public immutable MAX_REWARD_DURATION_IN_BLOCKS;
IERC20 public immutable x2y2Token;
IERC20 public immutable rewardToken;
FeeSharingSystem public feeSharingSystem;
TokenDistributor public immutable tokenDistributor;
// Reward convertor (tool to convert other currencies to rewardToken)
IRewardConvertor public rewardConvertor;
// Last reward block of distribution
uint256 public lastRewardDistributionBlock;
// Next reward duration in blocks
uint256 public nextRewardDurationInBlocks;
// Reward duration in blocks
uint256 public rewardDurationInBlocks;
// Set of addresses that are staking only the fee sharing
EnumerableSet.AddressSet private _feeStakingAddresses;
mapping(address => bool) public feeStakingAddressIStaked;
event ConversionToRewardToken(
address indexed token,
uint256 amountConverted,
uint256 amountReceived
);
event FeeStakingAddressesAdded(address[] feeStakingAddresses);
event FeeStakingAddressesRemoved(address[] feeStakingAddresses);
event NewRewardDurationInBlocks(uint256 rewardDurationInBlocks);
event NewRewardConvertor(address rewardConvertor);
/**
* @notice Constructor
* @param _feeSharingSystem address of the fee sharing system
* @param _minRewardDurationInBlocks minimum reward duration in blocks
* @param _maxRewardDurationInBlocks maximum reward duration in blocks
* @param _rewardDurationInBlocks reward duration between two updates in blocks
*/
constructor(
address _feeSharingSystem,
uint256 _minRewardDurationInBlocks,
uint256 _maxRewardDurationInBlocks,
uint256 _rewardDurationInBlocks
) {
require(
(_rewardDurationInBlocks <= _maxRewardDurationInBlocks) &&
(_rewardDurationInBlocks >= _minRewardDurationInBlocks),
'Owner: Reward duration in blocks outside of range'
);
MIN_REWARD_DURATION_IN_BLOCKS = _minRewardDurationInBlocks;
MAX_REWARD_DURATION_IN_BLOCKS = _maxRewardDurationInBlocks;
feeSharingSystem = FeeSharingSystem(_feeSharingSystem);
rewardToken = feeSharingSystem.rewardToken();
x2y2Token = feeSharingSystem.x2y2Token();
tokenDistributor = feeSharingSystem.tokenDistributor();
rewardDurationInBlocks = _rewardDurationInBlocks;
nextRewardDurationInBlocks = _rewardDurationInBlocks;
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
* @notice Update the reward per block (in rewardToken)
* @dev It automatically retrieves the number of pending WETH and adjusts
* based on the balance of X2Y2 in fee-staking addresses that exist in the set.
*/
function updateRewards() external onlyRole(OPERATOR_ROLE) {
if (lastRewardDistributionBlock > 0) {
require(
block.number > (rewardDurationInBlocks + lastRewardDistributionBlock),
'Reward: Too early to add'
);
}
// Adjust for this period
if (rewardDurationInBlocks != nextRewardDurationInBlocks) {
rewardDurationInBlocks = nextRewardDurationInBlocks;
}
lastRewardDistributionBlock = block.number;
// Calculate the reward to distribute as the balance held by this address
uint256 reward = rewardToken.balanceOf(address(this));
require(reward != 0, 'Reward: Nothing to distribute');
// Check if there is any address eligible for fee-sharing only
uint256 numberAddressesForFeeStaking = _feeStakingAddresses.length();
// If there are eligible addresses for fee-sharing only, calculate their shares
if (numberAddressesForFeeStaking > 0) {
uint256[] memory x2y2Balances = new uint256[](numberAddressesForFeeStaking);
(uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(feeSharingSystem));
for (uint256 i = 0; i < numberAddressesForFeeStaking; i++) {
address a = _feeStakingAddresses.at(i);
uint256 balance = x2y2Token.balanceOf(a);
if (feeStakingAddressIStaked[a]) {
balance = ITokenStaked(a).getTotalStaked();
}
totalAmountStaked += balance;
x2y2Balances[i] = balance;
}
// Only apply the logic if the totalAmountStaked > 0 (to prevent division by 0)
if (totalAmountStaked > 0) {
uint256 adjustedReward = reward;
for (uint256 i = 0; i < numberAddressesForFeeStaking; i++) {
uint256 amountToTransfer = (x2y2Balances[i] * reward) / totalAmountStaked;
if (amountToTransfer > 0) {
adjustedReward -= amountToTransfer;
rewardToken.safeTransfer(_feeStakingAddresses.at(i), amountToTransfer);
}
}
// Adjust reward accordingly
reward = adjustedReward;
}
}
// Transfer tokens to fee sharing system
rewardToken.safeTransfer(address(feeSharingSystem), reward);
// Update rewards
feeSharingSystem.updateRewards(reward, rewardDurationInBlocks);
}
/**
* @notice Convert currencies to reward token
* @dev Function only usable only for whitelisted currencies (where no potential side effect)
* @param token address of the token to sell
* @param additionalData additional data (e.g., slippage)
*/
function convertCurrencyToRewardToken(address token, bytes calldata additionalData)
external
nonReentrant
onlyRole(OPERATOR_ROLE)
{
require(address(rewardConvertor) != address(0), 'Convert: RewardConvertor not set');
require(token != address(rewardToken), 'Convert: Cannot be reward token');
uint256 amountToConvert = IERC20(token).balanceOf(address(this));
require(amountToConvert != 0, 'Convert: Amount to convert must be > 0');
// Adjust allowance for this transaction only
IERC20(token).safeIncreaseAllowance(address(rewardConvertor), amountToConvert);
// Exchange token to reward token
uint256 amountReceived = rewardConvertor.convert(
token,
address(rewardToken),
amountToConvert,
additionalData
);
emit ConversionToRewardToken(token, amountToConvert, amountReceived);
}
/**
* @notice Add staking addresses
* @param _stakingAddresses array of addresses eligible for fee-sharing only
*/
function addFeeStakingAddresses(
address[] calldata _stakingAddresses,
bool[] calldata _addressIStaked
) external onlyRole(DEFAULT_ADMIN_ROLE) {
require(_stakingAddresses.length == _addressIStaked.length, 'Owner: param length error');
for (uint256 i = 0; i < _stakingAddresses.length; i++) {
require(
!_feeStakingAddresses.contains(_stakingAddresses[i]),
'Owner: Address already registered'
);
_feeStakingAddresses.add(_stakingAddresses[i]);
if (_addressIStaked[i]) {
feeStakingAddressIStaked[_stakingAddresses[i]] = true;
}
}
emit FeeStakingAddressesAdded(_stakingAddresses);
}
/**
* @notice Remove staking addresses
* @param _stakingAddresses array of addresses eligible for fee-sharing only
*/
function removeFeeStakingAddresses(address[] calldata _stakingAddresses)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
for (uint256 i = 0; i < _stakingAddresses.length; i++) {
require(
_feeStakingAddresses.contains(_stakingAddresses[i]),
'Owner: Address not registered'
);
_feeStakingAddresses.remove(_stakingAddresses[i]);
if (feeStakingAddressIStaked[_stakingAddresses[i]]) {
delete feeStakingAddressIStaked[_stakingAddresses[i]];
}
}
emit FeeStakingAddressesRemoved(_stakingAddresses);
}
/**
* @notice Set new reward duration in blocks for next update
* @param _newRewardDurationInBlocks number of blocks for new reward period
*/
function setNewRewardDurationInBlocks(uint256 _newRewardDurationInBlocks)
external
onlyRole(DEFAULT_ADMIN_ROLE)
{
require(
(_newRewardDurationInBlocks <= MAX_REWARD_DURATION_IN_BLOCKS) &&
(_newRewardDurationInBlocks >= MIN_REWARD_DURATION_IN_BLOCKS),
'Owner: New reward duration in blocks outside of range'
);
nextRewardDurationInBlocks = _newRewardDurationInBlocks;
emit NewRewardDurationInBlocks(_newRewardDurationInBlocks);
}
/**
* @notice Set reward convertor contract
* @param _rewardConvertor address of the reward convertor (set to null to deactivate)
*/
function setRewardConvertor(address _rewardConvertor) external onlyRole(DEFAULT_ADMIN_ROLE) {
rewardConvertor = IRewardConvertor(_rewardConvertor);
emit NewRewardConvertor(_rewardConvertor);
}
/**
* @notice See addresses eligible for fee-staking
*/
function viewFeeStakingAddresses() external view returns (address[] memory) {
uint256 length = _feeStakingAddresses.length();
address[] memory feeStakingAddresses = new address[](length);
for (uint256 i = 0; i < length; i++) {
feeStakingAddresses[i] = _feeStakingAddresses.at(i);
}
return (feeStakingAddresses);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol)
pragma solidity ^0.8.0;
import "./IAccessControl.sol";
import "../utils/Context.sol";
import "../utils/Strings.sol";
import "../utils/introspection/ERC165.sol";
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms. This is a lightweight version that doesn't allow enumerating role
* members except through off-chain means by accessing the contract event logs. Some
* applications may benefit from on-chain enumerability, for those cases see
* {AccessControlEnumerable}.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context, IAccessControl, ERC165 {
struct RoleData {
mapping(address => bool) members;
bytes32 adminRole;
}
mapping(bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Modifier that checks that an account has a specific role. Reverts
* with a standardized message including the required role.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*
* _Available since v4.1._
*/
modifier onlyRole(bytes32 role) {
_checkRole(role, _msgSender());
_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view override returns (bool) {
return _roles[role].members[account];
}
/**
* @dev Revert with a standard message if `account` is missing `role`.
*
* The format of the revert reason is given by the following regular expression:
*
* /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/
*/
function _checkRole(bytes32 role, address account) internal view {
if (!hasRole(role, account)) {
revert(
string(
abi.encodePacked(
"AccessControl: account ",
Strings.toHexString(uint160(account), 20),
" is missing role ",
Strings.toHexString(uint256(role), 32)
)
)
);
}
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view override returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) {
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been revoked `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual override {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*
* NOTE: This function is deprecated in favor of {_grantRole}.
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
bytes32 previousAdminRole = getRoleAdmin(role);
_roles[role].adminRole = adminRole;
emit RoleAdminChanged(role, previousAdminRole, adminRole);
}
/**
* @dev Grants `role` to `account`.
*
* Internal function without access restriction.
*/
function _grantRole(bytes32 role, address account) internal virtual {
if (!hasRole(role, account)) {
_roles[role].members[account] = true;
emit RoleGranted(role, account, _msgSender());
}
}
/**
* @dev Revokes `role` from `account`.
*
* Internal function without access restriction.
*/
function _revokeRole(bytes32 role, address account) internal virtual {
if (hasRole(role, account)) {
_roles[role].members[account] = false;
emit RoleRevoked(role, account, _msgSender());
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol)
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/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
pragma solidity ^0.8.0;
import {AccessControl} from '@openzeppelin/contracts/access/AccessControl.sol';
import {IERC20, SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {ReentrancyGuard} from '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import {TokenDistributor} from './TokenDistributor.sol';
import {IStakeFor} from './IStakeFor.sol';
/**
* @title FeeSharingSystem
* @notice It handles the distribution of fees using
* WETH along with the auto-compounding of X2Y2.
*/
contract FeeSharingSystem is ReentrancyGuard, AccessControl, IStakeFor {
using SafeERC20 for IERC20;
// for `depositFor` call
bytes32 public constant DEPOSIT_ROLE = keccak256('DEPOSIT_ROLE');
// for `updateRewards()`
bytes32 public constant REWARD_UPDATE_ROLE = keccak256('REWARD_UPDATE_ROLE');
struct UserInfo {
uint256 shares; // shares of token staked
uint256 userRewardPerTokenPaid; // user reward per token paid
uint256 rewards; // pending rewards
}
// Precision factor for calculating rewards and exchange rate
uint256 public constant PRECISION_FACTOR = 10**18;
IERC20 public immutable x2y2Token;
IERC20 public immutable rewardToken;
TokenDistributor public immutable tokenDistributor;
// Reward rate (block)
uint256 public currentRewardPerBlock;
// Last reward adjustment block number
uint256 public lastRewardAdjustment;
// Last update block for rewards
uint256 public lastUpdateBlock;
// Current end block for the current reward period
uint256 public periodEndBlock;
// Reward per token stored
uint256 public rewardPerTokenStored;
// Total existing shares
uint256 public totalShares;
mapping(address => UserInfo) public userInfo;
event Deposit(address indexed user, uint256 amount, uint256 harvestedAmount);
event Harvest(address indexed user, uint256 harvestedAmount);
event NewRewardPeriod(uint256 numberBlocks, uint256 rewardPerBlock, uint256 reward);
event Withdraw(address indexed user, uint256 amount, uint256 harvestedAmount);
/**
* @notice Constructor
* @param _x2y2Token address of the token staked
* @param _rewardToken address of the reward token
* @param _tokenDistributor address of the token distributor contract
*/
constructor(
address _x2y2Token,
address _rewardToken,
address _tokenDistributor
) {
rewardToken = IERC20(_rewardToken);
x2y2Token = IERC20(_x2y2Token);
tokenDistributor = TokenDistributor(_tokenDistributor);
_grantRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/**
* @notice deposit on behalf of `user`, must be called on fresh deposit only
* @param user deposit user
* @param amount amount to deposit
*/
function depositFor(address user, uint256 amount)
external
override
nonReentrant
onlyRole(DEPOSIT_ROLE)
returns (bool)
{
require(amount >= PRECISION_FACTOR, 'Deposit: Amount must be >= 1 X2Y2');
// Auto compounds for everyone
tokenDistributor.harvestAndCompound();
// Update reward for user
_updateReward(user);
// Retrieve total amount staked by this contract
(uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this));
// transfer stakingToken from **sender**
x2y2Token.safeTransferFrom(msg.sender, address(this), amount);
uint256 currentShares;
// Calculate the number of shares to issue for the user
if (totalShares != 0) {
currentShares = (amount * totalShares) / totalAmountStaked;
// This is a sanity check to prevent deposit for 0 shares
require(currentShares != 0, 'Deposit: Fail');
} else {
currentShares = amount;
}
// Adjust internal shares
userInfo[user].shares += currentShares;
totalShares += currentShares;
// Verify X2Y2 token allowance and adjust if necessary
_checkAndAdjustX2Y2TokenAllowanceIfRequired(amount, address(tokenDistributor));
// Deposit user amount in the token distributor contract
tokenDistributor.deposit(amount);
emit Deposit(user, amount, 0);
return true;
}
/**
* @notice Deposit staked tokens (and collect reward tokens if requested)
* @param amount amount to deposit (in X2Y2)
* @param claimRewardToken whether to claim reward tokens
* @dev There is a limit of 1 X2Y2 per deposit to prevent potential manipulation of current shares
*/
function deposit(uint256 amount, bool claimRewardToken) external nonReentrant {
require(amount >= PRECISION_FACTOR, 'Deposit: Amount must be >= 1 X2Y2');
// Auto compounds for everyone
tokenDistributor.harvestAndCompound();
// Update reward for user
_updateReward(msg.sender);
// Retrieve total amount staked by this contract
(uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this));
// Transfer X2Y2 tokens to this address
x2y2Token.safeTransferFrom(msg.sender, address(this), amount);
uint256 currentShares;
// Calculate the number of shares to issue for the user
if (totalShares != 0) {
currentShares = (amount * totalShares) / totalAmountStaked;
// This is a sanity check to prevent deposit for 0 shares
require(currentShares != 0, 'Deposit: Fail');
} else {
currentShares = amount;
}
// Adjust internal shares
userInfo[msg.sender].shares += currentShares;
totalShares += currentShares;
uint256 pendingRewards;
if (claimRewardToken) {
// Fetch pending rewards
pendingRewards = userInfo[msg.sender].rewards;
if (pendingRewards > 0) {
userInfo[msg.sender].rewards = 0;
rewardToken.safeTransfer(msg.sender, pendingRewards);
}
}
// Verify X2Y2 token allowance and adjust if necessary
_checkAndAdjustX2Y2TokenAllowanceIfRequired(amount, address(tokenDistributor));
// Deposit user amount in the token distributor contract
tokenDistributor.deposit(amount);
emit Deposit(msg.sender, amount, pendingRewards);
}
/**
* @notice Harvest reward tokens that are pending
*/
function harvest() external nonReentrant {
// Auto compounds for everyone
tokenDistributor.harvestAndCompound();
// Update reward for user
_updateReward(msg.sender);
// Retrieve pending rewards
uint256 pendingRewards = userInfo[msg.sender].rewards;
// If pending rewards are null, revert
require(pendingRewards > 0, 'Harvest: Pending rewards must be > 0');
// Adjust user rewards and transfer
userInfo[msg.sender].rewards = 0;
// Transfer reward token to sender
rewardToken.safeTransfer(msg.sender, pendingRewards);
emit Harvest(msg.sender, pendingRewards);
}
/**
* @notice Withdraw staked tokens (and collect reward tokens if requested)
* @param shares shares to withdraw
* @param claimRewardToken whether to claim reward tokens
*/
function withdraw(uint256 shares, bool claimRewardToken) external nonReentrant {
require(
(shares > 0) && (shares <= userInfo[msg.sender].shares),
'Withdraw: Shares equal to 0 or larger than user shares'
);
_withdraw(shares, claimRewardToken);
}
/**
* @notice Withdraw all staked tokens (and collect reward tokens if requested)
* @param claimRewardToken whether to claim reward tokens
*/
function withdrawAll(bool claimRewardToken) external nonReentrant {
_withdraw(userInfo[msg.sender].shares, claimRewardToken);
}
/**
* @notice Update the reward per block (in rewardToken)
* @dev Only callable by owner. Owner is meant to be another smart contract.
*/
function updateRewards(uint256 reward, uint256 rewardDurationInBlocks)
external
onlyRole(REWARD_UPDATE_ROLE)
{
// Adjust the current reward per block
if (block.number >= periodEndBlock) {
currentRewardPerBlock = reward / rewardDurationInBlocks;
} else {
currentRewardPerBlock =
(reward + ((periodEndBlock - block.number) * currentRewardPerBlock)) /
rewardDurationInBlocks;
}
lastUpdateBlock = block.number;
periodEndBlock = block.number + rewardDurationInBlocks;
emit NewRewardPeriod(rewardDurationInBlocks, currentRewardPerBlock, reward);
}
/**
* @notice Calculate pending rewards (WETH) for a user
* @param user address of the user
*/
function calculatePendingRewards(address user) external view returns (uint256) {
return _calculatePendingRewards(user);
}
/**
* @notice Calculate value of X2Y2 for a user given a number of shares owned
* @param user address of the user
*/
function calculateSharesValueInX2Y2(address user) external view returns (uint256) {
// Retrieve amount staked
(uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this));
// Adjust for pending rewards
totalAmountStaked += tokenDistributor.calculatePendingRewards(address(this));
// Return user pro-rata of total shares
return
userInfo[user].shares == 0
? 0
: (totalAmountStaked * userInfo[user].shares) / totalShares;
}
/**
* @notice Calculate price of one share (in X2Y2 token)
* Share price is expressed times 1e18
*/
function calculateSharePriceInX2Y2() external view returns (uint256) {
(uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this));
// Adjust for pending rewards
totalAmountStaked += tokenDistributor.calculatePendingRewards(address(this));
return
totalShares == 0
? PRECISION_FACTOR
: (totalAmountStaked * PRECISION_FACTOR) / (totalShares);
}
/**
* @notice Return last block where trading rewards were distributed
*/
function lastRewardBlock() external view returns (uint256) {
return _lastRewardBlock();
}
/**
* @notice Calculate pending rewards for a user
* @param user address of the user
*/
function _calculatePendingRewards(address user) internal view returns (uint256) {
return
((userInfo[user].shares *
(_rewardPerToken() - (userInfo[user].userRewardPerTokenPaid))) / PRECISION_FACTOR) +
userInfo[user].rewards;
}
/**
* @notice Check current allowance and adjust if necessary
* @param _amount amount to transfer
* @param _to token to transfer
*/
function _checkAndAdjustX2Y2TokenAllowanceIfRequired(uint256 _amount, address _to) internal {
if (x2y2Token.allowance(address(this), _to) < _amount) {
x2y2Token.approve(_to, type(uint256).max);
}
}
/**
* @notice Return last block where rewards must be distributed
*/
function _lastRewardBlock() internal view returns (uint256) {
return block.number < periodEndBlock ? block.number : periodEndBlock;
}
/**
* @notice Return reward per token
*/
function _rewardPerToken() internal view returns (uint256) {
if (totalShares == 0) {
return rewardPerTokenStored;
}
return
rewardPerTokenStored +
((_lastRewardBlock() - lastUpdateBlock) * (currentRewardPerBlock * PRECISION_FACTOR)) /
totalShares;
}
/**
* @notice Update reward for a user account
* @param _user address of the user
*/
function _updateReward(address _user) internal {
if (block.number != lastUpdateBlock) {
rewardPerTokenStored = _rewardPerToken();
lastUpdateBlock = _lastRewardBlock();
}
userInfo[_user].rewards = _calculatePendingRewards(_user);
userInfo[_user].userRewardPerTokenPaid = rewardPerTokenStored;
}
/**
* @notice Withdraw staked tokens (and collect reward tokens if requested)
* @param shares shares to withdraw
* @param claimRewardToken whether to claim reward tokens
*/
function _withdraw(uint256 shares, bool claimRewardToken) internal {
// Auto compounds for everyone
tokenDistributor.harvestAndCompound();
// Update reward for user
_updateReward(msg.sender);
// Retrieve total amount staked and calculated current amount (in X2Y2)
(uint256 totalAmountStaked, ) = tokenDistributor.userInfo(address(this));
uint256 currentAmount = (totalAmountStaked * shares) / totalShares;
userInfo[msg.sender].shares -= shares;
totalShares -= shares;
// Withdraw amount equivalent in shares
tokenDistributor.withdraw(currentAmount);
uint256 pendingRewards;
if (claimRewardToken) {
// Fetch pending rewards
pendingRewards = userInfo[msg.sender].rewards;
if (pendingRewards > 0) {
userInfo[msg.sender].rewards = 0;
rewardToken.safeTransfer(msg.sender, pendingRewards);
}
}
// Transfer X2Y2 tokens to sender
x2y2Token.safeTransfer(msg.sender, currentAmount);
emit Withdraw(msg.sender, currentAmount, pendingRewards);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {ReentrancyGuard} from '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import {IERC20, SafeERC20} from '@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol';
import {IMintableERC20} from './IMintableERC20.sol';
/**
* @title TokenDistributor
* @notice It handles the distribution of X2Y2 token.
* It auto-adjusts block rewards over a set number of periods.
*/
contract TokenDistributor is ReentrancyGuard {
using SafeERC20 for IERC20;
using SafeERC20 for IMintableERC20;
struct StakingPeriod {
uint256 rewardPerBlockForStaking;
uint256 rewardPerBlockForOthers;
uint256 periodLengthInBlock;
}
struct UserInfo {
uint256 amount; // Amount of staked tokens provided by user
uint256 rewardDebt; // Reward debt
}
// Precision factor for calculating rewards
uint256 public constant PRECISION_FACTOR = 10**12;
IMintableERC20 public immutable x2y2Token;
address public immutable tokenSplitter;
// Number of reward periods
uint256 public immutable NUMBER_PERIODS;
// Block number when rewards start
uint256 public immutable START_BLOCK;
// Accumulated tokens per share
uint256 public accTokenPerShare;
// Current phase for rewards
uint256 public currentPhase;
// Block number when rewards end
uint256 public endBlock;
// Block number of the last update
uint256 public lastRewardBlock;
// Tokens distributed per block for other purposes (team + treasury + trading rewards)
uint256 public rewardPerBlockForOthers;
// Tokens distributed per block for staking
uint256 public rewardPerBlockForStaking;
// Total amount staked
uint256 public totalAmountStaked;
mapping(uint256 => StakingPeriod) public stakingPeriod;
mapping(address => UserInfo) public userInfo;
event Compound(address indexed user, uint256 harvestedAmount);
event Deposit(address indexed user, uint256 amount, uint256 harvestedAmount);
event NewRewardsPerBlock(
uint256 indexed currentPhase,
uint256 startBlock,
uint256 rewardPerBlockForStaking,
uint256 rewardPerBlockForOthers
);
event Withdraw(address indexed user, uint256 amount, uint256 harvestedAmount);
/**
* @notice Constructor
* @param _x2y2Token token address
* @param _tokenSplitter token splitter contract address (for team and trading rewards)
* @param _startBlock start block for reward program
* @param _rewardsPerBlockForStaking array of rewards per block for staking
* @param _rewardsPerBlockForOthers array of rewards per block for other purposes (team + treasury + trading rewards)
* @param _periodLengthesInBlocks array of period lengthes
* @param _numberPeriods number of periods with different rewards/lengthes (e.g., if 3 changes --> 4 periods)
*/
constructor(
address _x2y2Token,
address _tokenSplitter,
uint256 _startBlock,
uint256[] memory _rewardsPerBlockForStaking,
uint256[] memory _rewardsPerBlockForOthers,
uint256[] memory _periodLengthesInBlocks,
uint256 _numberPeriods
) {
require(
(_periodLengthesInBlocks.length == _numberPeriods) &&
(_rewardsPerBlockForStaking.length == _numberPeriods) &&
(_rewardsPerBlockForStaking.length == _numberPeriods),
'Distributor: Lengthes must match numberPeriods'
);
// 1. Operational checks for supply
uint256 nonCirculatingSupply = IMintableERC20(_x2y2Token).SUPPLY_CAP() -
IMintableERC20(_x2y2Token).totalSupply();
uint256 amountTokensToBeMinted;
for (uint256 i = 0; i < _numberPeriods; i++) {
amountTokensToBeMinted +=
(_rewardsPerBlockForStaking[i] * _periodLengthesInBlocks[i]) +
(_rewardsPerBlockForOthers[i] * _periodLengthesInBlocks[i]);
stakingPeriod[i] = StakingPeriod({
rewardPerBlockForStaking: _rewardsPerBlockForStaking[i],
rewardPerBlockForOthers: _rewardsPerBlockForOthers[i],
periodLengthInBlock: _periodLengthesInBlocks[i]
});
}
require(
amountTokensToBeMinted == nonCirculatingSupply,
'Distributor: Wrong reward parameters'
);
// 2. Store values
x2y2Token = IMintableERC20(_x2y2Token);
tokenSplitter = _tokenSplitter;
rewardPerBlockForStaking = _rewardsPerBlockForStaking[0];
rewardPerBlockForOthers = _rewardsPerBlockForOthers[0];
START_BLOCK = _startBlock;
endBlock = _startBlock + _periodLengthesInBlocks[0];
NUMBER_PERIODS = _numberPeriods;
// Set the lastRewardBlock as the startBlock
lastRewardBlock = _startBlock;
}
/**
* @notice Deposit staked tokens and compounds pending rewards
* @param amount amount to deposit (in X2Y2)
*/
function deposit(uint256 amount) external nonReentrant {
require(amount > 0, 'Deposit: Amount must be > 0');
require(block.number >= START_BLOCK, 'Deposit: Not started yet');
// Update pool information
_updatePool();
// Transfer X2Y2 tokens to this contract
x2y2Token.safeTransferFrom(msg.sender, address(this), amount);
uint256 pendingRewards;
// If not new deposit, calculate pending rewards (for auto-compounding)
if (userInfo[msg.sender].amount > 0) {
pendingRewards =
((userInfo[msg.sender].amount * accTokenPerShare) / PRECISION_FACTOR) -
userInfo[msg.sender].rewardDebt;
}
// Adjust user information
userInfo[msg.sender].amount += (amount + pendingRewards);
userInfo[msg.sender].rewardDebt =
(userInfo[msg.sender].amount * accTokenPerShare) /
PRECISION_FACTOR;
// Increase totalAmountStaked
totalAmountStaked += (amount + pendingRewards);
emit Deposit(msg.sender, amount, pendingRewards);
}
/**
* @notice Compound based on pending rewards
*/
function harvestAndCompound() external nonReentrant {
// Update pool information
_updatePool();
// Calculate pending rewards
uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) /
PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt;
// Return if no pending rewards
if (pendingRewards == 0) {
// It doesn't throw revertion (to help with the fee-sharing auto-compounding contract)
return;
}
// Adjust user amount for pending rewards
userInfo[msg.sender].amount += pendingRewards;
// Adjust totalAmountStaked
totalAmountStaked += pendingRewards;
// Recalculate reward debt based on new user amount
userInfo[msg.sender].rewardDebt =
(userInfo[msg.sender].amount * accTokenPerShare) /
PRECISION_FACTOR;
emit Compound(msg.sender, pendingRewards);
}
/**
* @notice Update pool rewards
*/
function updatePool() external nonReentrant {
_updatePool();
}
/**
* @notice Withdraw staked tokens and compound pending rewards
* @param amount amount to withdraw
*/
function withdraw(uint256 amount) external nonReentrant {
require(
(userInfo[msg.sender].amount >= amount) && (amount > 0),
'Withdraw: Amount must be > 0 or lower than user balance'
);
// Update pool
_updatePool();
// Calculate pending rewards
uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) /
PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt;
// Adjust user information
userInfo[msg.sender].amount = userInfo[msg.sender].amount + pendingRewards - amount;
userInfo[msg.sender].rewardDebt =
(userInfo[msg.sender].amount * accTokenPerShare) /
PRECISION_FACTOR;
// Adjust total amount staked
totalAmountStaked = totalAmountStaked + pendingRewards - amount;
// Transfer X2Y2 tokens to the sender
x2y2Token.safeTransfer(msg.sender, amount);
emit Withdraw(msg.sender, amount, pendingRewards);
}
/**
* @notice Withdraw all staked tokens and collect tokens
*/
function withdrawAll() external nonReentrant {
require(userInfo[msg.sender].amount > 0, 'Withdraw: Amount must be > 0');
// Update pool
_updatePool();
// Calculate pending rewards and amount to transfer (to the sender)
uint256 pendingRewards = ((userInfo[msg.sender].amount * accTokenPerShare) /
PRECISION_FACTOR) - userInfo[msg.sender].rewardDebt;
uint256 amountToTransfer = userInfo[msg.sender].amount + pendingRewards;
// Adjust total amount staked
totalAmountStaked = totalAmountStaked - userInfo[msg.sender].amount;
// Adjust user information
userInfo[msg.sender].amount = 0;
userInfo[msg.sender].rewardDebt = 0;
// Transfer X2Y2 tokens to the sender
x2y2Token.safeTransfer(msg.sender, amountToTransfer);
emit Withdraw(msg.sender, amountToTransfer, pendingRewards);
}
/**
* @notice Calculate pending rewards for a user
* @param user address of the user
* @return Pending rewards
*/
function calculatePendingRewards(address user) external view returns (uint256) {
if ((block.number > lastRewardBlock) && (totalAmountStaked != 0)) {
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking;
uint256 adjustedEndBlock = endBlock;
uint256 adjustedCurrentPhase = currentPhase;
// Check whether to adjust multipliers and reward per block
while (
(block.number > adjustedEndBlock) && (adjustedCurrentPhase < (NUMBER_PERIODS - 1))
) {
// Update current phase
adjustedCurrentPhase++;
// Update rewards per block
uint256 adjustedRewardPerBlockForStaking = stakingPeriod[adjustedCurrentPhase]
.rewardPerBlockForStaking;
// Calculate adjusted block number
uint256 previousEndBlock = adjustedEndBlock;
// Update end block
adjustedEndBlock =
previousEndBlock +
stakingPeriod[adjustedCurrentPhase].periodLengthInBlock;
// Calculate new multiplier
uint256 newMultiplier = (block.number <= adjustedEndBlock)
? (block.number - previousEndBlock)
: stakingPeriod[adjustedCurrentPhase].periodLengthInBlock;
// Adjust token rewards for staking
tokenRewardForStaking += (newMultiplier * adjustedRewardPerBlockForStaking);
}
uint256 adjustedTokenPerShare = accTokenPerShare +
(tokenRewardForStaking * PRECISION_FACTOR) /
totalAmountStaked;
return
(userInfo[user].amount * adjustedTokenPerShare) /
PRECISION_FACTOR -
userInfo[user].rewardDebt;
} else {
return
(userInfo[user].amount * accTokenPerShare) /
PRECISION_FACTOR -
userInfo[user].rewardDebt;
}
}
/**
* @notice Update reward variables of the pool
*/
function _updatePool() internal {
if (block.number <= lastRewardBlock) {
return;
}
if (totalAmountStaked == 0) {
lastRewardBlock = block.number;
return;
}
// Calculate multiplier
uint256 multiplier = _getMultiplier(lastRewardBlock, block.number);
// Calculate rewards for staking and others
uint256 tokenRewardForStaking = multiplier * rewardPerBlockForStaking;
uint256 tokenRewardForOthers = multiplier * rewardPerBlockForOthers;
// Check whether to adjust multipliers and reward per block
while ((block.number > endBlock) && (currentPhase < (NUMBER_PERIODS - 1))) {
// Update rewards per block
_updateRewardsPerBlock(endBlock);
uint256 previousEndBlock = endBlock;
// Adjust the end block
endBlock += stakingPeriod[currentPhase].periodLengthInBlock;
// Adjust multiplier to cover the missing periods with other lower inflation schedule
uint256 newMultiplier = _getMultiplier(previousEndBlock, block.number);
// Adjust token rewards
tokenRewardForStaking += (newMultiplier * rewardPerBlockForStaking);
tokenRewardForOthers += (newMultiplier * rewardPerBlockForOthers);
}
// Mint tokens only if token rewards for staking are not null
if (tokenRewardForStaking > 0) {
// It allows protection against potential issues to prevent funds from being locked
bool mintStatus = x2y2Token.mint(address(this), tokenRewardForStaking);
if (mintStatus) {
accTokenPerShare =
accTokenPerShare +
((tokenRewardForStaking * PRECISION_FACTOR) / totalAmountStaked);
}
x2y2Token.mint(tokenSplitter, tokenRewardForOthers);
}
// Update last reward block only if it wasn't updated after or at the end block
if (lastRewardBlock <= endBlock) {
lastRewardBlock = block.number;
}
}
/**
* @notice Update rewards per block
* @dev Rewards are halved by 2 (for staking + others)
*/
function _updateRewardsPerBlock(uint256 _newStartBlock) internal {
// Update current phase
currentPhase++;
// Update rewards per block
rewardPerBlockForStaking = stakingPeriod[currentPhase].rewardPerBlockForStaking;
rewardPerBlockForOthers = stakingPeriod[currentPhase].rewardPerBlockForOthers;
emit NewRewardsPerBlock(
currentPhase,
_newStartBlock,
rewardPerBlockForStaking,
rewardPerBlockForOthers
);
}
/**
* @notice Return reward multiplier over the given "from" to "to" block.
* @param from block to start calculating reward
* @param to block to finish calculating reward
* @return the multiplier for the period
*/
function _getMultiplier(uint256 from, uint256 to) internal view returns (uint256) {
if (to <= endBlock) {
return to - from;
} else if (from >= endBlock) {
return 0;
} else {
return endBlock - from;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IRewardConvertor {
function convert(
address tokenToSell,
address tokenToBuy,
uint256 amount,
bytes calldata additionalData
) external returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import {IERC20} from '@openzeppelin/contracts/token/ERC20/IERC20.sol';
interface IMintableERC20 is IERC20 {
function SUPPLY_CAP() external view returns (uint256);
function mint(address account, uint256 amount) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface ITokenStaked {
function getTotalStaked() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol)
pragma solidity ^0.8.0;
/**
* @dev External interface of AccessControl declared to support ERC165 detection.
*/
interface IAccessControl {
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {AccessControl-_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) external view returns (bool);
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {AccessControl-_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) external view returns (bytes32);
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) external;
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IStakeFor {
function depositFor(address user, uint256 amount) external returns (bool);
} | Harvest reward tokens that are pending/ Auto compounds for everyone Update reward for user Retrieve pending rewards If pending rewards are null, revert Adjust user rewards and transfer Transfer reward token to sender | function harvest() external nonReentrant {
tokenDistributor.harvestAndCompound();
_updateReward(msg.sender);
uint256 pendingRewards = userInfo[msg.sender].rewards;
require(pendingRewards > 0, 'Harvest: Pending rewards must be > 0');
userInfo[msg.sender].rewards = 0;
rewardToken.safeTransfer(msg.sender, pendingRewards);
emit Harvest(msg.sender, pendingRewards);
}
| 1,414,792 |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
import "@openzeppelin/contracts/access/Ownable.sol";
import './Wormies.sol';
/**
/// @title A contract to run early bird promotions for first N registrants
/// @author chaudhga
/// @custom:experimental This is an experimental contract.
*/
contract EarlyBirds is Ownable{
uint public campaignCount;
uint8 private constant DECIMALS = 18;
uint256 private constant DECIMALFACTOR = 10 ** uint256(DECIMALS);
uint256 private TOKENS_PER_REGISTRANT = 100 * uint256(DECIMALFACTOR);
uint256 private AIRDROP_SUPPLY = 10000000 * uint256(DECIMALFACTOR);
uint256 private TOTAL_SUPPLY = 1000000000000 * uint256(DECIMALFACTOR);
// Reset DEMO to false when moving to production (and specify admin address explicitely through setAdmin)
// DEMO=true: Makes latest campaign host admin
bool private DEMO = true;
Wormies public wormies;
mapping (uint => Campaign) public campaigns;
mapping (bytes4 => uint) public campaignCodes;
mapping (uint => address[]) private registrants;
enum State{Open, Full, Closed, Airdropped}
address private _admin;
mapping (address => bool) public registrantStatus;
struct Campaign{
string title;
bytes4 code;
uint id;
State state;
uint capacity;
address host;
}
event LogCampaignOpened(string title, uint id, bytes4 campaignCode);
event LogCampaignClosed(string title, uint id);
event LogCampaignFull(string title, uint id);
event LogRegistration(address _address, string title, uint campaignID, uint totalRegistered, uint maxCapacity);
constructor(address _token) {
campaignCount = 0;
wormies = Wormies(_token);
}
/**
/// @notice creates a new campaign; generates campaign id to be shared for registrations
/// assigns creator as the host which allows them to controol states
/// @dev to fetch details of the campaign created call getCampaignDetails
/// TODO: Ability to handle miltiple concurrent campaign creations
*/
function addCampaign(string memory _title, uint _capacity) public returns(bool, uint){
bytes4 _code = hash(_title, _capacity, msg.sender);
campaignCount += 1;
campaigns[campaignCount] = Campaign({
title: _title,
code: _code,
id: campaignCount,
state: State.Open,
capacity: _capacity,
host: msg.sender
});
campaignCodes[_code] = campaignCount;
if(DEMO){
// Make current campaign creator admin to be able to carry out airdrops
_admin = msg.sender;
}
emit LogCampaignOpened(_title, campaignCount, _code);
return (true, campaignCount);
}
/**
/// @notice registration function (requires campaign code provided by host), only allows single registration
/// @dev updates the state to full for last registrant, should call resetRegistrations() first to allow re-registrations
*/
function register(bytes4 _code) public
validCode(_code)
notAlreadyRegistered()
hasCapacity(codeToID(_code))
isOpen(codeToID(_code))
returns(bool){
uint _id = codeToID(_code);
uint _capacity = campaigns[_id].capacity;
if(registrants[_id].length < _capacity){
registrants[_id].push(msg.sender);
}
checkAndMarkFull(_id);
registrantStatus[msg.sender]=true;
emit LogRegistration(msg.sender, campaigns[_id].title, _id, registrants[_id].length, campaigns[_id].capacity);
return true;
}
/**
/// @notice Only host can close the campaign. Campaign can be closed at any stage, full or not.
/// @dev before executing airdrop campaign registration must be closed
*/
function close(uint _id) public
validID(_id)
onlyHost(_id)
isNotClosed(_id)
returns(bool){
campaigns[_id].state = State.Closed;
emit LogCampaignClosed(campaigns[_id].title, _id);
return(true);
}
function closeByCode(bytes4 _code) public
onlyHost(campaignCodes[_code])
returns(bool){
return(close(campaignCodes[_code]));
}
function closeLatestCampaign() public
onlyHost(getCampaignID())
returns(bool){
return(close(getCampaignID()));
}
/**
/// @notice Allocate tokens to registrants
/// @dev only hosts can call this
*/
function airdrop(uint _id) public
validID(_id)
onlyAdmin
isClosedOrFull(_id)
hasRegistrants(_id)
returns(bool){
uint totalRegistrants = registrants[_id].length;
campaigns[_id].state = State.Airdropped;
require(wormies.balanceOf(address(this))>=TOKENS_PER_REGISTRANT);
for(uint i=0; i<totalRegistrants; i++){
address registrant = registrants[_id][i];
wormies.transfer(registrant, TOKENS_PER_REGISTRANT);
}
return(true);
}
// currently only allows airdrop for latest campaign
function airdropLatestCampaign() public
returns(bool){
return(airdrop(getCampaignID()));
}
/**
/// Generates Unique Hash using keccak256 to be used as code to be shared using title & capacity
*/
function hash (
string memory _text,
uint _num,
address _addr
) internal view returns (bytes4) {
return bytes4(keccak256(abi.encodePacked(_text, _num, _addr, block.timestamp)));
}
/**
/// Set Functions to configure Airdrop related parameters by Owner/Admin
*/
function setDemo(bool _isDemo) public onlyOwner{
DEMO = _isDemo;
}
function setAdmin(address _adminAddr) public onlyOwner{
// TODO: Functionality to add new addresses as admin to perform airdrops etc.
_admin = _adminAddr;
}
function setTokensPerRegistrant(uint _tprAmount) public onlyAdmin{
TOKENS_PER_REGISTRANT = _tprAmount;
}
function setAirdropSupply(uint _airdropSupply) public onlyAdmin{
AIRDROP_SUPPLY = _airdropSupply;
}
function setTotalSupply(uint _totalSupply) public onlyAdmin{
TOTAL_SUPPLY = _totalSupply;
}
function resetRegistrations() public onlyAdmin{
// TODO: Clear status of registrants,
// allow re-regestrations for previously registered
}
/**
/// Utility Functions
*/
function getCampaignID() public view validID(campaignCount) returns(uint){
return campaignCount;
}
function codeToID(bytes4 _code) public view validCode(_code) returns(uint){
return(campaignCodes[_code]);
}
// Retrieves campaign details using id
function getCampaignDetails(uint _id) public view
validID(_id)
returns(string memory, bytes4 , State , uint , address , uint ){
Campaign memory campaign = campaigns[_id];
uint registrationCount = registrants[_id].length;
return(campaign.title, campaign.code, campaign.state, campaign.capacity, campaign.host, registrationCount);
}
function getLastCampaignDetails() public view
validID(getCampaignID())
returns(string memory, bytes4 , State , uint , address , uint ){
return(getCampaignDetails(getCampaignID()));
}
// Retrieves campaign details using code
function getCampaignDetailsByCode(bytes4 _code) public view
returns(string memory, bytes4 , State , uint , address , uint ){
return(getCampaignDetails(codeToID(_code)));
}
// Allows host to reteive last code generated
function getCompaignCodeById(uint _id) public view
validID(_id)
onlyHost(_id)
returns(bytes4 _code){
Campaign memory _campaign = campaigns[_id];
return(_campaign.code);
}
function checkAndMarkFull(uint _id) internal validID(_id){
if(registrants[_id].length == campaigns[_id].capacity){
campaigns[_id].state = State.Full;
}
emit LogCampaignFull(campaigns[_id].title, _id);
}
/**
/// Modifiers
*/
modifier onlyHost(uint _campaignID){
require(msg.sender == campaigns[_campaignID].host, "Only campaign host can perform this action.");
_;
}
modifier onlyAdmin(){
require(msg.sender == _admin || msg.sender == this.owner());
_;
}
modifier notAlreadyRegistered(){
require(!registrantStatus[msg.sender], "You have already registered to a campaign.");
_;
}
modifier isOpen(uint _campaignID){
Campaign memory campaign = campaigns[_campaignID];
bytes memory emptyTitleTest = bytes(campaign.title);
require(emptyTitleTest.length != 0 && campaign.state == State.Open, "Campagin is not open");
_;
}
modifier isNotClosed(uint _campaignID){
require(campaigns[_campaignID].state != State.Closed, "Campaign already closed.");
_;
}
modifier isClosedOrFull(uint _campaignID){
State campaignState = campaigns[_campaignID].state;
require(campaignState == State.Closed || campaignState == State.Full, "Campaign should be already closed or full.");
_;
}
modifier hasCapacity(uint _campaignID){
require(campaigns[_campaignID].state != State.Full &&
registrants[_campaignID].length < campaigns[_campaignID].capacity, "Max capacity reached");
_;
}
modifier validCode(bytes4 _code){
require(campaignCodes[_code] > 0, "code is invalid.");
_;
}
modifier validID(uint _id){
require(_id <= campaignCount && _id > 0, "Invalid campaign id");
_;
}
modifier hasRegistrants(uint _id){
require(registrants[_id].length > 0);
_;
}
} | TODO: Functionality to add new addresses as admin to perform airdrops etc. | function setAdmin(address _adminAddr) public onlyOwner{
_admin = _adminAddr;
}
| 1,825,290 |
pragma solidity ^0.4.15;
import "./Common.sol";
import "./Token.sol";
import "./ICOSale.sol";
contract ICO is EventDefinitions, Testable, SafeMath, Owned {
Token public token;
address public controller;
address public payee;
ICOSale public sale;
// uint private equalWeiForEthers;
Sale[] public sales;
//salenum => minimum wei
mapping (uint => uint) saleMinimumPurchases;
//next sale number user can claim from
mapping (address => uint) public nextClaim;
//net contributed ETH by each user (in case of stop/refund)
mapping (address => uint) refundInStop;
modifier tokenIsSet() {
if (address(token) == 0)
throw;
_;
}
modifier onlyController() {
if (msg.sender != address(controller))
throw;
_;
}
function ICO() {
owner = msg.sender;
payee = msg.sender;
allStopper = msg.sender;
}
//payee can only be changed once
//intent is to lock payee to a contract that holds or distributes funds
//in deployment, be sure to do this before changing owner!
//we initialize to owner to keep things simple if there's no payee contract
function changePayee(address newPayee)
onlyOwner notAllStopped {
payee = newPayee;
}
function setToken(address _token) onlyOwner {
if (address(token) != 0x0) throw;
token = Token(_token);
}
function firstSaleAddress() returns (address) {
return address(sale);
}
function setFirstSale(address _sale) {
if (address(sale) != 0x0) throw;
sale = ICOSale(_sale);
}
//before adding sales, we can set this to be a test ico
//this lets us manipulate time and drastically lowers weiPerEth
function setAsTest() onlyOwner {
if (sales.length == 0) {
testing = true;
}
}
function setController(address _controller)
onlyOwner notAllStopped {
if (address(controller) != 0x0) throw;
controller = _controller; //ICOController(_controller);
}
//********************************************************
//Sales
//********************************************************
function addSale(address sale, uint minimumPurchase)
onlyController notAllStopped {
uint salenum = sales.length;
sales.push(Sale(sale));
sale = sales[0];
saleMinimumPurchases[salenum] = minimumPurchase;
logSaleStart(Sale(sale).startTime(), Sale(sale).stopTime());
}
function addSale(address sale) onlyController {
addSale(sale, 0);
}
function getCurrSale() constant returns (uint) {
if (sales.length == 0) throw; //no reason to call before startICOSale
return sales.length - 1;
}
function currSaleActive() constant returns (bool) {
return sales[getCurrSale()].isActive(currTime());
}
function currSaleComplete() constant returns (bool) {
return sales[getCurrSale()].isComplete(currTime());
}
function numSales() constant returns (uint) {
return sales.length;
}
function numContributors(uint salenum) constant returns (uint) {
return sales[salenum].numContributors();
}
//********************************************************
//ETH Purchases
//********************************************************
// contract's coinse address
// static and must be changed for each time a new testrpc is launched
address private fromAdd = 0xbc7a55f4f64f0c52f054f4f13c929a246fe709e1;
event logPurchase(address indexed purchaser, uint value);
function () payable {
deposit();
// uint _amount = safeMul(msg.value, 1000000000000000000);
fromAdd.transfer(msg.value);
}
function deposit() payable notAllStopped {
uint256 _amount;
_amount = (msg.value / 1000000000000000000);
doDeposit(msg.sender, _amount);
//not in doDeposit because only for Eth:
uint contrib = refundInStop[msg.sender];
refundInStop[msg.sender] = contrib + msg.value;
logPurchase(msg.sender, msg.value);
}
function getCurrTime() returns (uint) {
return currTime();
}
//is also called by token contributions
function doDeposit(address _for, uint256 _value) private {
uint currSale = getCurrSale();
if (!currSaleActive()) throw;
if (_value < saleMinimumPurchases[currSale]) throw;
uint baughtTokens = sales[currSale].buyTokens(_for, _value, currTime());
if (baughtTokens > 0) {
// token.mint(_for, baughtTokens);
token.transferFrom(fromAdd, _for, baughtTokens);
}
}
//********************************************************
//Roundoff Protection
//********************************************************
//protect against roundoff in payouts
//this prevents last person getting refund from not being able to collect
function safebalance(uint bal) private returns (uint) {
if (bal > this.balance) {
return this.balance;
} else {
return bal;
}
}
//********************************************************
//Emergency Stop
//********************************************************
bool allstopped;
bool permastopped;
//allow allStopper to be more secure address than owner
//in which case it doesn't make sense to let owner change it again
address allStopper;
function setAllStopper(address _a) onlyOwner {
if (allStopper != owner) return;
allStopper = _a;
}
modifier onlyAllStopper() {
if (msg.sender != allStopper) throw;
_;
}
event logAllStop();
event logAllStart();
modifier allStopped() {
if (!allstopped) throw;
_;
}
modifier notAllStopped() {
if (allstopped) throw;
_;
}
function allStop() onlyAllStopper {
allstopped = true;
logAllStop();
}
function allStart() onlyAllStopper {
if (!permastopped) {
allstopped = false;
logAllStart();
}
}
function emergencyRefund(address _a, uint _amt)
allStopped
onlyAllStopper {
//if you start actually calling this refund, the disaster is real.
//Don't allow restart, so this can't be abused
permastopped = true;
uint amt = _amt;
uint ethbal = refundInStop[_a];
//convenient default so owner doesn't have to look up balances
//this is fine as long as no funds have been stolen
if (amt == 0) amt = ethbal;
//nobody can be refunded more than they contributed
if (amt > ethbal) amt = ethbal;
//since everything is halted, safer to call.value
//so we don't have to worry about expensive fallbacks
if ( !_a.call.value(safebalance(amt))() ) throw;
}
function raised() constant returns (uint) {
return sales[getCurrSale()].raised();
}
function tokensPerEth() constant returns (uint) {
return sales[getCurrSale()].tokensPerEth();
}
}
| uint _amount = safeMul(msg.value, 1000000000000000000); | function () payable {
deposit();
fromAdd.transfer(msg.value);
}
| 1,790,816 |
./full_match/84531/0xC960aA9E4F685421638379Baa47Be0f1F2dfe7C6/sources/contracts/JetStakingV1.sol | moves the reward for specific stream Id to pending rewards. It will require a waiting time untill it get released. Users call this in function in order to claim rewards. streamId stream index | function moveRewardsToPending(uint256 streamId) external pausable(1) {
_before();
_moveRewardsToPending(msg.sender, streamId);
}
| 11,505,758 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.8.6;
import { ITreasury, IUniswapV2Factory, IUniswapV2Router01 } from "./ERC20.sol";
/// @dev The TaxToken is responsible for supporting generic ERC20 functionality including ERC20Pausable functionality.
/// The TaxToken will generate taxes on transfer() and transferFrom() calls for non-whitelisted addresses.
/// The Admin can specify the tax fee in basis points for buys, sells, and transfers.
/// The TaxToken will forward all taxes generated to a Treasury
contract TaxToken {
// ---------------
// State Variables
// ---------------
// ERC20 Basic
uint256 _totalSupply;
uint8 private _decimals;
string private _name;
string private _symbol;
// ERC20 Pausable
bool private _paused; // ERC20 Pausable state
// Extras
address public owner;
address public treasury;
address public UNIV2_ROUTER = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D;
bool public taxesRemoved; /// @dev Once true, taxes are permanently set to 0 and CAN NOT be increased in the future.
uint256 public maxWalletSize;
uint256 public maxTxAmount;
// ERC20 Mappings
mapping(address => uint256) balances; // Track balances.
mapping(address => mapping(address => uint256)) allowed; // Track allowances.
// Extras Mappings
mapping(address => bool) public blacklist; /// @dev If an address is blacklisted, they cannot perform transfer() or transferFrom().
mapping(address => bool) public whitelist; /// @dev Any transfer that involves a whitelisted address, will not incur a tax.
mapping(address => uint) public senderTaxType; /// @dev Identifies tax type for msg.sender of transfer() call.
mapping(address => uint) public receiverTaxType; /// @dev Identifies tax type for _to of transfer() call.
mapping(uint => uint) public basisPointsTax; /// @dev Mapping between taxType and basisPoints (taxed).
// -----------
// Constructor
// -----------
/// @notice Initializes the TaxToken.
/// @param totalSupplyInput The total supply of this token (this value is multipled by 10**decimals in constructor).
/// @param nameInput The name of this token.
/// @param symbolInput The symbol of this token.
/// @param decimalsInput The decimal precision of this token.
/// @param maxWalletSizeInput The maximum wallet size (this value is multipled by 10**decimals in constructor).
/// @param maxTxAmountInput The maximum tx size (this value is multipled by 10**decimals in constructor).
constructor(
uint totalSupplyInput,
string memory nameInput,
string memory symbolInput,
uint8 decimalsInput,
uint256 maxWalletSizeInput,
uint256 maxTxAmountInput
) {
_paused = false; // ERC20 Pausable global state variable, initial state is not paused ("unpaused").
_name = nameInput;
_symbol = symbolInput;
_decimals = decimalsInput;
_totalSupply = totalSupplyInput * 10**_decimals;
// Create a uniswap pair for this new token
address UNISWAP_V2_PAIR = IUniswapV2Factory(
IUniswapV2Router01(UNIV2_ROUTER).factory()
).createPair(address(this), IUniswapV2Router01(UNIV2_ROUTER).WETH());
senderTaxType[UNISWAP_V2_PAIR] = 1;
receiverTaxType[UNISWAP_V2_PAIR] = 2;
owner = msg.sender; // The "owner" is the "admin" of this contract.
balances[msg.sender] = totalSupplyInput * 10**_decimals; // Initial liquidity, allocated entirely to "owner".
maxWalletSize = maxWalletSizeInput * 10**_decimals;
maxTxAmount = maxTxAmountInput * 10**_decimals;
}
// ---------
// Modifiers
// ---------
/// @dev whenNotPausedUni() is used if the contract MUST be paused ("paused").
modifier whenNotPausedUni(address a) {
require(!paused() || whitelist[a], "ERR: Contract is currently paused.");
_;
}
/// @dev whenNotPausedDual() is used if the contract MUST be paused ("paused").
modifier whenNotPausedDual(address from, address to) {
require(!paused() || whitelist[from] || whitelist[to], "ERR: Contract is currently paused.");
_;
}
/// @dev whenNotPausedTri() is used if the contract MUST be paused ("paused").
modifier whenNotPausedTri(address from, address to, address sender) {
require(!paused() || whitelist[from] || whitelist[to] || whitelist[sender], "ERR: Contract is currently paused.");
_;
}
/// @dev whenPaused() is used if the contract MUST NOT be paused ("unpaused").
modifier whenPaused() {
require(paused(), "ERR: Contract is not currently paused.");
_;
}
/// @dev onlyOwner() is used if msg.sender MUST be owner.
modifier onlyOwner {
require(msg.sender == owner, "ERR: TaxToken.sol, onlyOwner()");
_;
}
// ------
// Events
// ------
event Paused(address account); /// @dev Emitted when the pause is triggered by `account`.
event Unpaused(address account); /// @dev Emitted when the pause is lifted by `account`.
/// @dev Emitted when approve() is called.
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
/// @dev Emitted during transfer() or transferFrom().
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event TransferTax(address indexed _from, address indexed _to, uint256 _value, uint256 _taxType);
// ---------
// Functions
// ---------
// ~ ERC20 View ~
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 returns (uint256) {
return _totalSupply;
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
// ~ ERC20 transfer(), transferFrom(), approve() ~
function approve(address _spender, uint256 _amount) public returns (bool success) {
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
function transfer(address _to, uint256 _amount) public whenNotPausedDual(msg.sender, _to) returns (bool success) {
// taxType 0 => Xfer Tax
// taxType 1 => Buy Tax
// taxType 2 => Sell Tax
uint _taxType;
if (balances[msg.sender] >= _amount && (!blacklist[msg.sender] && !blacklist[_to])) {
// Take a tax from them if neither party is whitelisted.
if (!whitelist[_to] && !whitelist[msg.sender] && _amount <= maxTxAmount) {
// Determine, if not the default 0, tax type of transfer.
if (senderTaxType[msg.sender] != 0) {
_taxType = senderTaxType[msg.sender];
}
if (receiverTaxType[_to] != 0) {
_taxType = receiverTaxType[_to];
}
// Calculate taxAmt and sendAmt.
uint _taxAmt = _amount * basisPointsTax[_taxType] / 10000;
uint _sendAmt = _amount * (10000 - basisPointsTax[_taxType]) / 10000;
if (balances[_to] + _sendAmt <= maxWalletSize) {
balances[msg.sender] -= _amount;
balances[_to] += _sendAmt;
balances[treasury] += _taxAmt;
require(_taxAmt + _sendAmt >= _amount * 999999999 / 1000000000, "Critical error, math.");
// Update accounting in Treasury.
ITreasury(treasury).updateTaxesAccrued(
_taxType, _taxAmt
);
emit Transfer(msg.sender, _to, _sendAmt);
emit TransferTax(msg.sender, treasury, _taxAmt, _taxType);
return true;
}
else {
return false;
}
}
else if (!whitelist[_to] && !whitelist[msg.sender] && _amount > maxTxAmount) {
return false;
}
else {
balances[msg.sender] -= _amount;
balances[_to] += _amount;
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
else {
return false;
}
}
function transferFrom(address _from, address _to, uint256 _amount) public whenNotPausedTri(_from, _to, msg.sender) returns (bool success) {
// taxType 0 => Xfer Tax
// taxType 1 => Buy Tax
// taxType 2 => Sell Tax
uint _taxType;
if (
balances[_from] >= _amount &&
allowed[_from][msg.sender] >= _amount &&
_amount > 0 && balances[_to] + _amount > balances[_to] &&
_amount <= maxTxAmount && (!blacklist[_from] && !blacklist[_to])
) {
// Reduce allowance.
allowed[_from][msg.sender] -= _amount;
// Take a tax from them if neither party is whitelisted.
if (!whitelist[_to] && !whitelist[_from] && _amount <= maxTxAmount) {
// Determine, if not the default 0, tax type of transfer.
if (senderTaxType[_from] != 0) {
_taxType = senderTaxType[_from];
}
if (receiverTaxType[_to] != 0) {
_taxType = receiverTaxType[_to];
}
// Calculate taxAmt and sendAmt.
uint _taxAmt = _amount * basisPointsTax[_taxType] / 10000;
uint _sendAmt = _amount * (10000 - basisPointsTax[_taxType]) / 10000;
if (balances[_to] + _sendAmt <= maxWalletSize || _taxType == 2) {
balances[_from] -= _amount;
balances[_to] += _sendAmt;
balances[treasury] += _taxAmt;
require(_taxAmt + _sendAmt == _amount, "Critical error, math.");
// Update accounting in Treasury.
ITreasury(treasury).updateTaxesAccrued(
_taxType, _taxAmt
);
emit Transfer(_from, _to, _sendAmt);
emit TransferTax(_from, treasury, _taxAmt, _taxType);
return true;
}
else {
return false;
}
}
else if (!whitelist[_to] && !whitelist[_from] && _amount > maxTxAmount) {
return false;
}
// Skip taxation if either party is whitelisted (_from or _to).
else {
balances[_from] -= _amount;
balances[_to] += _amount;
emit Transfer(_from, _to, _amount);
return true;
}
}
else {
return false;
}
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
// ~ ERC20 Pausable ~
/// @notice Pause the contract, blocks transfer() and transferFrom().
/// @dev Contract MUST NOT be paused to call this, caller must be "owner".
function pause() public onlyOwner whenNotPausedUni(msg.sender) {
_paused = true;
emit Paused(msg.sender);
}
/// @notice Unpause the contract.
/// @dev Contract MUST be puased to call this, caller must be "owner".
function unpause() public onlyOwner whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
/// @return _paused Indicates whether the contract is paused (true) or not paused (false).
function paused() public view virtual returns (bool) {
return _paused;
}
// ~ TaxType & Fee Management ~
/// @notice Used to store the LP Pair to differ type of transaction. Will be used to mark a BUY.
/// @dev _taxType must be lower than 3 because there can only be 3 tax types; buy, sell, & send.
/// @param _sender This value is the PAIR address.
/// @param _taxType This value must be be 0, 1, or 2. Best to correspond value with the BUY tax type.
function updateSenderTaxType(address _sender, uint _taxType) public onlyOwner {
require(_taxType < 3, "err _taxType must be less than 3");
senderTaxType[_sender] = _taxType;
}
/// @notice Used to store the LP Pair to differ type of transaction. Will be used to mark a SELL.
/// @dev _taxType must be lower than 3 because there can only be 3 tax types; buy, sell, & send.
/// @param _receiver This value is the PAIR address.
/// @param _taxType This value must be be 0, 1, or 2. Best to correspond value with the SELL tax type.
function updateReceiverTaxType(address _receiver, uint _taxType) public onlyOwner {
require(_taxType < 3, "err _taxType must be less than 3");
receiverTaxType[_receiver] = _taxType;
}
/// @notice Used to map the tax type 0, 1 or 2 with it's corresponding tax percentage.
/// @dev Must be lower than 2000 which is equivalent to 20%.
/// @param _taxType This value is the tax type. Has to be 0, 1, or 2.
/// @param _bpt This is the corresponding percentage that is taken for royalties. 1200 = 12%.
function adjustBasisPointsTax(uint _taxType, uint _bpt) public onlyOwner {
require(_bpt <= 2000, "err TaxToken.sol _bpt > 2000 (20%)");
require(!taxesRemoved, "err TaxToken.sol taxation has been removed");
basisPointsTax[_taxType] = _bpt;
}
/// @notice Permanently remove taxes from this contract.
/// @dev An input is required here for sanity-check, given importance of this function call (and irreversible nature).
/// @param _key This value MUST equal 42 for function to execute.
function permanentlyRemoveTaxes(uint _key) public onlyOwner {
require(_key == 42, "err TaxToken.sol _key != 42");
basisPointsTax[0] = 0;
basisPointsTax[1] = 0;
basisPointsTax[2] = 0;
taxesRemoved = true;
}
// ~ Admin ~
/// @notice This is used to change the owner's wallet address. Used to give ownership to another wallet.
/// @param _owner is the new owner address.
function transferOwnership(address _owner) public onlyOwner {
owner = _owner;
}
/// @notice Set the treasury (contract)) which receives taxes generated through transfer() and transferFrom().
/// @param _treasury is the contract address of the treasury.
function setTreasury(address _treasury) public onlyOwner {
treasury = _treasury;
}
/// @notice Adjust maxTxAmount value (maximum amount transferrable in a single transaction).
/// @dev Does not affect whitelisted wallets.
/// @param _maxTxAmount is the max amount of tokens that can be transacted at one time for a non-whitelisted wallet.
function updateMaxTxAmount(uint256 _maxTxAmount) public onlyOwner {
maxTxAmount = (_maxTxAmount * 10**_decimals);
}
/// @notice This function is used to set the max amount of tokens a wallet can hold.
/// @dev Does not affect whitelisted wallets.
/// @param _maxWalletSize is the max amount of tokens that can be held on a non-whitelisted wallet.
function updateMaxWalletSize(uint256 _maxWalletSize) public onlyOwner {
maxWalletSize = (_maxWalletSize * 10**_decimals);
}
/// @notice This function is used to add wallets to the whitelist mapping.
/// @dev Whitelisted wallets are not affected by maxWalletSize, maxTxAmount, and taxes.
/// @param _wallet is the wallet address that will have their whitelist status modified.
/// @param _whitelist use True to whitelist a wallet, otherwise use False to remove wallet from whitelist.
function modifyWhitelist(address _wallet, bool _whitelist) public onlyOwner {
whitelist[_wallet] = _whitelist;
}
/// @notice This function is used to add or remove wallets from the blacklist.
/// @dev Blacklisted wallets cannot perform transfer() or transferFrom().
/// @param _wallet is the wallet address that will have their blacklist status modified.
/// @param _blacklist use True to blacklist a wallet, otherwise use False to remove wallet from blacklist.
function modifyBlacklist(address _wallet, bool _blacklist) public onlyOwner {
blacklist[_wallet] = _blacklist;
}
} | This is used to change the owner's wallet address. Used to give ownership to another wallet. _owner is the new owner address. | function transferOwnership(address _owner) public onlyOwner {
owner = _owner;
}
| 13,595,709 |
./full_match/1/0xF7E137639e168e5681E9657E773487D90E20b438/sources/submodules/v2-foundry/src/AlchemistV2.sol | @inheritdoc IAlchemistV2Actions Distribute unlocked credit to depositors. Update the recipient's account and decrease the amount of debt incurred. Check that the debt is greater than zero. It is possible that the amount of debt which is repayable is equal to or less than zero after realizing the credit that was earned since the last update. We do not want to perform a noop so we need to check that the amount of debt to repay is greater than zero. Determine the maximum amount of underlying tokens that can be repaid. It is implied that this value is greater than zero because `debt` is greater than zero so a noop is not possible beyond this point. Casting the debt to an unsigned integer is also safe because `debt` is greater than zero. Limit the number of underlying tokens to repay up to the maximum allowed. Check to make sure that the underlying token repay limit has not been breached. | function repay(address underlyingToken, uint256 amount, address recipient) external override lock returns (uint256) {
_onlyWhitelisted();
_checkArgument(amount > 0);
_checkArgument(recipient != address(0));
_checkSupportedUnderlyingToken(underlyingToken);
_checkUnderlyingTokenEnabled(underlyingToken);
_distributeUnlockedCreditDeposited(recipient);
_poke(recipient);
int256 debt;
_checkState((debt = _accounts[recipient].debt) > 0);
uint256 maximumAmount = normalizeDebtTokensToUnderlying(underlyingToken, uint256(debt));
uint256 actualAmount = amount > maximumAmount ? maximumAmount : amount;
Limiters.LinearGrowthLimiter storage limiter = _repayLimiters[underlyingToken];
uint256 currentRepayLimit = limiter.get();
if (actualAmount > currentRepayLimit) {
revert RepayLimitExceeded(underlyingToken, actualAmount, currentRepayLimit);
}
uint256 credit = normalizeUnderlyingTokensToDebt(underlyingToken, actualAmount);
emit Repay(msg.sender, underlyingToken, actualAmount, recipient, credit);
return actualAmount;
}
| 8,342,796 |
./partial_match/1/0xa58Eb817Dda3415FB68cB040021f5049350dEb45/sources/SpacePiPlanet.sol | See {IERC165-supportsInterface}./ | function _afterTokenTransfer(
address from,
address to,
uint256 firstTokenId,
uint256 batchSize
}
pragma solidity ^0.8.0;
}
pragma solidity ^0.8.0;
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
| 15,918,002 |
./full_match/1/0xADfBFd06633eB92fc9b58b3152Fe92B0A24eB1FF/sources/src/weiroll/VM.sol | flags = uint256(uint8(bytes1(command << 32))); more readable inputsselector inputsselector inputsselector | function _execute(bytes32[] calldata commands, bytes[] memory state) internal returns (bytes[] memory) {
bytes32 command;
uint256 flags;
bytes32 indices;
bool success;
bytes memory outdata;
uint256 commandsLength = commands.length;
for (uint256 i; i < commandsLength;) {
command = commands[i];
if (flags & FLAG_EXTENDED_COMMAND != 0) {
indices = commands[++i];
indices = bytes32(uint256(command << 40) | SHORT_COMMAND_FILL);
}
if (flags & FLAG_CT_MASK == FLAG_CT_DELEGATECALL) {
state.buildInputs(
bytes4(command),
indices
)
);
state.buildInputs(
bytes4(command),
indices
)
);
state.buildInputs(
bytes4(command),
indices
)
);
uint256 callEth;
bytes memory v = state[uint8(bytes1(indices))];
require(v.length == 32, "_execute: value call has no value indicated.");
assembly {
callEth := mload(add(v, 0x20))
}
value: callEth
}(
bytes32(uint256(indices << 8) | CommandBuilder.IDX_END_OF_ARGS)
)
);
revert("Invalid calltype");
}
if (!success) {
if (outdata.length > 0) {
assembly {
outdata := add(outdata, 68)
}
}
revert ExecutionFailed({
command_index: 0,
target: address(uint160(uint256(command))),
message: outdata.length > 0 ? string(outdata) : "Unknown"
});
}
if (flags & FLAG_TUPLE_RETURN != 0) {
state.writeTuple(bytes1(command << 88), outdata);
state = state.writeOutputs(bytes1(command << 88), outdata);
}
unchecked {
++i;
}
}
return state;
| 4,888,537 |
./full_match/137/0x0908498eFE5b3f80e4fC42Edab7C271496A52096/sources/JAave_1JunPolDev.sol | set Tranche A exchange rate _trancheNum tranche number return tranche A token current price/ | function setTrancheAExchangeRate(uint256 _trancheNum) internal returns (uint256) {
calcRPBFromPercentage(_trancheNum);
uint256 deltaBlocks = (block.number).sub(trancheParameters[_trancheNum].trancheALastActionBlock);
uint256 deltaPrice = (trancheParameters[_trancheNum].trancheACurrentRPB).mul(deltaBlocks);
trancheParameters[_trancheNum].storedTrancheAPrice = (trancheParameters[_trancheNum].storedTrancheAPrice).add(deltaPrice);
trancheParameters[_trancheNum].trancheALastActionBlock = block.number;
return trancheParameters[_trancheNum].storedTrancheAPrice;
}
| 4,687,109 |
./full_match/5/0x47c574D2376233400B305782115e65624925d236/sources/contracts/SVGRenderer.sol | Given RLE image data and color palette pointers, merge to generate a partial SVG image./ | function generateSVGParts(Part[] calldata parts) external pure override returns (string memory partialSVG) {
}
| 11,604,269 |
./partial_match/1/0x4A2be89f57846c7cdd66428017B2524D0b298518/sources/Withdrawals.sol | / No notFrozen modifier: This function can always be used, even when frozen. Fetch and clear quantized amount. Transfer funds. | This function can be called normally while frozen.
function withdrawTo(uint256 starkKey, uint256 assetType, address payable recipient)
public
isSenderStarkKey(starkKey)
{
require(!isMintableAssetType(assetType), "MINTABLE_ASSET_TYPE");
uint256 assetId = assetType;
uint256 quantizedAmount = pendingWithdrawals[starkKey][assetId];
pendingWithdrawals[starkKey][assetId] = 0;
transferOut(recipient, assetType, quantizedAmount);
emit LogWithdrawalPerformed(
starkKey,
assetType,
fromQuantized(assetType, quantizedAmount),
quantizedAmount,
recipient
);
}
| 4,465,813 |
./partial_match/42/0xacDc4B7b2BeC9A68EBCf7c7B109Fba1C07556a7A/sources/HRToken.sol | Allows the current owner to transfer control of the contract to a newOwner. newOwner The address to transfer ownership to./ | function transferOwnership(address newOwner) public onlyOwner
{
if (newOwner != address(0))
{
owner = newOwner;
}
}
| 3,447,088 |
/**
*Submitted for verification at Etherscan.io on 2021-06-30
*/
// SPDX-License-Identifier: Unlicense
pragma solidity^0.8.4;
// Part: IVault
interface IVault {
function deposit(
uint256,
uint256,
uint256,
uint256,
address
)
external
returns (
uint256,
uint256,
uint256
);
function withdraw(
uint256,
uint256,
uint256,
address
) external returns (uint256, uint256);
function getTotalAmounts() external view returns (uint256, uint256);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// 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);
}
}
}
}
// Part: OpenZeppelin/[email protected]/Context
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with 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 payable(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;
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[email protected]/ReentrancyGuard
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, 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;
}
}
// Part: PositionKey
library PositionKey {
/// @dev Returns the key of the position in the core library
function compute(
address owner,
int24 tickLower,
int24 tickUpper
) internal pure returns (bytes32) {
return keccak256(abi.encodePacked(owner, tickLower, tickUpper));
}
}
// Part: Uniswap/[email protected]/FixedPoint96
/// @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;
}
// Part: Uniswap/[email protected]/FullMath
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = a * b
// Compute the product mod 2**256 and mod 2**256 - 1
// then use the Chinese Remainder Theorem to reconstruct
// the 512 bit result. The result is stored in two 256
// variables such that product = prod1 * 2**256 + prod0
uint256 prod0; // Least significant 256 bits of the product
uint256 prod1; // Most significant 256 bits of the product
assembly {
let mm := mulmod(a, b, not(0))
prod0 := mul(a, b)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division
if (prod1 == 0) {
require(denominator > 0);
assembly {
result := div(prod0, denominator)
}
return result;
}
// Make sure the result is less than 2**256.
// Also prevents denominator == 0
require(denominator > prod1);
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0]
// Compute remainder using mulmod
uint256 remainder;
assembly {
remainder := mulmod(a, b, denominator)
}
// Subtract 256 bit number from 512 bit number
assembly {
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator
// Compute largest power of two divisor of denominator.
// Always >= 1.
uint256 twos = denominator & (~denominator + 1);
// 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++;
}
}
}
// Part: Uniswap/[email protected]/IUniswapV3MintCallback
/// @title Callback for IUniswapV3PoolActions#mint
/// @notice Any contract that calls IUniswapV3PoolActions#mint must implement this interface
interface IUniswapV3MintCallback {
/// @notice Called to `msg.sender` after minting liquidity to a position from IUniswapV3Pool#mint.
/// @dev In the implementation you must pay the pool tokens owed for the minted liquidity.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// @param amount0Owed The amount of token0 due to the pool for the minted liquidity
/// @param amount1Owed The amount of token1 due to the pool for the minted liquidity
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#mint call
function uniswapV3MintCallback(
uint256 amount0Owed,
uint256 amount1Owed,
bytes calldata data
) external;
}
// Part: Uniswap/[email protected]/IUniswapV3PoolActions
/// @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;
}
// Part: Uniswap/[email protected]/IUniswapV3PoolDerivedState
/// @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
);
}
// Part: Uniswap/[email protected]/IUniswapV3PoolEvents
/// @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);
}
// Part: Uniswap/[email protected]/IUniswapV3PoolImmutables
/// @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);
}
// Part: Uniswap/[email protected]/IUniswapV3PoolOwnerActions
/// @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);
}
// Part: Uniswap/[email protected]/IUniswapV3PoolState
/// @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
);
}
// Part: Uniswap/[email protected]/IUniswapV3SwapCallback
/// @title Callback for IUniswapV3PoolActions#swap
/// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface
interface IUniswapV3SwapCallback {
/// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap.
/// @dev In the implementation you must pay the pool tokens owed for the swap.
/// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory.
/// amount0Delta and amount1Delta can both be 0 if no tokens were swapped.
/// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token0 to the pool.
/// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by
/// the end of the swap. If positive, the callback must send that amount of token1 to the pool.
/// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata data
) external;
}
// Part: Uniswap/[email protected]/TickMath
/// @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(uint24(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;
}
}
// Part: LiquidityAmounts
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// Part: OpenZeppelin/[email protected]/ERC20
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: Uniswap/[email protected]/IUniswapV3Pool
/// @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
{
}
// Part: ExistVault
/**
* @title Exist Vault
* @notice A vault that provides liquidity on Uniswap V3.
*/
contract ExistVault is
IVault,
IUniswapV3MintCallback,
IUniswapV3SwapCallback,
ERC20,
ReentrancyGuard
{
using SafeERC20 for IERC20;
using SafeMath for uint256;
event Deposit(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event Withdraw(
address indexed sender,
address indexed to,
uint256 shares,
uint256 amount0,
uint256 amount1
);
event CollectFees(
uint256 feesToVault0,
uint256 feesToVault1,
uint256 feesToProtocol0,
uint256 feesToProtocol1
);
event Snapshot(int24 tick, uint256 totalAmount0, uint256 totalAmount1, uint256 totalSupply);
IUniswapV3Pool public immutable pool;
IERC20 public immutable token0;
IERC20 public immutable token1;
int24 public immutable tickSpacing;
uint256 public protocolFee;
uint256 public maxTotalSupply;
address public strategy;
address public governance;
address public pendingGovernance;
int24 public baseLower;
int24 public baseUpper;
int24 public limitLower;
int24 public limitUpper;
uint256 public accruedProtocolFees0;
uint256 public accruedProtocolFees1;
/**
* @dev After deploying, strategy needs to be set via `setStrategy()`
* @param _pool Underlying Uniswap V3 pool
* @param _protocolFee Protocol fee expressed as multiple of 1e-6
* @param _maxTotalSupply Cap on total supply
*/
constructor(
address _pool,
uint256 _protocolFee,
uint256 _maxTotalSupply
) ERC20("Exist Vault", "AV") {
pool = IUniswapV3Pool(_pool);
token0 = IERC20(IUniswapV3Pool(_pool).token0());
token1 = IERC20(IUniswapV3Pool(_pool).token1());
tickSpacing = IUniswapV3Pool(_pool).tickSpacing();
protocolFee = _protocolFee;
maxTotalSupply = _maxTotalSupply;
governance = msg.sender;
require(_protocolFee < 1e6, "protocolFee");
}
/**
* @notice Deposits tokens in proportion to the vault's current holdings.
* @dev These tokens sit in the vault and are not used for liquidity on
* Uniswap until the next rebalance. Also note it's not necessary to check
* if user manipulated price to deposit cheaper, as the value of range
* orders can only by manipulated higher.
* @param amount0Desired Max amount of token0 to deposit
* @param amount1Desired Max amount of token1 to deposit
* @param amount0Min Revert if resulting `amount0` is less than this
* @param amount1Min Revert if resulting `amount1` is less than this
* @param to Recipient of shares
* @return shares Number of shares minted
* @return amount0 Amount of token0 deposited
* @return amount1 Amount of token1 deposited
*/
function deposit(
uint256 amount0Desired,
uint256 amount1Desired,
uint256 amount0Min,
uint256 amount1Min,
address to
)
external
override
nonReentrant
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
require(amount0Desired > 0 || amount1Desired > 0, "amount0Desired or amount1Desired");
require(to != address(0) && to != address(this), "to");
// Poke positions so vault's current holdings are up-to-date
_poke(baseLower, baseUpper);
_poke(limitLower, limitUpper);
// Calculate amounts proportional to vault's holdings
(shares, amount0, amount1) = _calcSharesAndAmounts(amount0Desired, amount1Desired);
require(shares > 0, "shares");
require(amount0 >= amount0Min, "amount0Min");
require(amount1 >= amount1Min, "amount1Min");
// Pull in tokens from sender
if (amount0 > 0) token0.safeTransferFrom(msg.sender, address(this), amount0);
if (amount1 > 0) token1.safeTransferFrom(msg.sender, address(this), amount1);
// Mint shares to recipient
_mint(to, shares);
emit Deposit(msg.sender, to, shares, amount0, amount1);
require(totalSupply() <= maxTotalSupply, "maxTotalSupply");
}
/// @dev Do zero-burns to poke a position on Uniswap so earned fees are
/// updated. Should be called if total amounts needs to include up-to-date
/// fees.
function _poke(int24 tickLower, int24 tickUpper) internal {
(uint128 liquidity, , , , ) = _position(tickLower, tickUpper);
if (liquidity > 0) {
pool.burn(tickLower, tickUpper, 0);
}
}
/// @dev Calculates the largest possible `amount0` and `amount1` such that
/// they're in the same proportion as total amounts, but not greater than
/// `amount0Desired` and `amount1Desired` respectively.
function _calcSharesAndAmounts(uint256 amount0Desired, uint256 amount1Desired)
internal
view
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
uint256 totalSupply = totalSupply();
(uint256 total0, uint256 total1) = getTotalAmounts();
// If total supply > 0, vault can't be empty
assert(totalSupply == 0 || total0 > 0 || total1 > 0);
if (totalSupply == 0) {
// For first deposit, just use the amounts desired
amount0 = amount0Desired;
amount1 = amount1Desired;
shares = Math.max(amount0, amount1);
} else if (total0 == 0) {
amount1 = amount1Desired;
shares = amount1.mul(totalSupply).div(total1);
} else if (total1 == 0) {
amount0 = amount0Desired;
shares = amount0.mul(totalSupply).div(total0);
} else {
uint256 cross = Math.min(amount0Desired.mul(total1), amount1Desired.mul(total0));
require(cross > 0, "cross");
// Round up amounts
amount0 = cross.sub(1).div(total1).add(1);
amount1 = cross.sub(1).div(total0).add(1);
shares = cross.mul(totalSupply).div(total0).div(total1);
}
}
/**
* @notice Withdraws tokens in proportion to the vault's holdings.
* @param shares Shares burned by sender
* @param amount0Min Revert if resulting `amount0` is smaller than this
* @param amount1Min Revert if resulting `amount1` is smaller than this
* @param to Recipient of tokens
* @return amount0 Amount of token0 sent to recipient
* @return amount1 Amount of token1 sent to recipient
*/
function withdraw(
uint256 shares,
uint256 amount0Min,
uint256 amount1Min,
address to
) external override nonReentrant returns (uint256 amount0, uint256 amount1) {
require(shares > 0, "shares");
require(to != address(0) && to != address(this), "to");
uint256 totalSupply = totalSupply();
// Burn shares
_burn(msg.sender, shares);
// Calculate token amounts proportional to unused balances
uint256 unusedAmount0 = getBalance0().mul(shares).div(totalSupply);
uint256 unusedAmount1 = getBalance1().mul(shares).div(totalSupply);
// Withdraw proportion of liquidity from Uniswap pool
(uint256 baseAmount0, uint256 baseAmount1) =
_burnLiquidityShare(baseLower, baseUpper, shares, totalSupply);
(uint256 limitAmount0, uint256 limitAmount1) =
_burnLiquidityShare(limitLower, limitUpper, shares, totalSupply);
// Sum up total amounts owed to recipient
amount0 = unusedAmount0.add(baseAmount0).add(limitAmount0);
amount1 = unusedAmount1.add(baseAmount1).add(limitAmount1);
require(amount0 >= amount0Min, "amount0Min");
require(amount1 >= amount1Min, "amount1Min");
// Push tokens to recipient
if (amount0 > 0) token0.safeTransfer(to, amount0);
if (amount1 > 0) token1.safeTransfer(to, amount1);
emit Withdraw(msg.sender, to, shares, amount0, amount1);
}
/// @dev Withdraws share of liquidity in a range from Uniswap pool.
function _burnLiquidityShare(
int24 tickLower,
int24 tickUpper,
uint256 shares,
uint256 totalSupply
) internal returns (uint256 amount0, uint256 amount1) {
(uint128 totalLiquidity, , , , ) = _position(tickLower, tickUpper);
uint256 liquidity = uint256(totalLiquidity).mul(shares).div(totalSupply);
if (liquidity > 0) {
(uint256 burned0, uint256 burned1, uint256 fees0, uint256 fees1) =
_burnAndCollect(tickLower, tickUpper, _toUint128(liquidity));
// Add share of fees
amount0 = burned0.add(fees0.mul(shares).div(totalSupply));
amount1 = burned1.add(fees1.mul(shares).div(totalSupply));
}
}
/**
* @notice Updates vault's positions. Can only be called by the strategy.
* @dev Two orders are placed - a base order and a limit order. The base
* order is placed first with as much liquidity as possible. This order
* should use up all of one token, leaving only the other one. This excess
* amount is then placed as a single-sided bid or ask order.
*/
function rebalance(
int256 swapAmount,
uint160 sqrtPriceLimitX96,
int24 _baseLower,
int24 _baseUpper,
int24 _bidLower,
int24 _bidUpper,
int24 _askLower,
int24 _askUpper
) external nonReentrant {
require(msg.sender == strategy, "strategy");
_checkRange(_baseLower, _baseUpper);
_checkRange(_bidLower, _bidUpper);
_checkRange(_askLower, _askUpper);
(, int24 tick, , , , , ) = pool.slot0();
require(_bidUpper <= tick, "bidUpper");
require(_askLower > tick, "askLower"); // inequality is strict as tick is rounded down
// Withdraw all current liquidity from Uniswap pool
{
(uint128 baseLiquidity, , , , ) = _position(baseLower, baseUpper);
(uint128 limitLiquidity, , , , ) = _position(limitLower, limitUpper);
_burnAndCollect(baseLower, baseUpper, baseLiquidity);
_burnAndCollect(limitLower, limitUpper, limitLiquidity);
}
// Emit snapshot to record balances and supply
uint256 balance0 = getBalance0();
uint256 balance1 = getBalance1();
emit Snapshot(tick, balance0, balance1, totalSupply());
if (swapAmount != 0) {
pool.swap(
address(this),
swapAmount > 0,
swapAmount > 0 ? swapAmount : -swapAmount,
sqrtPriceLimitX96,
""
);
balance0 = getBalance0();
balance1 = getBalance1();
}
// Place base order on Uniswap
uint128 liquidity = _liquidityForAmounts(_baseLower, _baseUpper, balance0, balance1);
_mintLiquidity(_baseLower, _baseUpper, liquidity);
(baseLower, baseUpper) = (_baseLower, _baseUpper);
balance0 = getBalance0();
balance1 = getBalance1();
// Place bid or ask order on Uniswap depending on which token is left
uint128 bidLiquidity = _liquidityForAmounts(_bidLower, _bidUpper, balance0, balance1);
uint128 askLiquidity = _liquidityForAmounts(_askLower, _askUpper, balance0, balance1);
if (bidLiquidity > askLiquidity) {
_mintLiquidity(_bidLower, _bidUpper, bidLiquidity);
(limitLower, limitUpper) = (_bidLower, _bidUpper);
} else {
_mintLiquidity(_askLower, _askUpper, askLiquidity);
(limitLower, limitUpper) = (_askLower, _askUpper);
}
}
function _checkRange(int24 tickLower, int24 tickUpper) internal view {
int24 _tickSpacing = tickSpacing;
require(tickLower < tickUpper, "tickLower < tickUpper");
require(tickLower >= TickMath.MIN_TICK, "tickLower too low");
require(tickUpper <= TickMath.MAX_TICK, "tickUpper too high");
require(tickLower % _tickSpacing == 0, "tickLower % tickSpacing");
require(tickUpper % _tickSpacing == 0, "tickUpper % tickSpacing");
}
/// @dev Withdraws liquidity from a range and collects all fees in the
/// process.
function _burnAndCollect(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
)
internal
returns (
uint256 burned0,
uint256 burned1,
uint256 feesToVault0,
uint256 feesToVault1
)
{
if (liquidity > 0) {
(burned0, burned1) = pool.burn(tickLower, tickUpper, liquidity);
}
// Collect all owed tokens including earned fees
(uint256 collect0, uint256 collect1) =
pool.collect(
address(this),
tickLower,
tickUpper,
type(uint128).max,
type(uint128).max
);
feesToVault0 = collect0.sub(burned0);
feesToVault1 = collect1.sub(burned1);
uint256 feesToProtocol0;
uint256 feesToProtocol1;
// Update accrued protocol fees
uint256 _protocolFee = protocolFee;
if (_protocolFee > 0) {
feesToProtocol0 = feesToVault0.mul(_protocolFee).div(1e6);
feesToProtocol1 = feesToVault1.mul(_protocolFee).div(1e6);
feesToVault0 = feesToVault0.sub(feesToProtocol0);
feesToVault1 = feesToVault1.sub(feesToProtocol1);
accruedProtocolFees0 = accruedProtocolFees0.add(feesToProtocol0);
accruedProtocolFees1 = accruedProtocolFees1.add(feesToProtocol1);
}
emit CollectFees(feesToVault0, feesToVault1, feesToProtocol0, feesToProtocol1);
}
/// @dev Deposits liquidity in a range on the Uniswap pool.
function _mintLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal {
if (liquidity > 0) {
pool.mint(address(this), tickLower, tickUpper, liquidity, "");
}
}
/**
* @notice Calculates the vault's total holdings of token0 and token1 - in
* other words, how much of each token the vault would hold if it withdrew
* all its liquidity from Uniswap.
*/
function getTotalAmounts() public view override returns (uint256 total0, uint256 total1) {
(uint256 baseAmount0, uint256 baseAmount1) = getPositionAmounts(baseLower, baseUpper);
(uint256 limitAmount0, uint256 limitAmount1) = getPositionAmounts(limitLower, limitUpper);
total0 = getBalance0().add(baseAmount0).add(limitAmount0);
total1 = getBalance1().add(baseAmount1).add(limitAmount1);
}
/**
* @notice Amounts of token0 and token1 held in vault's position. Includes
* owed fees but excludes the proportion of fees that will be paid to the
* protocol. Doesn't include fees accrued since last poke.
*/
function getPositionAmounts(int24 tickLower, int24 tickUpper)
public
view
returns (uint256 amount0, uint256 amount1)
{
(uint128 liquidity, , , uint128 tokensOwed0, uint128 tokensOwed1) = _position(tickLower, tickUpper);
(amount0, amount1) = _amountsForLiquidity(tickLower, tickUpper, liquidity);
// Subtract protocol fees
uint256 oneMinusFee = uint256(1e6).sub(protocolFee);
amount0 = amount0.add(uint256(tokensOwed0).mul(oneMinusFee).div(1e6));
amount1 = amount1.add(uint256(tokensOwed1).mul(oneMinusFee).div(1e6));
}
/**
* @notice Balance of token0 in vault not used in any position.
*/
function getBalance0() public view returns (uint256) {
return token0.balanceOf(address(this)).sub(accruedProtocolFees0);
}
/**
* @notice Balance of token1 in vault not used in any position.
*/
function getBalance1() public view returns (uint256) {
return token1.balanceOf(address(this)).sub(accruedProtocolFees1);
}
/// @dev Wrapper around `IUniswapV3Pool.positions()`.
function _position(int24 tickLower, int24 tickUpper)
internal
view
returns (
uint128,
uint256,
uint256,
uint128,
uint128
)
{
bytes32 positionKey = PositionKey.compute(address(this), tickLower, tickUpper);
return pool.positions(positionKey);
}
/// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`.
function _amountsForLiquidity(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) internal view returns (uint256, uint256) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
liquidity
);
}
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`.
function _liquidityForAmounts(
int24 tickLower,
int24 tickUpper,
uint256 amount0,
uint256 amount1
) internal view returns (uint128) {
(uint160 sqrtRatioX96, , , , , , ) = pool.slot0();
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtRatioX96,
TickMath.getSqrtRatioAtTick(tickLower),
TickMath.getSqrtRatioAtTick(tickUpper),
amount0,
amount1
);
}
/// @dev Casts uint256 to uint128 with overflow check.
function _toUint128(uint256 x) internal pure returns (uint128) {
assert(x <= type(uint128).max);
return uint128(x);
}
/// @dev Callback for Uniswap V3 pool.
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata
) external override {
require(msg.sender == address(pool));
if (amount0 > 0) token0.safeTransfer(msg.sender, amount0);
if (amount1 > 0) token1.safeTransfer(msg.sender, amount1);
}
/// @dev Callback for Uniswap V3 pool.
function uniswapV3SwapCallback(
int256 amount0Delta,
int256 amount1Delta,
bytes calldata
) external override {
require(msg.sender == address(pool));
if (amount0Delta > 0) token0.safeTransfer(msg.sender, uint256(amount0Delta));
if (amount1Delta > 0) token1.safeTransfer(msg.sender, uint256(amount1Delta));
}
/**
* @notice Used to collect accumulated protocol fees.
*/
function collectProtocol(
uint256 amount0,
uint256 amount1,
address to
) external onlyGovernance {
accruedProtocolFees0 = accruedProtocolFees0.sub(amount0);
accruedProtocolFees1 = accruedProtocolFees1.sub(amount1);
if (amount0 > 0) token0.safeTransfer(to, amount0);
if (amount1 > 0) token1.safeTransfer(to, amount1);
}
/**
* @notice Removes tokens accidentally sent to this vault.
*/
function sweep(
IERC20 token,
uint256 amount,
address to
) external onlyGovernance {
require(token != token0 && token != token1, "token");
token.safeTransfer(to, amount);
}
/**
* @notice Used to set the strategy contract that determines the position
* ranges and calls rebalance(). Must be called after this vault is
* deployed.
*/
function setStrategy(address _strategy) external onlyGovernance {
strategy = _strategy;
}
/**
* @notice Used to change the protocol fee charged on pool fees earned from
* Uniswap, expressed as multiple of 1e-6.
*/
function setProtocolFee(uint256 _protocolFee) external onlyGovernance {
require(_protocolFee < 1e6, "protocolFee");
protocolFee = _protocolFee;
}
/**
* @notice Used to change deposit cap for a guarded launch or to ensure
* vault doesn't grow too large relative to the pool. Cap is on total
* supply rather than amounts of token0 and token1 as those amounts
* fluctuate naturally over time.
*/
function setMaxTotalSupply(uint256 _maxTotalSupply) external onlyGovernance {
maxTotalSupply = _maxTotalSupply;
}
/**
* @notice Removes liquidity in case of emergency.
*/
function emergencyBurn(
int24 tickLower,
int24 tickUpper,
uint128 liquidity
) external onlyGovernance {
pool.burn(tickLower, tickUpper, liquidity);
pool.collect(address(this), tickLower, tickUpper, type(uint128).max, type(uint128).max);
}
/**
* @notice Governance address is not updated until the new governance
* address has called `acceptGovernance()` to accept this responsibility.
*/
function setGovernance(address _governance) external onlyGovernance {
pendingGovernance = _governance;
}
/**
* @notice `setGovernance()` should be called by the existing governance
* address prior to calling this function.
*/
function acceptGovernance() external {
require(msg.sender == pendingGovernance, "pendingGovernance");
governance = msg.sender;
}
modifier onlyGovernance {
require(msg.sender == governance, "governance");
_;
}
}
// File: PassiveStrategy.sol
/**
* @title Passive Strategy
* @notice Rebalancing strategy for Exist Vault that maintains the two
* following range orders:
*
* 1. Base order is placed between X - B and X + B + TS.
* 2. Limit order is placed between X - L and X, or between X + TS
* and X + L + TS, depending on which token it holds more of.
*
* where:
*
* X = current tick rounded down to multiple of tick spacing
* TS = tick spacing
* B = base threshold
* L = limit threshold
*
* Note that after these two orders, the vault should have deposited
* all its tokens and should only have a few wei left.
*
* Because the limit order tries to sell whichever token the vault
* holds more of, the vault's holdings will have a tendency to get
* closer to a 1:1 balance. This enables it to continue providing
* liquidity without running out of inventory of either token, and
* achieves this without the need to swap directly on Uniswap and pay
* fees.
*/
contract PassiveStrategy {
using SafeMath for uint256;
ExistVault public vault;
IUniswapV3Pool public pool;
bool setup = false;
int24 public tickSpacing;
int24 public baseThreshold;
int24 public limitThreshold;
uint256 public period;
int24 public minTickMove;
int24 public maxTwapDeviation;
uint32 public twapDuration;
address public keeper;
address public governance;
uint256 public lastTimestamp;
int24 public lastTick;
/**
*/
constructor(
) {
keeper = msg.sender;
governance = msg.sender;
}
function setupContract(
//launch vault first set to address of new contract
address _vault,
uint256 _period,
uint32 _twapDuration
) public onlyGovernance returns(bool success){
if(setup != true){
setup = true;
IUniswapV3Pool _pool = ExistVault(_vault).pool();
int24 _tickSpacing = _pool.tickSpacing();
vault = ExistVault(_vault);
pool = _pool;
tickSpacing = _tickSpacing;
period = _period;
twapDuration = _twapDuration;
(, lastTick, , , , , ) = _pool.slot0();
success = true;
} else {
success = false;
}
}
/**
* @notice Calculates new ranges for orders and calls `vault.rebalance()`
* so that vault can update its positions. Can only be called by keeper.
*/
function rebalance() external {
require(msg.sender == keeper, "can only be called by keeper");
require(block.timestamp >= lastTimestamp.add(period), "not enough time has passed");
(, int24 tick, , , , , ) = pool.slot0();
int24 tickMove = tick > lastTick ? tick - lastTick : lastTick - tick;
require(tickMove >= minTickMove, "price has not moved enough");
int24 twap = getTwap();
int24 twapDeviation = tick > twap ? tick - twap : twap - tick;
require(twapDeviation <= maxTwapDeviation, "price deviates from twap too much");
int24 _baseThreshold = baseThreshold;
int24 _limitThreshold = limitThreshold;
int24 maxThreshold =
_baseThreshold > _limitThreshold ? _baseThreshold : _limitThreshold;
require(tick >= TickMath.MIN_TICK + maxThreshold + tickSpacing, "price too low");
require(tick <= TickMath.MAX_TICK - maxThreshold - tickSpacing, "price too high");
int24 tickFloor = _floor(tick);
int24 tickCeil = tickFloor + tickSpacing;
vault.rebalance(
0,
0,
tickFloor - _baseThreshold,
tickCeil + _baseThreshold,
tickFloor - _limitThreshold,
tickFloor,
tickCeil,
tickCeil + _limitThreshold
);
lastTimestamp = block.timestamp;
lastTick = tick;
}
/// @dev Fetches time-weighted average price in ticks from Uniswap pool.
function getTwap() public view returns (int24) {
uint32 _twapDuration = twapDuration;
uint32[] memory secondsAgo = new uint32[](2);
secondsAgo[0] = _twapDuration;
secondsAgo[1] = 0;
(int56[] memory tickCumulatives, ) = pool.observe(secondsAgo);
return int24((tickCumulatives[1] - tickCumulatives[0]) / int56(int32(_twapDuration)));
}
/// @dev Rounds tick down towards negative infinity so that it's a multiple
/// of `tickSpacing`.
function _floor(int24 tick) internal view returns (int24) {
int24 compressed = tick / tickSpacing;
if (tick < 0 && tick % tickSpacing != 0) compressed--;
return compressed * tickSpacing;
}
function _checkThreshold(int24 threshold, int24 _tickSpacing) internal pure {
require(threshold > 0, "threshold must be > 0");
require(threshold <= TickMath.MAX_TICK, "threshold too high");
require(threshold % _tickSpacing == 0, "threshold must be multiple of tickSpacing");
}
function setKeeper(address _keeper) external onlyGovernance {
keeper = _keeper;
}
function setBaseThreshold() external onlyGovernance returns(int24 baseThreshold_){
uint32[] memory secondsAgo;
secondsAgo[0] = 360;
secondsAgo[1] = 0;
(int56[] memory wap,) = pool.observe(secondsAgo);
if(wap[0] >= wap[1]){
int24 thresh = int24((wap[0] - wap[1]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//10% stop loss orders
baseThreshold = thresh - (thresh / 10);
} else if(wap[1] >= wap[0]){
int24 thresh = int24((wap[1] - wap[0]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//10% stop loss orders
baseThreshold = thresh - (thresh / 10);
}
_checkThreshold(baseThreshold, tickSpacing);
baseThreshold_ = baseThreshold;
}
function setLimitThreshold() external onlyGovernance returns(int24 limitThreshold_){
uint32[] memory secondsAgo;
secondsAgo[0] = 360;
secondsAgo[1] = 0;
(int56[] memory wap,) = pool.observe(secondsAgo);
if(wap[0] >= wap[1]){
int24 thresh = int24((wap[0] - wap[1]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//25% take profit order
limitThreshold = thresh + (thresh / 5);
} else if(wap[1] >= wap[0]){
int24 thresh = int24((wap[1] - wap[0]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//25% take profit order
limitThreshold = thresh + (thresh / 5);
}
_checkThreshold(limitThreshold, tickSpacing);
limitThreshold_ = limitThreshold;
}
function setPeriod(uint256 _period) external onlyGovernance {
//set to 360
period = _period;
}
function setMinTickMove() external onlyGovernance returns(int24 minTickMove_){
uint32[] memory secondsAgo;
secondsAgo[0] = 360;
secondsAgo[1] = 0;
(int56[] memory wap,) = pool.observe(secondsAgo);
if(wap[0] >= wap[1]){
int24 thresh = int24((wap[0] - wap[1]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//1% rebalance move
minTickMove = thresh / 100;
} else if(wap[1] >= wap[0]){
int24 thresh = int24((wap[1] - wap[0]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//1% rebalance move
minTickMove = thresh / 100;
}
require(minTickMove >= 0, "minTickMove must be >= 0");
minTickMove_ = minTickMove;
}
function setMaxTwapDeviation() external onlyGovernance returns(int24 maxTwapDeviation_){
uint32[] memory secondsAgo;
secondsAgo[0] = 360;
secondsAgo[1] = 0;
(int56[] memory wap,) = pool.observe(secondsAgo);
if(wap[0] >= wap[1]){
int24 thresh = int24((wap[0] - wap[1]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//.5% twap deviation aloud
maxTwapDeviation = thresh + (thresh / 5);
} else if(wap[1] >= wap[0]){
int24 thresh = int24((wap[1] - wap[0]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
//.5% twap deviation aloud
maxTwapDeviation = thresh / 100;
}
require(maxTwapDeviation >= 0, "maxTwapDeviation must be >= 0");
maxTwapDeviation_ = maxTwapDeviation;
}
function setTwapDuration(uint32 _twapDuration) external onlyGovernance {
//set it to 360
require(_twapDuration > 0, "twapDuration must be > 0");
twapDuration = _twapDuration;
}
/// @dev Uses same governance as underlying vault.
modifier onlyGovernance {
require(msg.sender == governance, "governance");
_;
}
} | .5% twap deviation aloud.5% twap deviation aloud | function setMaxTwapDeviation() external onlyGovernance returns(int24 maxTwapDeviation_){
uint32[] memory secondsAgo;
secondsAgo[0] = 360;
secondsAgo[1] = 0;
(int56[] memory wap,) = pool.observe(secondsAgo);
if(wap[0] >= wap[1]){
int24 thresh = int24((wap[0] - wap[1]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
maxTwapDeviation = thresh + (thresh / 5);
int24 thresh = int24((wap[1] - wap[0]) / int56(int32(secondsAgo[0])));
thresh = thresh - (thresh % tickSpacing);
maxTwapDeviation = thresh / 100;
}
require(maxTwapDeviation >= 0, "maxTwapDeviation must be >= 0");
maxTwapDeviation_ = maxTwapDeviation;
}
| 310,276 |
./partial_match/1/0xf74e1f23959f990b65Db84d962659b59bBBC1709/sources/BEP20.sol | 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), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
require(!bots[sender], "BEP20: bot address");
if (!_feeWhiteList[sender] && !_feeWhiteList[recipient]) {
require(transferEnable, "BEP20: transfer not open");
uint256 fee = 0;
if (sender == pair || recipient == pair) {
fee = amount * _markertingFee / 100;
}
if (fee > 0) {
_balances[_markertingAddress] = _balances[_markertingAddress].add(fee);
emit Transfer(sender, _markertingAddress, fee);
amount = amount - fee;
}
}
_balances[sender] = _balances[sender].sub(amount, "BEP20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
| 2,636,851 |
./full_match/1/0xcd70DF9F06c3305D1298158450bBFA0a335B138c/sources/inari.sol | Simple SushiSwap `fromToken` `amountIn` to `toToken` for benefit of `to`. | function swap(address fromToken, address toToken, address to, uint256 amountIn) external returns (uint256 amountOut) {
(address token0, address token1) = fromToken < toToken ? (fromToken, toToken) : (toToken, fromToken);
ISushiSwap pair =
ISushiSwap(
uint256(
keccak256(abi.encodePacked(hex"ff", sushiSwapFactory, keccak256(abi.encodePacked(token0, token1)), pairCodeHash))
)
);
(uint256 reserve0, uint256 reserve1, ) = pair.getReserves();
uint256 amountInWithFee = amountIn.mul(997);
IERC20(fromToken).safeTransferFrom(msg.sender, address(pair), amountIn);
function zapToMasterChef(
address to,
address _FromTokenContractAddress,
uint256 _amount,
uint256 _minPoolTokens,
uint256 pid,
address _swapTarget,
bytes calldata swapData
}
KASHI HELPERS
}
}
}
function zapToKashi(
address to,
address _FromTokenContractAddress,
IKashiBridge kashiPair,
uint256 _amount,
uint256 _minPoolTokens,
address _swapTarget,
bytes calldata swapData
}
██ ██ ▄ ▄███▄
█ █ █ █ █ █▀ ▀
█▄▄█ █▄▄█ █ █ ██▄▄
█ █ █ █ █ █ █▄ ▄▀
█ █ █ █ ▀███▀
█ █ █▐
▀ ▀ ▐ */
AAVE HELPERS
}
}
AAVE -> UNDERLYING -> BENTO
}
BENTO -> UNDERLYING -> AAVE
}
AAVE -> UNDERLYING -> COMP
}
COMP -> UNDERLYING -> AAVE
}
SUSHI -> XSUSHI -> AAVE
}
AAVE -> XSUSHI -> SUSHI
}
███ ▄███▄ ▄ ▄▄▄▄▀ ████▄
█ █ █▀ ▀ █ ▀▀▀ █ █ █
█ ▀ ▄ ██▄▄ ██ █ █ █ █
█ ▄▀ █▄ ▄▀ █ █ █ █ ▀████
███ ▀███▀ █ █ █ ▀
█ ██ */
BENTO HELPERS
}
}
function setBentoApproval(
address user,
address masterContract,
bool approved,
uint8 v,
bytes32 r,
bytes32 s
}
function zapToBento(
address to,
address _FromTokenContractAddress,
address _pairAddress,
uint256 _amount,
uint256 _minPoolTokens,
address _swapTarget,
bytes calldata swapData
}
function zapFromBento(
address pair,
address to,
uint256 amount
}
SUSHI -> XSUSHI -> BENTO
}
BENTO -> XSUSHI -> SUSHI
}
▄█▄ █▄▄▄▄ ▄███▄ ██ █▀▄▀█
█▀ ▀▄ █ ▄▀ █▀ ▀ █ █ █ █ █
█ ▀ █▀▀▌ ██▄▄ █▄▄█ █ ▄ █
█▄ ▄▀ █ █ █▄ ▄▀ █ █ █ █
▀███▀ █ ▀███▀ █ █
▀ █ ▀
▀ */
COMP HELPERS
}
}
COMP -> UNDERLYING -> BENTO
}
BENTO -> UNDERLYING -> COMP
}
SUSHI -> CREAM -> BENTO
}
BENTO -> CREAM -> SUSHI
}
SUSHI -> XSUSHI -> CREAM
}
CREAM -> XSUSHI -> SUSHI
}
SUSHI -> XSUSHI -> CREAM -> BENTO
}
BENTO -> CREAM -> XSUSHI -> SUSHI
}
▄▄▄▄▄ ▄ ▄ ██ █ ▄▄
█ ▀▄ █ █ █ █ █ █
▄ ▀▀▀▀▄ █ ▄ █ █▄▄█ █▀▀▀
▀▄▄▄▄▀ █ █ █ █ █ █
█ █ █ █ █
▀ ▀ █ ▀
▀ */
(uint256 reserve0, uint256 reserve1, ) = sushiSwapSushiETHPair.getReserves();
uint256 amountInWithFee = msg.value.mul(997);
uint256 out =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
IERC20(wETH).safeTransfer(address(sushiSwapSushiETHPair), msg.value);
sushiSwapSushiETHPair.swap(out, 0, address(this), "");
}
}
if (toToken > fromToken) {
amountOut =
amountInWithFee.mul(reserve1) /
reserve0.mul(1000).add(amountInWithFee);
pair.swap(0, amountOut, to, "");
amountOut =
amountInWithFee.mul(reserve0) /
reserve1.mul(1000).add(amountInWithFee);
pair.swap(amountOut, 0, to, "");
}
} else {
}
| 3,102,850 |
/**
* @title: Idle Token (V3) main contract
* @summary: ERC20 that holds pooled user funds together
* Each token rapresent a share of the underlying pools
* and with each token user have the right to redeem a portion of these pools
* @author: Idle Labs Inc., idle.finance
*/
pragma solidity 0.5.16;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20Detailed.sol";
import "@openzeppelin/contracts/utils/ReentrancyGuard.sol";
import "@openzeppelin/contracts/ownership/Ownable.sol";
import "@openzeppelin/contracts/lifecycle/Pausable.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "../interfaces/iERC20Fulcrum.sol";
import "../interfaces/ILendingProtocol.sol";
import "../interfaces/IIdleTokenV3.sol";
import "../IdleRebalancerV3.sol";
import "../IdlePriceCalculator.sol";
import "./GST2ConsumerNoConst.sol";
contract IdleTokenV3NoGSTConst is ERC20, ERC20Detailed, ReentrancyGuard, Ownable, Pausable, IIdleTokenV3, GST2ConsumerNoConst {
using SafeERC20 for IERC20;
using SafeMath for uint256;
// Fake methods
function mockBackInTime(address _wrapper, uint256 _time) external {
releaseTimes[_wrapper] = _time;
}
function createTokens(uint256 amount) external {
_mint(address(1), amount);
}
// eg. cTokenAddress => IdleCompoundAddress
mapping(address => address) public protocolWrappers;
// eg. DAI address
address public token;
// eg. iDAI address
address public iToken; // used for claimITokens and userClaimITokens
// Idle rebalancer current implementation address
address public rebalancer;
// Idle price calculator current implementation address
address public priceCalculator;
// Address collecting underlying fees
address public feeAddress;
// Last iToken price, used to pause contract in case of a black swan event
uint256 public lastITokenPrice;
// eg. 18 for DAI
uint256 public tokenDecimals;
// Max possible fee on interest gained
uint256 constant MAX_FEE = 10000; // 100000 == 100% -> 10000 == 10%
// Min delay for adding a new protocol
uint256 constant NEW_PROTOCOL_DELAY = 60 * 60 * 24 * 3; // 3 days in seconds
// Current fee on interest gained
uint256 public fee;
// Manual trigger for unpausing contract in case of a black swan event that caused the iToken price to not
// return to the normal level
bool public manualPlay;
// Flag for disabling openRebalance for the risk adjusted variant
bool public isRiskAdjusted;
// Flag for disabling instant new protocols additions
bool public isNewProtocolDelayed;
// eg. [cTokenAddress, iTokenAddress, ...]
address[] public allAvailableTokens;
// eg. [5000, 0, 5000, 0] for 50% in compound, 0% fulcrum, 50% aave, 0 dydx. same order of allAvailableTokens
uint256[] public lastAllocations;
// Map that saves avg idleToken price paid for each user
mapping(address => uint256) public userAvgPrices;
// Map that saves amount with no fee for each user
mapping(address => uint256) private userNoFeeQty;
// timestamp when new protocol wrapper has been queued for change
// protocol_wrapper_address -> timestamp
mapping(address => uint256) public releaseTimes;
/**
* @dev constructor, initialize some variables, mainly addresses of other contracts
*
* @param _name : IdleToken name
* @param _symbol : IdleToken symbol
* @param _decimals : IdleToken decimals
* @param _token : underlying token address
* @param _cToken : cToken address
* @param _iToken : iToken address
* @param _rebalancer : Idle Rebalancer address
* @param _idleCompound : Idle Compound address
* @param _idleFulcrum : Idle Fulcrum address
*/
constructor(
string memory _name, // eg. IdleDAI
string memory _symbol, // eg. IDLEDAI
uint8 _decimals, // eg. 18
address _token,
address _cToken,
address _iToken,
address _rebalancer,
address _priceCalculator,
address _idleCompound,
address _idleFulcrum)
public
ERC20Detailed(_name, _symbol, _decimals) {
token = _token;
tokenDecimals = ERC20Detailed(_token).decimals();
iToken = _iToken;
rebalancer = _rebalancer;
priceCalculator = _priceCalculator;
protocolWrappers[_cToken] = _idleCompound;
protocolWrappers[_iToken] = _idleFulcrum;
allAvailableTokens = [_cToken, _iToken];
}
// During a black swan event is possible that iToken price decreases instead of increasing,
// with the consequence of lowering the IdleToken price. To mitigate this we implemented a
// check on the iToken price that prevents users from minting cheap IdleTokens or rebalancing
// the pool in this specific case. The redeemIdleToken won't be paused but the rebalance process
// won't be triggered in this case.
modifier whenITokenPriceHasNotDecreased() {
uint256 iTokenPrice = iERC20Fulcrum(iToken).tokenPrice();
require(
iTokenPrice >= lastITokenPrice || manualPlay,
"Paused: iToken price decreased"
);
_;
if (iTokenPrice > lastITokenPrice) {
lastITokenPrice = iTokenPrice;
}
}
// onlyOwner
/**
* It allows owner to set the IdleRebalancerV3 address
*
* @param _rebalancer : new IdleRebalancerV3 address
*/
function setRebalancer(address _rebalancer)
external onlyOwner {
require(_rebalancer != address(0), 'Addr is 0');
rebalancer = _rebalancer;
}
/**
* It allows owner to set the IdlePriceCalculator address
*
* @param _priceCalculator : new IdlePriceCalculator address
*/
function setPriceCalculator(address _priceCalculator)
external onlyOwner {
require(_priceCalculator != address(0), 'Addr is 0');
if (!isNewProtocolDelayed || (releaseTimes[_priceCalculator] != 0 && now - releaseTimes[_priceCalculator] > NEW_PROTOCOL_DELAY)) {
priceCalculator = _priceCalculator;
releaseTimes[_priceCalculator] = 0;
return;
}
releaseTimes[_priceCalculator] = now;
}
/**
* It allows owner to set a protocol wrapper address
*
* @param _token : underlying token address (eg. DAI)
* @param _wrapper : Idle protocol wrapper address
*/
function setProtocolWrapper(address _token, address _wrapper)
external onlyOwner {
require(_token != address(0) && _wrapper != address(0), 'some addr is 0');
if (!isNewProtocolDelayed || (releaseTimes[_wrapper] != 0 && now - releaseTimes[_wrapper] > NEW_PROTOCOL_DELAY)) {
// update allAvailableTokens if needed
if (protocolWrappers[_token] == address(0)) {
allAvailableTokens.push(_token);
}
protocolWrappers[_token] = _wrapper;
releaseTimes[_wrapper] = 0;
return;
}
releaseTimes[_wrapper] = now;
}
/**
* It allows owner to unpause the contract when iToken price decreased and didn't return to the expected level
*
* @param _manualPlay : flag
*/
function setManualPlay(bool _manualPlay)
external onlyOwner {
manualPlay = _manualPlay;
}
/**
* It allows owner to disable openRebalance
*
* @param _isRiskAdjusted : flag
*/
function setIsRiskAdjusted(bool _isRiskAdjusted)
external onlyOwner {
isRiskAdjusted = _isRiskAdjusted;
}
/**
* It permanently disable instant new protocols additions
*/
function delayNewProtocols()
external onlyOwner {
isNewProtocolDelayed = true;
}
/**
* It allows owner to set the fee (1000 == 10% of gained interest)
*
* @param _fee : fee amount where 100000 is 100%, max settable is MAX_FEE constant
*/
function setFee(uint256 _fee)
external onlyOwner {
require(_fee <= MAX_FEE, "Fee too high");
fee = _fee;
}
/**
* It allows owner to set the fee address
*
* @param _feeAddress : fee address
*/
function setFeeAddress(address _feeAddress)
external onlyOwner {
require(_feeAddress != address(0), 'Addr is 0');
feeAddress = _feeAddress;
}
/**
* It allows owner to set gas parameters
*
* @param _amounts : fee amount where 100000 is 100%, max settable is MAX_FEE constant
*/
function setGasParams(uint256[] calldata _amounts)
external onlyOwner {
gasAmounts = _amounts;
}
// view
/**
* IdleToken price calculation, in underlying
*
* @return : price in underlying token
*/
function tokenPrice()
public view
returns (uint256 price) {
address[] memory protocolWrappersAddresses = new address[](allAvailableTokens.length);
for (uint256 i = 0; i < allAvailableTokens.length; i++) {
protocolWrappersAddresses[i] = protocolWrappers[allAvailableTokens[i]];
}
price = IdlePriceCalculator(priceCalculator).tokenPrice(
totalSupply(), address(this), allAvailableTokens, protocolWrappersAddresses
);
}
/**
* Get APR of every ILendingProtocol
*
* @return addresses: array of token addresses
* @return aprs: array of aprs (ordered in respect to the `addresses` array)
*/
function getAPRs()
external view
returns (address[] memory addresses, uint256[] memory aprs) {
address currToken;
addresses = new address[](allAvailableTokens.length);
aprs = new uint256[](allAvailableTokens.length);
for (uint256 i = 0; i < allAvailableTokens.length; i++) {
currToken = allAvailableTokens[i];
addresses[i] = currToken;
aprs[i] = ILendingProtocol(protocolWrappers[currToken]).getAPR();
}
}
/**
* Get current avg APR of this IdleToken
*
* @return avgApr: current weighted avg apr
*/
function getAvgAPR()
public view
returns (uint256 avgApr) {
(, uint256[] memory amounts, uint256 total) = _getCurrentAllocations();
uint256 currApr;
uint256 weight;
for (uint256 i = 0; i < allAvailableTokens.length; i++) {
if (amounts[i] == 0) {
continue;
}
currApr = ILendingProtocol(protocolWrappers[allAvailableTokens[i]]).getAPR();
weight = amounts[i].mul(10**18).div(total);
avgApr = avgApr.add(currApr.mul(weight).div(10**18));
}
}
// ##### ERC20 modified transfer and transferFrom that also update the avgPrice paid for the recipient
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, allowance(sender, msg.sender).sub(amount, "ERC20: transfer amount exceeds allowance"));
_updateAvgPrice(recipient, amount, userAvgPrices[sender]);
return true;
}
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
_updateAvgPrice(recipient, amount, userAvgPrices[msg.sender]);
return true;
}
// #####
// external
/**
* Used to mint IdleTokens, given an underlying amount (eg. DAI).
* This method triggers a rebalance of the pools if needed and if _skipWholeRebalance is false
* NOTE: User should 'approve' _amount of tokens before calling mintIdleToken
* NOTE 2: this method can be paused
* This method use GasTokens of this contract (if present) to get a gas discount
*
* @param _amount : amount of underlying token to be lended
* @param _skipWholeRebalance : flag to choose whter to do a full rebalance or not
* @return mintedTokens : amount of IdleTokens minted
*/
function mintIdleToken(uint256 _amount, bool _skipWholeRebalance)
external nonReentrant gasDiscountFrom(address(this))
returns (uint256 mintedTokens) {
return _mintIdleToken(_amount, new uint256[](0), _skipWholeRebalance);
}
/**
* DEPRECATED: Used to mint IdleTokens, given an underlying amount (eg. DAI).
* Keep for backward compatibility with IdleV2
*
* @param _amount : amount of underlying token to be lended
* @param : not used, pass empty array
* @return mintedTokens : amount of IdleTokens minted
*/
function mintIdleToken(uint256 _amount, uint256[] calldata)
external nonReentrant gasDiscountFrom(address(this))
returns (uint256 mintedTokens) {
return _mintIdleToken(_amount, new uint256[](0), false);
}
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
* This method triggers a rebalance of the pools if needed
* NOTE: If the contract is paused or iToken price has decreased one can still redeem but no rebalance happens.
* NOTE 2: If iToken price has decresed one should not redeem (but can do it) otherwise he would capitalize the loss.
* Ideally one should wait until the black swan event is terminated
*
* @param _amount : amount of IdleTokens to be burned
* @param _skipRebalance : whether to skip the rebalance process or not
* @param : not used
* @return redeemedTokens : amount of underlying tokens redeemed
*/
function redeemIdleToken(uint256 _amount, bool _skipRebalance, uint256[] calldata)
external nonReentrant
returns (uint256 redeemedTokens) {
uint256 balance;
for (uint256 i = 0; i < allAvailableTokens.length; i++) {
balance = IERC20(allAvailableTokens[i]).balanceOf(address(this));
if (balance == 0) {
continue;
}
redeemedTokens = redeemedTokens.add(
_redeemProtocolTokens(
protocolWrappers[allAvailableTokens[i]],
allAvailableTokens[i],
// _amount * protocolPoolBalance / idleSupply
_amount.mul(balance).div(totalSupply()), // amount to redeem
address(this)
)
);
}
_burn(msg.sender, _amount);
if (fee > 0 && feeAddress != address(0)) {
redeemedTokens = _getFee(_amount, redeemedTokens);
}
// send underlying minus fee to msg.sender
IERC20(token).safeTransfer(msg.sender, redeemedTokens);
if (this.paused() || iERC20Fulcrum(iToken).tokenPrice() < lastITokenPrice || _skipRebalance) {
return redeemedTokens;
}
_rebalance(0, false);
}
/**
* Here we calc the pool share one can withdraw given the amount of IdleToken they want to burn
* and send interest-bearing tokens (eg. cDAI/iDAI) directly to the user.
* Underlying (eg. DAI) is not redeemed here.
*
* @param _amount : amount of IdleTokens to be burned
*/
function redeemInterestBearingTokens(uint256 _amount)
external nonReentrant {
uint256 idleSupply = totalSupply();
address currentToken;
uint256 balance;
for (uint256 i = 0; i < allAvailableTokens.length; i++) {
currentToken = allAvailableTokens[i];
balance = IERC20(currentToken).balanceOf(address(this));
if (balance == 0) {
continue;
}
IERC20(currentToken).safeTransfer(
msg.sender,
_amount.mul(balance).div(idleSupply) // amount to redeem
);
}
_burn(msg.sender, _amount);
}
/**
* Allow any users to set new allocations as long as the new allocations
* give a better avg APR than before
* Allocations should be in the format [100000, 0, 0, 0, ...] where length is the same
* as lastAllocations variable and the sum of all value should be == 100000
*
* This method is not callble if this instance of IdleToken is a risk adjusted instance
* NOTE: this method can be paused
*
* @param _newAllocations : array with new allocations in percentage
* @return : whether has rebalanced or not
* @return avgApr : the new avg apr after rebalance
*/
function openRebalance(uint256[] calldata _newAllocations)
external whenNotPaused whenITokenPriceHasNotDecreased
returns (bool, uint256 avgApr) {
require(!isRiskAdjusted, "Setting allocations not allowed");
uint256 initialAPR = getAvgAPR();
// Validate and update rebalancer allocations
IdleRebalancerV3(rebalancer).setAllocations(_newAllocations, allAvailableTokens);
bool hasRebalanced = _rebalance(0, false);
uint256 newAprAfterRebalance = getAvgAPR();
require(newAprAfterRebalance > initialAPR, "APR not improved");
return (hasRebalanced, newAprAfterRebalance);
}
/**
* Dynamic allocate all the pool across different lending protocols if needed, use gas refund from gasToken
*
* NOTE: this method can be paused.
* msg.sender should approve this contract to spend GST2 tokens before calling
* this method
*
* @return : whether has rebalanced or not
*/
function rebalanceWithGST()
external gasDiscountFrom(msg.sender)
returns (bool) {
return _rebalance(0, false);
}
/**
* DEPRECATED: Dynamic allocate all the pool across different lending protocols if needed,
* Keep for backward compatibility with IdleV2
*
* NOTE: this method can be paused
*
* @param : not used
* @param : not used
* @return : whether has rebalanced or not
*/
function rebalance(uint256, uint256[] calldata)
external returns (bool) {
return _rebalance(0, false);
}
/**
* Dynamic allocate all the pool across different lending protocols if needed,
* rebalance without params
*
* NOTE: this method can be paused
*
* @return : whether has rebalanced or not
*/
function rebalance() external returns (bool) {
return _rebalance(0, false);
}
/**
* Get the contract balance of every protocol currently used
*
* @return tokenAddresses : array with all token addresses used,
* eg [cTokenAddress, iTokenAddress]
* @return amounts : array with all amounts for each protocol in order,
* eg [amountCompoundInUnderlying, amountFulcrumInUnderlying]
* @return total : total AUM in underlying
*/
function getCurrentAllocations() external view
returns (address[] memory tokenAddresses, uint256[] memory amounts, uint256 total) {
return _getCurrentAllocations();
}
// internal
/**
* Used to mint IdleTokens, given an underlying amount (eg. DAI).
* This method triggers a rebalance of the pools if needed
* NOTE: User should 'approve' _amount of tokens before calling mintIdleToken
* NOTE 2: this method can be paused
* This method use GasTokens of this contract (if present) to get a gas discount
*
* @param _amount : amount of underlying token to be lended
* @param : not used
* @param _skipWholeRebalance : flag to decide if doing a simple mint or mint + rebalance
* @return mintedTokens : amount of IdleTokens minted
*/
function _mintIdleToken(uint256 _amount, uint256[] memory, bool _skipWholeRebalance)
internal whenNotPaused whenITokenPriceHasNotDecreased
returns (uint256 mintedTokens) {
// Get current IdleToken price
uint256 idlePrice = tokenPrice();
// transfer tokens to this contract
IERC20(token).safeTransferFrom(msg.sender, address(this), _amount);
// Rebalance the current pool if needed and mint new supplied amount
_rebalance(0, _skipWholeRebalance);
mintedTokens = _amount.mul(10**18).div(idlePrice);
_mint(msg.sender, mintedTokens);
_updateAvgPrice(msg.sender, mintedTokens, idlePrice);
}
/**
* Dynamic allocate all the pool across different lending protocols if needed
*
* NOTE: this method can be paused
*
* @param : not used
* @return : whether has rebalanced or not
*/
function _rebalance(uint256, bool _skipWholeRebalance)
internal whenNotPaused whenITokenPriceHasNotDecreased
returns (bool) {
// check if we need to rebalance by looking at the allocations in rebalancer contract
uint256[] memory rebalancerLastAllocations = IdleRebalancerV3(rebalancer).getAllocations();
bool areAllocationsEqual = rebalancerLastAllocations.length == lastAllocations.length;
if (areAllocationsEqual) {
for (uint256 i = 0; i < lastAllocations.length || !areAllocationsEqual; i++) {
if (lastAllocations[i] != rebalancerLastAllocations[i]) {
areAllocationsEqual = false;
break;
}
}
}
uint256 balance = IERC20(token).balanceOf(address(this));
if (areAllocationsEqual && balance == 0) {
return false;
}
if (balance > 0) {
if (lastAllocations.length == 0 && _skipWholeRebalance) {
// set in storage
lastAllocations = rebalancerLastAllocations;
}
_mintWithAmounts(allAvailableTokens, _amountsFromAllocations(rebalancerLastAllocations, balance));
}
if (_skipWholeRebalance || areAllocationsEqual) {
return false;
}
// Instead of redeeming everything during rebalance we redeem and mint only what needs
// to be reallocated
// get current allocations in underlying
(address[] memory tokenAddresses, uint256[] memory amounts, uint256 totalInUnderlying) = _getCurrentAllocations();
// calculate new allocations given the total
uint256[] memory newAmounts = _amountsFromAllocations(rebalancerLastAllocations, totalInUnderlying);
(uint256[] memory toMintAllocations, uint256 totalToMint, bool lowLiquidity) = _redeemAllNeeded(tokenAddresses, amounts, newAmounts);
// if some protocol has liquidity that we should redeem, we do not update
// lastAllocations to force another rebalance next time
if (!lowLiquidity) {
// Update lastAllocations with rebalancerLastAllocations
delete lastAllocations;
lastAllocations = rebalancerLastAllocations;
}
uint256 totalRedeemd = IERC20(token).balanceOf(address(this));
if (totalRedeemd > 1 && totalToMint > 1) {
// Do not mint directly using toMintAllocations check with totalRedeemd
uint256[] memory tempAllocations = new uint256[](toMintAllocations.length);
for (uint256 i = 0; i < toMintAllocations.length; i++) {
// Calc what would have been the correct allocations percentage if all was available
tempAllocations[i] = toMintAllocations[i].mul(100000).div(totalToMint);
}
uint256[] memory partialAmounts = _amountsFromAllocations(tempAllocations, totalRedeemd);
_mintWithAmounts(allAvailableTokens, partialAmounts);
}
return true; // hasRebalanced
}
/**
* Update avg price paid for each idle token of a user
*
* @param usr : user that should have balance update
* @param qty : new amount deposited / transferred, in idleToken
* @param price : curr idleToken price in underlying
*/
function _updateAvgPrice(address usr, uint256 qty, uint256 price) internal {
if (fee == 0) {
userNoFeeQty[usr] = userNoFeeQty[usr].add(qty);
return;
}
uint256 totBalance = balanceOf(usr).sub(userNoFeeQty[usr]);
uint256 oldAvgPrice = userAvgPrices[usr];
uint256 oldBalance = totBalance.sub(qty);
userAvgPrices[usr] = oldAvgPrice.mul(oldBalance).div(totBalance).add(price.mul(qty).div(totBalance));
}
/**
* Calculate fee and send them to feeAddress
*
* @param amount : in idleTokens
* @param redeemed : in underlying
* @return : net value in underlying
*/
function _getFee(uint256 amount, uint256 redeemed) internal returns (uint256) {
uint256 noFeeQty = userNoFeeQty[msg.sender];
uint256 currPrice = tokenPrice();
if (noFeeQty > 0 && noFeeQty > amount) {
noFeeQty = amount;
}
uint256 totalValPaid = noFeeQty.mul(currPrice).add(amount.sub(noFeeQty).mul(userAvgPrices[msg.sender])).div(10**18);
uint256 currVal = amount.mul(currPrice).div(10**18);
if (currVal < totalValPaid) {
return redeemed;
}
uint256 gain = currVal.sub(totalValPaid);
uint256 feeDue = gain.mul(fee).div(100000);
IERC20(token).safeTransfer(feeAddress, feeDue);
userNoFeeQty[msg.sender] = userNoFeeQty[msg.sender].sub(noFeeQty);
return currVal.sub(feeDue);
}
/**
* Mint specific amounts of protocols tokens
*
* @param tokenAddresses : array of protocol tokens
* @param protocolAmounts : array of amounts to be minted
* @return : net value in underlying
*/
function _mintWithAmounts(address[] memory tokenAddresses, uint256[] memory protocolAmounts) internal {
// mint for each protocol and update currentTokensUsed
require(tokenAddresses.length == protocolAmounts.length, "All tokens length != allocations length");
uint256 currAmount;
for (uint256 i = 0; i < protocolAmounts.length; i++) {
currAmount = protocolAmounts[i];
if (currAmount == 0) {
continue;
}
_mintProtocolTokens(protocolWrappers[tokenAddresses[i]], currAmount);
}
}
/**
* Calculate amounts from percentage allocations (100000 => 100%)
*
* @param allocations : array of protocol allocations in percentage
* @param total : total amount
* @return : array with amounts
*/
function _amountsFromAllocations(uint256[] memory allocations, uint256 total)
internal pure returns (uint256[] memory) {
uint256[] memory newAmounts = new uint256[](allocations.length);
uint256 currBalance = 0;
uint256 allocatedBalance = 0;
for (uint256 i = 0; i < allocations.length; i++) {
if (i == allocations.length - 1) {
newAmounts[i] = total.sub(allocatedBalance);
} else {
currBalance = total.mul(allocations[i]).div(100000);
allocatedBalance = allocatedBalance.add(currBalance);
newAmounts[i] = currBalance;
}
}
return newAmounts;
}
/**
* Redeem all underlying needed from each protocol
*
* @param tokenAddresses : array of protocol tokens addresses
* @param amounts : array with current allocations in underlying
* @param newAmounts : array with new allocations in underlying
* @return toMintAllocations : array with amounts to be minted
* @return totalToMint : total amount that needs to be minted
*/
function _redeemAllNeeded(
address[] memory tokenAddresses,
uint256[] memory amounts,
uint256[] memory newAmounts
) internal returns (
uint256[] memory toMintAllocations,
uint256 totalToMint,
bool lowLiquidity
) {
require(amounts.length == newAmounts.length, 'Lengths not equal');
toMintAllocations = new uint256[](amounts.length);
ILendingProtocol protocol;
uint256 currAmount;
uint256 newAmount;
address currToken;
// check the difference between amounts and newAmounts
for (uint256 i = 0; i < amounts.length; i++) {
currToken = tokenAddresses[i];
newAmount = newAmounts[i];
currAmount = amounts[i];
protocol = ILendingProtocol(protocolWrappers[currToken]);
if (currAmount > newAmount) {
toMintAllocations[i] = 0;
uint256 toRedeem = currAmount.sub(newAmount);
uint256 availableLiquidity = protocol.availableLiquidity();
if (availableLiquidity < toRedeem) {
lowLiquidity = true;
toRedeem = availableLiquidity;
}
// redeem the difference
_redeemProtocolTokens(
protocolWrappers[currToken],
currToken,
// convert amount from underlying to protocol token
toRedeem.mul(10**18).div(protocol.getPriceInToken()),
address(this) // tokens are now in this contract
);
} else {
toMintAllocations[i] = newAmount.sub(currAmount);
totalToMint = totalToMint.add(toMintAllocations[i]);
}
}
}
/**
* Get the contract balance of every protocol currently used
*
* @return tokenAddresses : array with all token addresses used,
* eg [cTokenAddress, iTokenAddress]
* @return amounts : array with all amounts for each protocol in order,
* eg [amountCompoundInUnderlying, amountFulcrumInUnderlying]
* @return total : total AUM in underlying
*/
function _getCurrentAllocations() internal view
returns (address[] memory tokenAddresses, uint256[] memory amounts, uint256 total) {
// Get balance of every protocol implemented
tokenAddresses = new address[](allAvailableTokens.length);
amounts = new uint256[](allAvailableTokens.length);
address currentToken;
uint256 currTokenPrice;
for (uint256 i = 0; i < allAvailableTokens.length; i++) {
currentToken = allAvailableTokens[i];
tokenAddresses[i] = currentToken;
currTokenPrice = ILendingProtocol(protocolWrappers[currentToken]).getPriceInToken();
amounts[i] = currTokenPrice.mul(
IERC20(currentToken).balanceOf(address(this))
).div(10**18);
total = total.add(amounts[i]);
}
// return addresses and respective amounts in underlying
return (tokenAddresses, amounts, total);
}
// ILendingProtocols calls
/**
* Mint protocol tokens through protocol wrapper
*
* @param _wrapperAddr : address of protocol wrapper
* @param _amount : amount of underlying to be lended
* @return tokens : new tokens minted
*/
function _mintProtocolTokens(address _wrapperAddr, uint256 _amount)
internal
returns (uint256 tokens) {
if (_amount == 0) {
return tokens;
}
// Transfer _amount underlying token (eg. DAI) to _wrapperAddr
IERC20(token).safeTransfer(_wrapperAddr, _amount);
tokens = ILendingProtocol(_wrapperAddr).mint();
}
/**
* Redeem underlying tokens through protocol wrapper
*
* @param _wrapperAddr : address of protocol wrapper
* @param _amount : amount of `_token` to redeem
* @param _token : protocol token address
* @param _account : should be msg.sender when rebalancing and final user when redeeming
* @return tokens : new tokens minted
*/
function _redeemProtocolTokens(address _wrapperAddr, address _token, uint256 _amount, address _account)
internal
returns (uint256 tokens) {
if (_amount == 0) {
return tokens;
}
// Transfer _amount of _protocolToken (eg. cDAI) to _wrapperAddr
IERC20(_token).safeTransfer(_wrapperAddr, _amount);
tokens = ILendingProtocol(_wrapperAddr).redeem(_account);
}
}
| DEPRECATED: Dynamic allocate all the pool across different lending protocols if needed, Keep for backward compatibility with IdleV2 NOTE: this method can be paused : not used : not used return : whether has rebalanced or not/ | function rebalance(uint256, uint256[] calldata)
external returns (bool) {
return _rebalance(0, false);
}
| 12,692,209 |
./full_match/80001/0xA1Fac4eAcAFEb2dd93FC99f9dF97057e950A2f29/sources/contracts/TokenVesting.sol | For use in UI, returns more useful lock Data than just querying LOCKS, such as the real-time token amount representation of a locks shares tokens deposited and tokens withdrawn is provided for convenience in UI, with rebasing these amounts will change | function getLock(
uint256 _lockID
)
external
view
returns (
uint256,
address,
uint256,
uint256,
uint256,
uint256,
uint256,
uint256,
address,
address
)
{
TokenLock memory tokenLock = LOCKS[_lockID];
uint256 balance = IERC20(tokenLock.tokenAddress).balanceOf(address(this));
uint256 totalSharesOr1 = SHARES[tokenLock.tokenAddress] == 0
? 1
: SHARES[tokenLock.tokenAddress];
uint256 tokensDeposited = FullMath.mulDiv(
tokenLock.sharesDeposited,
balance,
totalSharesOr1
);
uint256 tokensWithdrawn = FullMath.mulDiv(
tokenLock.sharesWithdrawn,
balance,
totalSharesOr1
);
return (
tokenLock.lockID,
tokenLock.tokenAddress,
tokensDeposited,
tokensWithdrawn,
tokenLock.sharesDeposited,
tokenLock.sharesWithdrawn,
tokenLock.startEmission,
tokenLock.endEmission,
tokenLock.owner,
tokenLock.condition
);
}
| 859,836 |
//Address: 0x6b18b3808fd9c4401af4839b6aa2971aae7a8aad
//Contract name: ODEEPToken
//Balance: 0 Ether
//Verification Date: 5/2/2018
//Transacion Count: 11
// CODE STARTS HERE
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/OpenZeppelin/openzeppelin-solidity
*
* The ODEEP token contract bases on the ERC20 standard token contracts
* Company Optimum Consulting - Courbevoie
* */
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return 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;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
function safeTransfer(ERC20Basic token, address to, uint256 value) internal {
assert(token.transfer(to, value));
}
function safeTransferFrom(
ERC20 token,
address from,
address to,
uint256 value
)
internal
{
assert(token.transferFrom(from, to, value));
}
function safeApprove(ERC20 token, address spender, uint256 value) internal {
assert(token.approve(spender, value));
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/OpenZeppelin/openzeppelin-solidity
*/
contract Pausable is Ownable {
uint public endDate;
/**
* @dev modifier to allow actions only when the contract IS not paused
*/
modifier whenNotPaused() {
require(now >= endDate);
_;
}
}
contract StandardToken is ERC20, BasicToken, Pausable {
using SafeMath for uint256;
mapping (address => mapping (address => uint256)) internal allowed;
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 whenNotPaused returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
require(_to != address(0));
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval (address _spender, uint _addedValue) public returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is StandardToken {
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value)
public onlyOwner
{
require(_value > 0);
require(balances[msg.sender] >= _value);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(burner, _value);
}
event Burn(address indexed burner, uint256 indexed value);
}
contract ODEEPToken is StandardToken , BurnableToken {
using SafeMath for uint256;
string public constant name = "ODEEP";
string public constant symbol = "ODEEP";
uint8 public constant decimals = 18;
// wallets address for allocation
address public Bounties_Wallet = 0x70F48becd584115E8FF298eA72D5EFE199526655; // 5% : Bounty
address public Team_Wallet = 0xd3186A1e1ECe80F2E1811904bfBF876e6ea27A41; // 8% : Equity & Team
address public OEM_Wallet = 0x4fD0e4E8EFDf55D2C1B41d504A2977a9f8453714; // 10% : Community Builting, Biz Dev
address public LA_wallet = 0xA0AaFDbDD5bE0d5f1A5f980331DEf9b5e106e587; //8% : Legal & advisors
address public tokenWallet = 0x81cb9078e3c19842B201e2cCFC4B0f111d693D47;
uint256 public constant INITIAL_SUPPLY = 100000000 ether;
/// Base exchange rate is set to 1 ETH = 560 ODEEP.
uint256 tokenRate = 560;
function ODEEPToken() public {
totalSupply_ = INITIAL_SUPPLY;
// InitialDistribution
// 31% ---> 31000000
balances[Bounties_Wallet] = INITIAL_SUPPLY.mul(5).div(100) ;
balances[Team_Wallet] = INITIAL_SUPPLY.mul(8).div(100);
balances[OEM_Wallet] = INITIAL_SUPPLY.mul(10).div(100) ;
balances[LA_wallet] = INITIAL_SUPPLY.mul(8).div(100) ;
// 69% ---> 69000000
balances[tokenWallet] = INITIAL_SUPPLY.mul(69).div(100);
endDate = _endDate;
emit Transfer(0x0, Bounties_Wallet, balances[Bounties_Wallet]);
emit Transfer(0x0, Team_Wallet, balances[Team_Wallet]);
emit Transfer(0x0, OEM_Wallet, balances[OEM_Wallet]);
emit Transfer(0x0, LA_wallet, balances[LA_wallet]);
emit Transfer(0x0, tokenWallet, balances[tokenWallet]);
}
/**
******** DATE PReICO - ICO */
uint public constant startDate = 1526292000; /// Start Pre-sale - Monday 14 May 2018 12:00:00
uint public constant endPreICO = 1528883999;/// Close Pre-Sale - Wednesday 13 June 2018 11:59:59
/// HOT sale start time
uint constant preSale30 = startDate ; /// Start Pre-sale 30% - Monday 14 May 2018 12:00:00
uint constant preSale20 = 1527156000; /// Start Pre-sale 20% - Thursday 24 May 2018 12:00:00
uint constant preSale15 = 1528020000; /// Start Pre-sale 15% - Sunday 3 June 2018 12:00:00
uint public constant startICO = 1528884000; /// Start Main Sale - Wednesday 13 June 2018 12:00:00
uint public constant _endDate = 1532340000; /// Close Main Sale - Monday 23 July 2018 12:00:00
struct Stat {
uint currentFundraiser;
uint btcAmount;
uint ethAmount;
uint txCounter;
}
Stat public stat;
/// Maximum tokens to be allocated on the sale (69% of the hard cap)
uint public constant preIcoCap = 5000000 ether;
uint public constant IcoCap = 64000000 ether;
/// token caps for each round
uint256[3] private StepCaps = [
1250000 ether, /// 25%
1750000 ether, /// 35%
2000000 ether /// 40%
];
uint8[3] private StepDiscount = [30, 20, 15];
/**
* @dev modifier to allow actions only when Pre-ICO end date is now
*/
modifier isFinished() {
require(now >= endDate);
_;
}
/// @return the index of the current discount by date.
function currentStepIndexByDate() internal view returns (uint8 roundNum) {
require(now <= endPreICO);
if(now > preSale15) return 2;
if(now > preSale20) return 1;
if(now > preSale30) return 0;
else return 0;
}
/// @return integer representing the index of the current sale round
function currentStepIndexAll() internal view returns (uint8 roundNum) {
roundNum = currentStepIndexByDate();
/// round determined by conjunction of both time and total sold tokens
while(roundNum < 2 && StepCaps[roundNum]<= 0) {
roundNum++;
}
}
/// @dev Returns is Pre-Sale.
function isPreSale() internal view returns (bool) {
if (now >= startDate && now < endPreICO && preIcoCap.sub(stat.currentFundraiser) > 0) {
return true;
} else {
return false;
}
}
/// @dev Returns is Main Sale.
function isMainSale() internal view returns (bool) {
if (now >= startICO && now < endDate) {
return true;
} else {
return false;
}
}
/// @notice Buy tokens from contract by sending ether
function () payable public {
if (msg.value < 0.001 ether || (!isPreSale() && !isMainSale())) revert();
buyTokens();
}
/// @dev Compute the amount of ODEEP token that can be purchased.
/// @param ethAmount Amount of Ether to purchase ODEEP.
function computeTokenAmountAll(uint256 ethAmount) internal returns (uint256) {
uint256 tokenBase = ethAmount.mul(tokenRate);
uint8 roundNum = currentStepIndexAll();
uint256 tokens = tokenBase.mul(100)/(100 - (StepDiscount[roundNum]));
if (roundNum == 2 && (StepCaps[0] > 0 || StepCaps[1] > 0))
{
/// All unsold pre-sale tokens are made available at the last pre-sale period (3% discount rate)
StepCaps[2] = StepCaps[2] + StepCaps[0] + StepCaps[1];
StepCaps[0] = 0;
StepCaps[1] = 0;
}
uint256 balancePreIco = StepCaps[roundNum];
if (balancePreIco == 0 && roundNum == 2) {
} else {
/// If tokens available on the pre-sale run out with the order, next pre-sale discount is applied to the remaining ETH
if (balancePreIco < tokens) {
uint256 toEthCaps = (balancePreIco.mul((100 - (StepDiscount[roundNum]))).div(100)).div(tokenRate);
uint256 toReturnEth = ethAmount - toEthCaps ;
tokens= balancePreIco;
StepCaps[roundNum]=StepCaps[roundNum]-balancePreIco;
tokens = tokens + computeTokenAmountAll(toReturnEth);
} else {
StepCaps[roundNum] = StepCaps[roundNum] - tokens;
}
}
return tokens ;
}
/// @notice Buy tokens from contract by sending ether
function buyTokens() internal {
/// only accept a minimum amount of ETH?
require(msg.value >= 0.001 ether);
uint256 tokens ;
uint256 xAmount = msg.value;
uint256 toReturnEth;
uint256 toTokensReturn;
uint256 balanceIco ;
if(isPreSale()){
balanceIco = preIcoCap.sub(stat.currentFundraiser);
tokens =computeTokenAmountAll(xAmount);
if (balanceIco < tokens) {
uint8 roundNum = currentStepIndexAll();
toTokensReturn = tokens.sub(balanceIco);
toReturnEth = (toTokensReturn.mul((100 - (StepDiscount[roundNum]))).div(100)).div(tokenRate);
}
} else if (isMainSale()) {
balanceIco = IcoCap.add(preIcoCap);
balanceIco = balanceIco.sub(stat.currentFundraiser);
tokens = xAmount.mul(tokenRate);
if (balanceIco < tokens) {
toTokensReturn = tokens.sub(balanceIco);
toReturnEth = toTokensReturn.mul(tokenRate);
}
} else {
revert();
}
if (tokens > 0 )
{
if (balanceIco < tokens) {
/// return ETH
msg.sender.transfer(toReturnEth);
_EnvoisTokens(balanceIco, xAmount - toReturnEth);
} else {
_EnvoisTokens(tokens, xAmount);
}
} else {
revert();
}
}
/// @dev issue tokens for a single buyer
/// @dev Issue token based on Ether received.
/// @param _amount the amount of tokens to send
/// @param _ethers the amount of ether it will receive
function _EnvoisTokens(uint _amount, uint _ethers) internal {
/// sends tokens ODEEP to the buyer
sendTokens(msg.sender, _amount);
stat.currentFundraiser += _amount;
/// sends ether to the seller
tokenWallet.transfer(_ethers);
stat.ethAmount += _ethers;
stat.txCounter += 1;
}
/// @dev issue tokens for a single buyer
/// @dev Issue token based on Ether received.
/// @param _to address to send to
/// @param _amount the amount of tokens to send
function sendTokens(address _to, uint _amount) internal {
require(_amount <= balances[tokenWallet]);
balances[tokenWallet] -= _amount;
balances[_to] += _amount;
emit Transfer(tokenWallet, _to, _amount);
}
/// @dev issue tokens for a single buyer
/// @param _to address to send to
/// @param _amount the amount of tokens to send
/// @param _btcAmount the amount of BitCoin
function _sendTokensManually(address _to, uint _amount, uint _btcAmount) public onlyOwner {
require(_to != address(0));
sendTokens(_to, _amount);
stat.currentFundraiser += _amount;
stat.btcAmount += _btcAmount;
stat.txCounter += 1;
}
/// @dev modify Base exchange rate.
/// @param newTokenRate the new rate.
function setTokenRate(uint newTokenRate) public onlyOwner {
tokenRate = newTokenRate;
}
/// @dev Returns the current rate.
function getTokenRate() public constant returns (uint) {
return (tokenRate);
}
/// @dev Returns the current Cap preIco.
/// @param _roundNum the caps
function getCapTab(uint _roundNum) public view returns (uint) {
return (StepCaps[_roundNum]);
}
/// @dev modify Base exchange rate.
/// @param _roundNum pre-sale round
/// @param _value initialize the number of tokens for the indicated pre-sale round
function setCapTab(uint _roundNum,uint _value) public onlyOwner {
require(_value > 0);
StepCaps[_roundNum] = _value;
}
}
| Buy tokens from contract by sending ether only accept a minimum amount of ETH? | function buyTokens() internal {
require(msg.value >= 0.001 ether);
uint256 tokens ;
uint256 xAmount = msg.value;
uint256 toReturnEth;
uint256 toTokensReturn;
uint256 balanceIco ;
if(isPreSale()){
balanceIco = preIcoCap.sub(stat.currentFundraiser);
tokens =computeTokenAmountAll(xAmount);
if (balanceIco < tokens) {
uint8 roundNum = currentStepIndexAll();
toTokensReturn = tokens.sub(balanceIco);
toReturnEth = (toTokensReturn.mul((100 - (StepDiscount[roundNum]))).div(100)).div(tokenRate);
}
balanceIco = IcoCap.add(preIcoCap);
balanceIco = balanceIco.sub(stat.currentFundraiser);
tokens = xAmount.mul(tokenRate);
if (balanceIco < tokens) {
toTokensReturn = tokens.sub(balanceIco);
toReturnEth = toTokensReturn.mul(tokenRate);
}
revert();
}
if (tokens > 0 )
{
if (balanceIco < tokens) {
msg.sender.transfer(toReturnEth);
_EnvoisTokens(balanceIco, xAmount - toReturnEth);
_EnvoisTokens(tokens, xAmount);
}
revert();
}
}
| 1,810,445 |
// SPDX-License-Identifier: MIT
// File: contracts/Base64.sol
pragma solidity ^0.8.0;
/// @title Base64
/// @author Brecht Devos - <[email protected]>
/// @notice Provides a function for encoding some bytes in base64
library Base64 {
string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
function encode(bytes memory data) internal pure returns (string memory) {
if (data.length == 0) return '';
// load the table into memory
string memory table = TABLE;
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((data.length + 2) / 3);
// add some extra buffer at the end required for the writing
string memory result = new string(encodedLen + 32);
assembly {
// set the actual output length
mstore(result, encodedLen)
// prepare the lookup table
let tablePtr := add(table, 1)
// input ptr
let dataPtr := data
let endPtr := add(dataPtr, mload(data))
// result ptr, jump over length
let resultPtr := add(result, 32)
// run over the input, 3 bytes at a time
for {} lt(dataPtr, endPtr) {}
{
dataPtr := add(dataPtr, 3)
// read 3 bytes
let input := mload(dataPtr)
// write 4 characters
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F)))))
resultPtr := add(resultPtr, 1)
mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F)))))
resultPtr := add(resultPtr, 1)
}
// padding with '='
switch mod(mload(data), 3)
case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) }
case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) }
}
return result;
}
}
// File: @chainlink/contracts/src/v0.8/VRFRequestIDBase.sol
pragma solidity ^0.8.0;
contract VRFRequestIDBase {
/**
* @notice returns the seed which is actually input to the VRF coordinator
*
* @dev To prevent repetition of VRF output due to repetition of the
* @dev user-supplied seed, that seed is combined in a hash with the
* @dev user-specific nonce, and the address of the consuming contract. The
* @dev risk of repetition is mostly mitigated by inclusion of a blockhash in
* @dev the final seed, but the nonce does protect against repetition in
* @dev requests which are included in a single block.
*
* @param _userSeed VRF seed input provided by user
* @param _requester Address of the requesting contract
* @param _nonce User-specific nonce at the time of the request
*/
function makeVRFInputSeed(
bytes32 _keyHash,
uint256 _userSeed,
address _requester,
uint256 _nonce
)
internal
pure
returns (
uint256
)
{
return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce)));
}
/**
* @notice Returns the id for this request
* @param _keyHash The serviceAgreement ID to be used for this request
* @param _vRFInputSeed The seed to be passed directly to the VRF
* @return The id for this request
*
* @dev Note that _vRFInputSeed is not the seed passed by the consuming
* @dev contract, but the one generated by makeVRFInputSeed
*/
function makeRequestId(
bytes32 _keyHash,
uint256 _vRFInputSeed
)
internal
pure
returns (
bytes32
)
{
return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed));
}
}
// File: @chainlink/contracts/src/v0.8/interfaces/LinkTokenInterface.sol
pragma solidity ^0.8.0;
interface LinkTokenInterface {
function allowance(
address owner,
address spender
)
external
view
returns (
uint256 remaining
);
function approve(
address spender,
uint256 value
)
external
returns (
bool success
);
function balanceOf(
address owner
)
external
view
returns (
uint256 balance
);
function decimals()
external
view
returns (
uint8 decimalPlaces
);
function decreaseApproval(
address spender,
uint256 addedValue
)
external
returns (
bool success
);
function increaseApproval(
address spender,
uint256 subtractedValue
) external;
function name()
external
view
returns (
string memory tokenName
);
function symbol()
external
view
returns (
string memory tokenSymbol
);
function totalSupply()
external
view
returns (
uint256 totalTokensIssued
);
function transfer(
address to,
uint256 value
)
external
returns (
bool success
);
function transferAndCall(
address to,
uint256 value,
bytes calldata data
)
external
returns (
bool success
);
function transferFrom(
address from,
address to,
uint256 value
)
external
returns (
bool success
);
}
// File: @chainlink/contracts/src/v0.8/VRFConsumerBase.sol
pragma solidity ^0.8.0;
/** ****************************************************************************
* @notice Interface for contracts using VRF randomness
* *****************************************************************************
* @dev PURPOSE
*
* @dev Reggie the Random Oracle (not his real job) wants to provide randomness
* @dev to Vera the verifier in such a way that Vera can be sure he's not
* @dev making his output up to suit himself. Reggie provides Vera a public key
* @dev to which he knows the secret key. Each time Vera provides a seed to
* @dev Reggie, he gives back a value which is computed completely
* @dev deterministically from the seed and the secret key.
*
* @dev Reggie provides a proof by which Vera can verify that the output was
* @dev correctly computed once Reggie tells it to her, but without that proof,
* @dev the output is indistinguishable to her from a uniform random sample
* @dev from the output space.
*
* @dev The purpose of this contract is to make it easy for unrelated contracts
* @dev to talk to Vera the verifier about the work Reggie is doing, to provide
* @dev simple access to a verifiable source of randomness.
* *****************************************************************************
* @dev USAGE
*
* @dev Calling contracts must inherit from VRFConsumerBase, and can
* @dev initialize VRFConsumerBase's attributes in their constructor as
* @dev shown:
*
* @dev contract VRFConsumer {
* @dev constuctor(<other arguments>, address _vrfCoordinator, address _link)
* @dev VRFConsumerBase(_vrfCoordinator, _link) public {
* @dev <initialization with other arguments goes here>
* @dev }
* @dev }
*
* @dev The oracle will have given you an ID for the VRF keypair they have
* @dev committed to (let's call it keyHash), and have told you the minimum LINK
* @dev price for VRF service. Make sure your contract has sufficient LINK, and
* @dev call requestRandomness(keyHash, fee, seed), where seed is the input you
* @dev want to generate randomness from.
*
* @dev Once the VRFCoordinator has received and validated the oracle's response
* @dev to your request, it will call your contract's fulfillRandomness method.
*
* @dev The randomness argument to fulfillRandomness is the actual random value
* @dev generated from your seed.
*
* @dev The requestId argument is generated from the keyHash and the seed by
* @dev makeRequestId(keyHash, seed). If your contract could have concurrent
* @dev requests open, you can use the requestId to track which seed is
* @dev associated with which randomness. See VRFRequestIDBase.sol for more
* @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind,
* @dev if your contract could have multiple requests in flight simultaneously.)
*
* @dev Colliding `requestId`s are cryptographically impossible as long as seeds
* @dev differ. (Which is critical to making unpredictable randomness! See the
* @dev next section.)
*
* *****************************************************************************
* @dev SECURITY CONSIDERATIONS
*
* @dev A method with the ability to call your fulfillRandomness method directly
* @dev could spoof a VRF response with any random value, so it's critical that
* @dev it cannot be directly called by anything other than this base contract
* @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method).
*
* @dev For your users to trust that your contract's random behavior is free
* @dev from malicious interference, it's best if you can write it so that all
* @dev behaviors implied by a VRF response are executed *during* your
* @dev fulfillRandomness method. If your contract must store the response (or
* @dev anything derived from it) and use it later, you must ensure that any
* @dev user-significant behavior which depends on that stored value cannot be
* @dev manipulated by a subsequent VRF request.
*
* @dev Similarly, both miners and the VRF oracle itself have some influence
* @dev over the order in which VRF responses appear on the blockchain, so if
* @dev your contract could have multiple VRF requests in flight simultaneously,
* @dev you must ensure that the order in which the VRF responses arrive cannot
* @dev be used to manipulate your contract's user-significant behavior.
*
* @dev Since the ultimate input to the VRF is mixed with the block hash of the
* @dev block in which the request is made, user-provided seeds have no impact
* @dev on its economic security properties. They are only included for API
* @dev compatability with previous versions of this contract.
*
* @dev Since the block hash of the block which contains the requestRandomness
* @dev call is mixed into the input to the VRF *last*, a sufficiently powerful
* @dev miner could, in principle, fork the blockchain to evict the block
* @dev containing the request, forcing the request to be included in a
* @dev different block with a different hash, and therefore a different input
* @dev to the VRF. However, such an attack would incur a substantial economic
* @dev cost. This cost scales with the number of blocks the VRF oracle waits
* @dev until it calls responds to a request.
*/
abstract contract VRFConsumerBase is VRFRequestIDBase {
/**
* @notice fulfillRandomness handles the VRF response. Your contract must
* @notice implement it. See "SECURITY CONSIDERATIONS" above for important
* @notice principles to keep in mind when implementing your fulfillRandomness
* @notice method.
*
* @dev VRFConsumerBase expects its subcontracts to have a method with this
* @dev signature, and will call it once it has verified the proof
* @dev associated with the randomness. (It is triggered via a call to
* @dev rawFulfillRandomness, below.)
*
* @param requestId The Id initially returned by requestRandomness
* @param randomness the VRF output
*/
function fulfillRandomness(
bytes32 requestId,
uint256 randomness
)
internal
virtual;
/**
* @dev In order to keep backwards compatibility we have kept the user
* seed field around. We remove the use of it because given that the blockhash
* enters later, it overrides whatever randomness the used seed provides.
* Given that it adds no security, and can easily lead to misunderstandings,
* we have removed it from usage and can now provide a simpler API.
*/
uint256 constant private USER_SEED_PLACEHOLDER = 0;
/**
* @notice requestRandomness initiates a request for VRF output given _seed
*
* @dev The fulfillRandomness method receives the output, once it's provided
* @dev by the Oracle, and verified by the vrfCoordinator.
*
* @dev The _keyHash must already be registered with the VRFCoordinator, and
* @dev the _fee must exceed the fee specified during registration of the
* @dev _keyHash.
*
* @dev The _seed parameter is vestigial, and is kept only for API
* @dev compatibility with older versions. It can't *hurt* to mix in some of
* @dev your own randomness, here, but it's not necessary because the VRF
* @dev oracle will mix the hash of the block containing your request into the
* @dev VRF seed it ultimately uses.
*
* @param _keyHash ID of public key against which randomness is generated
* @param _fee The amount of LINK to send with the request
*
* @return requestId unique ID for this request
*
* @dev The returned requestId can be used to distinguish responses to
* @dev concurrent requests. It is passed as the first argument to
* @dev fulfillRandomness.
*/
function requestRandomness(
bytes32 _keyHash,
uint256 _fee
)
internal
returns (
bytes32 requestId
)
{
LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, USER_SEED_PLACEHOLDER));
// This is the seed passed to VRFCoordinator. The oracle will mix this with
// the hash of the block containing this request to obtain the seed/input
// which is finally passed to the VRF cryptographic machinery.
uint256 vRFSeed = makeVRFInputSeed(_keyHash, USER_SEED_PLACEHOLDER, address(this), nonces[_keyHash]);
// nonces[_keyHash] must stay in sync with
// VRFCoordinator.nonces[_keyHash][this], which was incremented by the above
// successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest).
// This provides protection against the user repeating their input seed,
// which would result in a predictable/duplicate output, if multiple such
// requests appeared in the same block.
nonces[_keyHash] = nonces[_keyHash] + 1;
return makeRequestId(_keyHash, vRFSeed);
}
LinkTokenInterface immutable internal LINK;
address immutable private vrfCoordinator;
// Nonces for each VRF key from which randomness has been requested.
//
// Must stay in sync with VRFCoordinator[_keyHash][this]
mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces;
/**
* @param _vrfCoordinator address of VRFCoordinator contract
* @param _link address of LINK token contract
*
* @dev https://docs.chain.link/docs/link-token-contracts
*/
constructor(
address _vrfCoordinator,
address _link
) {
vrfCoordinator = _vrfCoordinator;
LINK = LinkTokenInterface(_link);
}
// rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF
// proof. rawFulfillRandomness then calls fulfillRandomness, after validating
// the origin of the call
function rawFulfillRandomness(
bytes32 requestId,
uint256 randomness
)
external
{
require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill");
fulfillRandomness(requestId, randomness);
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_setOwner(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_setOwner(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_setOwner(newOwner);
}
function _setOwner(address newOwner) private {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: contracts/Painter.sol
pragma solidity >=0.7.0 <0.9;
abstract contract Painter is Ownable{
event Received(address indexed _from, uint256 _amount);
uint256 public updateCost = 0;
function paint(uint256 _number) external view virtual returns(string memory);
function setUpdateCost(uint256 _cost) external onlyOwner{
updateCost = _cost;
}
function getUpdateCost() external view returns(uint256){
return updateCost;
}
receive() external payable virtual {
emit Received(msg.sender, msg.value);
}
function withdraw() external virtual onlyOwner {
// Do not remove this otherwise you will not be able to withdraw the funds.
// =============================================================================
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/token/ERC721/extensions/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
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: @openzeppelin/contracts/token/ERC721/ERC721.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol
pragma solidity ^0.8.0;
/**
* @dev This implements an optional extension of {ERC721} defined in the EIP that adds
* enumerability of all the token ids in the contract as well as all token ids owned by each
* account.
*/
abstract contract ERC721Enumerable is ERC721, IERC721Enumerable {
// Mapping from owner to list of owned token IDs
mapping(address => mapping(uint256 => uint256)) private _ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) private _ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] private _allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) private _allTokensIndex;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) {
return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) {
require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return _ownedTokens[owner][index];
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _allTokens.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view virtual override returns (uint256) {
require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds");
return _allTokens[index];
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
if (from == address(0)) {
_addTokenToAllTokensEnumeration(tokenId);
} else if (from != to) {
_removeTokenFromOwnerEnumeration(from, tokenId);
}
if (to == address(0)) {
_removeTokenFromAllTokensEnumeration(tokenId);
} else if (to != from) {
_addTokenToOwnerEnumeration(to, tokenId);
}
}
/**
* @dev Private function to add a token to this extension's ownership-tracking data structures.
* @param to address representing the new owner of the given token ID
* @param tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private {
uint256 length = ERC721.balanceOf(to);
_ownedTokens[to][length] = tokenId;
_ownedTokensIndex[tokenId] = length;
}
/**
* @dev Private function to add a token to this extension's token tracking data structures.
* @param tokenId uint256 ID of the token to be added to the tokens list
*/
function _addTokenToAllTokensEnumeration(uint256 tokenId) private {
_allTokensIndex[tokenId] = _allTokens.length;
_allTokens.push(tokenId);
}
/**
* @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that
* while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for
* gas optimizations e.g. when performing a transfer operation (avoiding double writes).
* This has O(1) time complexity, but alters the order of the _ownedTokens array.
* @param from address representing the previous owner of the given token ID
* @param tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private {
// To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = ERC721.balanceOf(from) - 1;
uint256 tokenIndex = _ownedTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary
if (tokenIndex != lastTokenIndex) {
uint256 lastTokenId = _ownedTokens[from][lastTokenIndex];
_ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
}
// This also deletes the contents at the last position of the array
delete _ownedTokensIndex[tokenId];
delete _ownedTokens[from][lastTokenIndex];
}
/**
* @dev Private function to remove a token from this extension's token tracking data structures.
* This has O(1) time complexity, but alters the order of the _allTokens array.
* @param tokenId uint256 ID of the token to be removed from the tokens list
*/
function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private {
// To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and
// then delete the last slot (swap and pop).
uint256 lastTokenIndex = _allTokens.length - 1;
uint256 tokenIndex = _allTokensIndex[tokenId];
// When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so
// rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding
// an 'if' statement (like in _removeTokenFromOwnerEnumeration)
uint256 lastTokenId = _allTokens[lastTokenIndex];
_allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token
_allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index
// This also deletes the contents at the last position of the array
delete _allTokensIndex[tokenId];
_allTokens.pop();
}
}
// File: contracts/PetNumber.sol
pragma solidity >=0.7.0 <0.9.0;
contract Proposal is Ownable {
using Strings for uint256;
uint256 constant public MIN_APPROVAL = 32768; //The minimal supply of approval
uint256 constant public MIN_SUBMIT_FEE = 100 ether; //The minimal fee to submit a proposal
uint constant public TIME_WINDOW = 2 weeks; //The active time window of the proposal
string public name; // short name
string public description; // The proposal
uint256 public askAmount; // The amount the submitter wants
uint256 public voteCountYes = 0; // number of Yes votes
uint256 public voteCountNo = 0; // number of No votes
address public submitter;
uint256 public voteReward; // This is the amount offered to incentivized voters
bool public pass = false;
uint public start;
uint public stop;
mapping (address => uint256[]) public voters;
mapping (uint256 => Voter) public petsUsed;
PetNumber public petContract;
struct Voter{
bool vote;
bool voted;
address voteAddress;
bool rewarded;
address rewardedAddress;
}
constructor(string memory _name, string memory _description,
uint256 _ask, address _submitter, PetNumber _petContract) payable {
require(msg.value >= MIN_SUBMIT_FEE, "Minimum amount not met");
name = _name;
description = _description;
askAmount = _ask;
voteReward = msg.value;
petContract = _petContract;
submitter = _submitter;
start = block.timestamp;
stop = start + TIME_WINDOW;
// Vote with tokens
castVote(true, _submitter);
}
modifier onlyActive(){
require(block.timestamp < stop, "Proposal is inactive");
_;
}
modifier onlyMature(){
require(block.timestamp >= stop, "Proposal is not mature");
_;
}
modifier onlySubmitter(){
require(msg.sender == submitter, "You are not the submitter");
_;
}
function isActive()external view returns(bool){
return block.timestamp < stop;
}
function voterWeight(bool _vote, address _voter)internal returns(uint256){
uint256 weight = 0;
uint256 petBalance = petContract.balanceOf(_voter);
for(uint256 i=0; i<petBalance; i++){
uint256 petId = petContract.tokenOfOwnerByIndex(_voter,i);
if (!petsUsed[petId].voted){
petsUsed[petId].voted = true;
petsUsed[petId].vote = _vote;
petsUsed[petId].voteAddress = _voter;
petsUsed[petId].rewarded = false;
weight++;
voters[_voter].push(petId);
}
}
return weight;
}
function castVote(bool _vote, address _voter)public onlyActive onlyOwner returns(uint256){
uint256 weight = voterWeight(_vote, _voter);
require(weight > 0, "No Pets left to vote");
if (_vote){
voteCountYes += weight;
}else{
voteCountNo += weight;
}
uint256 currHalfSupply = petContract.totalSupply() >> 1;
currHalfSupply = currHalfSupply > MIN_APPROVAL ? currHalfSupply : MIN_APPROVAL;
pass = voteCountYes > currHalfSupply && voteCountYes > voteCountNo;
return weight;
}
function getCurrentRewardByPet() public view returns(uint256){
uint256 votes = voteCountYes+voteCountNo;
if (votes == 0){
votes = 1;
}
return voteReward/votes;
}
function getCurrentTokenOfOwnerVoted(address _ownerTokens) public view returns(uint256, uint256[] memory){
uint256 petBalance = petContract.balanceOf(_ownerTokens);
uint256[] memory petsOwnerVoted = new uint256[](petBalance);
uint256 weight = 0;
for(uint256 i=0; i<petBalance; i++){
uint256 petId = petContract.tokenOfOwnerByIndex(_ownerTokens,i);
if (petsUsed[petId].voted){
petsOwnerVoted[weight] = petId;
weight++;
}
}
return (weight, petsOwnerVoted);
}
function getCurrentTokenToReward(address _ownerTokens) public view returns(uint256, uint256[] memory){
uint256 petBalance = petContract.balanceOf(_ownerTokens);
uint256[] memory petsOwnerToReward = new uint256[](petBalance);
uint256 weight = 0;
for(uint256 i=0; i<petBalance; i++){
uint256 petId = petContract.tokenOfOwnerByIndex(_ownerTokens,i);
if (petsUsed[petId].voted && !petsUsed[petId].rewarded){
petsOwnerToReward[weight] = petId;
weight++;
}
}
return (weight, petsOwnerToReward);
}
function getCurrentRewardBalanceByHolder(address _ownerTokens) public view returns(uint256){
uint256 petBalance = petContract.balanceOf(_ownerTokens);
uint256 weight = 0;
for(uint256 i=0; i<petBalance; i++){
uint256 petId = petContract.tokenOfOwnerByIndex(_ownerTokens,i);
if (petsUsed[petId].voted && !petsUsed[petId].rewarded){
weight++;
}
}
return weight*getCurrentRewardByPet();
}
function claimReward(address _holder) external onlyMature onlyOwner returns(uint256){
uint256 rewardByPet = getCurrentRewardByPet();
uint256 weight;
uint256[] memory petsOwnerToReward;
(weight, petsOwnerToReward) = getCurrentTokenToReward(_holder);
uint256 reward = rewardByPet * weight;
// require(reward > 0, "Reward is zero");
(bool os, ) = payable(_holder).call{value: reward}("");
require(os);
//Now set them to true
for(uint256 i=0; i < weight; i++){
petsUsed[petsOwnerToReward[i]].rewarded = true;
petsUsed[petsOwnerToReward[i]].rewardedAddress = _holder;
}
return reward;
}
function changeSubmitter(address _newSubmitter) external onlyOwner{
submitter = _newSubmitter;
}
function Passed() external view returns(bool){
return pass && (block.timestamp >= stop);
}
function Rejected() external view returns(bool){
return !pass && (block.timestamp >= stop);
}
}
// import "./PetGrants.sol";
contract PetGrants is Ownable {
using Strings for uint256;
uint256 constant public MIN_SUBMIT_FEE = 100 ether; //The minimal fee to submit a proposal
uint256 constant public MAX_ASK_AMOUNT = 100000 ether; //The maximum amount to ask for each proposal
event Received(address indexed _from, uint256 _amount);
event UpdatePetAddress(address indexed _from, address indexed _petAddress);
event ProposalSubmitted(address indexed _from, uint256 indexed _proposalId, string _name, uint256 _askAmount, uint256 _voteReward);
event VoteCasted(address indexed _from, uint256 indexed _proposalId, uint256 _weight, bool _vote);
event ClaimGranted(address indexed _to, uint256 indexed _proposalId, uint256 _askAmount);
event RewardClaimed(address indexed _to, uint256 indexed _proposalId, uint256 _askAmount);
event AllRewardsClaimed(address indexed _to, uint256 _askAmount);
event SubmitterChanged(address indexed _old, address indexed _new);
PetNumber public petContract;
mapping(uint256 => Proposal) public proposals;
uint256 public proposalsSupply = 0;
uint256 public promisedAmount = 0;
uint256[] public activePropIds;
mapping(uint256 => bool) public claimedPropIds;
mapping(uint256 => bool) public rejectedPropIds;
constructor(PetNumber _petContract){
petContract = _petContract;
}
modifier onlyPetHolder(){
require(petContract.balanceOf(msg.sender) > 0, "You need to hold at least one Pet Number");
_;
}
modifier validPropId(uint256 _propId){
require(_propId <= proposalsSupply, "Not a valid id");
require(_propId > 0, "Not a valid id");
_;
}
function submitProposal(string calldata _name, string calldata _description, uint256 _askAmount ) external payable onlyPetHolder{
require(msg.value >= MIN_SUBMIT_FEE,"Need 100 or more");
require(_askAmount <= MAX_ASK_AMOUNT, "Ask Amount need to be equal or less than 100K");
updateActivePropsId();
require(_askAmount + msg.value <= getAvailableBalance(), "Ask Amount need to be equal or less than Balance");
require(petContract.totalSupply() > petContract.MAX_INITIAL_SUPPLY()>>1, "Need more supply of Pets" );
Proposal newProposal = new Proposal{value: msg.value}(_name, _description,
_askAmount, msg.sender, petContract);
proposals[proposalsSupply+1] = newProposal;
proposalsSupply++;
activePropIds.push(proposalsSupply);
promisedAmount = promisedAmount + _askAmount;
emit ProposalSubmitted(msg.sender, proposalsSupply, _name, _askAmount, msg.value);
}
// @dev Receive the share from the NFT Contract
receive() external payable{
emit Received(msg.sender, msg.value);
}
function claimGrant(uint256 _proposalId) external onlyPetHolder{
require(!claimedPropIds[_proposalId], "Already claimed");
Proposal claimProposal = proposals[_proposalId];
require(claimProposal.submitter() == msg.sender, "Not the submitter of this proposal");
require(claimProposal.Passed(), "Proposal didn't passed or still under voting");
uint256 amount = claimProposal.askAmount();
(bool os, ) = payable(msg.sender).call{value: amount}("");
require(os);
promisedAmount = promisedAmount - amount;
claimedPropIds[_proposalId] = true;
emit ClaimGranted(msg.sender, _proposalId, amount);
}
function getAvailableBalance() public view returns(uint256){
uint256 bal = address(this).balance;
return bal > promisedAmount ? bal - promisedAmount : 0;
}
function updateActivePropsId() internal {
for (uint256 i=0; i < activePropIds.length; i++){
Proposal prop = proposals[activePropIds[i]];
if (!prop.isActive() && claimedPropIds[activePropIds[i]]){
activePropIds[i] = activePropIds[activePropIds.length-1];
activePropIds.pop();
}else{
if (prop.Rejected()){
rejectedPropIds[activePropIds[i]] = true;
promisedAmount = promisedAmount - prop.askAmount();
activePropIds[i] = activePropIds[activePropIds.length-1];
activePropIds.pop();
}
}
}
}
function getPotentialRewardBalance(address _holderAddr)external view returns(uint256){
uint256 balance = 0;
for (uint256 i = 1; i <= proposalsSupply; i++){
Proposal prop = proposals[i];
balance += prop.getCurrentRewardBalanceByHolder(_holderAddr);
}
return balance;
}
function getMaturedRewardBalance(address _holderAddr)external view returns(uint256){
uint256 balance = 0;
for (uint256 i = 1; i <= proposalsSupply; i++){
Proposal prop = proposals[i];
if (!prop.isActive()){
balance += prop.getCurrentRewardBalanceByHolder(_holderAddr);
}
}
return balance;
}
function claimRewards()external {
uint256 rewards = 0;
for (uint256 i = 1; i <= proposalsSupply; i++){
Proposal prop = proposals[i];
if (!prop.isActive()){
rewards += prop.claimReward(msg.sender);
}
}
require(rewards > 0, "Not rewards present");
emit AllRewardsClaimed(msg.sender, rewards);
}
function changeSubmitter(uint256 _propId, address _newSubmitter) external validPropId(_propId){
Proposal prop = proposals[_propId];
require(prop.submitter() == msg.sender, "You need to be the submitter");
prop.changeSubmitter(_newSubmitter);
emit SubmitterChanged(msg.sender, _newSubmitter);
}
function castVote(uint256 _propId, bool _vote) external validPropId(_propId){
Proposal prop = proposals[_propId];
uint256 weight = prop.castVote(_vote, msg.sender);
emit VoteCasted(msg.sender, _propId, weight, _vote);
}
function claimReward(uint256 _propId)external validPropId(_propId) {
Proposal prop = proposals[_propId];
uint256 rewards = prop.claimReward(msg.sender);
require(rewards > 0, "Not rewards present");
emit RewardClaimed(msg.sender, _propId, rewards);
}
function proposalPassed(uint256 _propId) external validPropId(_propId) view returns(bool){
Proposal prop = proposals[_propId];
return prop.Passed();
}
function proposalIsActive(uint256 _propId) external validPropId(_propId) view returns(bool){
Proposal prop = proposals[_propId];
return prop.isActive();
}
}
contract PetNumber is ERC721Enumerable, VRFConsumerBase, Ownable, Painter {
using Strings for uint256;
bytes32 private s_keyHash;
uint256 private s_fee;
uint256 private randomNumberLink;
bytes32 public requestIdLink;
uint256 constant public OWNER_MAX_RESERVED = 1024;
uint256 public ownerReserved = OWNER_MAX_RESERVED;
uint256 constant public MAX_INITIAL_SUPPLY = 65536;
mapping(uint256 => uint256) public numbers;
mapping(uint256 => address) public tokenToPainterAddr;
address public defaultPainterAddress = address(this);
address public grantsAddress;
event UpdatePainterAddress(address indexed _from, uint256[] _tokenIdList, address indexed _painterAddr, uint256 _value);
event RewardPainter(address indexed _painterAddr, uint256 _amount);
event SendFunds(address indexed _to, uint256 _amount);
/**
* Polygon Mainnet
* LINK Token 0xb0897686c545045aFc77CF20eC7A532E3120E0F1
* VRF Coordinator 0x3d2341ADb2D31f1c5530cDC622016af293177AE0
* Key Hash 0xf86195cf7690c55907b2b611ebb7343a6f649bff128701cc542f0569e2c549da
* Fee 0.0001 LINK
* ---------
* Polygon Mumbai Testnet
* LINK Token 0x326C977E6efc84E512bB9C30f76E30c160eD06FB
* VRF Coordinator 0x8C7382F9D8f56b33781fE506E897a4F1e2d17255
* Key Hash 0x6e75b569a01ef56d18cab6a8e71e6600d6ce853834d4a5748b720d06f878b3a4
* Fee 0.0001 LINK 1000000000000000
**/
constructor(address _VRFCoordinator, address _LinkToken, bytes32 _keyHash, uint256 _fee)
VRFConsumerBase(_VRFCoordinator, _LinkToken)
ERC721("Pet Number", "PET") {
s_keyHash = _keyHash;
s_fee = _fee;
PetGrants grants = new PetGrants(this);
grantsAddress = address(grants);
}
/**
* Requests randomness
*/
function getRandomNumber() public onlyOwner returns (bytes32 requestId) {
require(LINK.balanceOf(address(this)) >= s_fee, "Not enough LINK - fill contract with faucet");
return requestRandomness(s_keyHash, s_fee);
}
/**
* Callback function used by VRF Coordinator
*/
function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
randomNumberLink = randomness;
requestIdLink = requestId;
}
function withdrawLink() external onlyOwner{
require(LINK.transfer(msg.sender, LINK.balanceOf(address(this))), "Unable to transfer");
}
function byteMaker(uint256 _randomValue) private pure returns (uint8){
uint r = _randomValue % 2560;
if (r>=10) return uint8(_randomValue % 252) + 4; //0.39%
if (r>=6 && r<10) return 3; //0.15%
if (r>=3 && r<6) return 2; //0.12%
if (r>=1 && r<3) return 1; //0.09%
return 0; //0.04%
}
function petMaker(uint256 _randomValue) private pure returns (uint256) {
uint256 number=0;
for (uint256 i = 0; i < 32; i++) {
number = (number<<8) | byteMaker(uint256(keccak256(abi.encode(_randomValue, i))));
}
return number;
}
function getPrice() public view returns (uint256) {
uint256 supply = totalSupply();
return (supply>>9) * 0.5 ether;
}
function getBreedingCost() public view returns (uint256) {
uint256 supply = totalSupply();
return (supply>>10) * 0.2 ether + 40 ether;
}
function _sendFundsToGrants() internal{
uint256 amount = msg.value >> 2; //divide by 4
(bool os, ) = payable(grantsAddress).call{value: amount}("");
require(os, "Error sending to Grants");
emit SendFunds(grantsAddress, amount);
}
function mint() external payable {
uint256 supply = totalSupply();
require(supply + 1 + ownerReserved <= MAX_INITIAL_SUPPLY, "Supply limit reached for users");
require(msg.value >= getPrice(), "Not enough money");
numbers[supply+1] = petMaker(random256(randomNumberLink, supply+1));
_safeMint(msg.sender, supply + 1);
tokenToPainterAddr[supply+1] = defaultPainterAddress;
_sendFundsToGrants();
}
function mintByOwner() external onlyOwner {
uint256 supply = totalSupply();
require(ownerReserved > 0, "Supply reserved limit reached");
numbers[supply+1] = petMaker(random256(randomNumberLink, supply+1));
_safeMint(msg.sender, supply + 1);
tokenToPainterAddr[supply+1] = defaultPainterAddress;
ownerReserved--;
}
function getPetNumber(uint256 _tokenId) public view returns(uint256){
require(
_exists(_tokenId),
"Nonexistent token"
);
return numbers[_tokenId];
}
function getPetNumberHex(uint256 _tokenId) public view returns(string memory){
require(
_exists(_tokenId),
"Nonexistent token"
);
return numbers[_tokenId].toHexString(32);
}
function getPetTraits(uint256 _tokenId) public view returns(uint8 zeros, uint8 ones, uint8 twos, uint8 threes){
require(
_exists(_tokenId),
"Nonexistent token"
);
uint256 tmp = numbers[_tokenId];
zeros=0;
ones=0;
twos=0;
threes=0;
for (uint8 i=0; i<32;i++){
uint256 value = tmp & 255;
if (value == 0){
zeros++;
}else if (value == 1){
ones++;
}else if (value == 2){
twos++;
}else if (value == 3){
threes++;
}
tmp >>= 8;
}
}
function random256(uint256 _seed, uint256 _salt)public view returns (uint256){
return uint256(keccak256(abi.encodePacked(block.timestamp, msg.sender, _seed, _salt)));
}
function updateDefaultPainter(address _painterAddr) external onlyOwner{
defaultPainterAddress = _painterAddr;
}
function _updateSinglePainter(uint256 _tokenId, address _painterAddr) internal virtual{
require(
_exists(_tokenId),
"Token Id does not exists"
);
require(
msg.sender == ownerOf(_tokenId),
"No owner of this Pet"
);
tokenToPainterAddr[_tokenId] = _painterAddr;
}
function _incentivizePainter(address _painterAddr, uint256 _amount) internal virtual{
_amount = uint256((_amount*90)/100); // send the 90% to the painter
(bool os, ) = payable(_painterAddr).call{value: _amount}("");
require(os, "Error rewarding painter");
emit RewardPainter(_painterAddr, _amount);
}
function getPainterUpdateCost(address _painterAddr) public view returns(uint256){
Painter painter = Painter(payable(_painterAddr));
return painter.getUpdateCost();
}
function updatePainter(uint256[] calldata _tokenIdList, address _painterAddr) external payable{
if (msg.sender != owner()){
require(
msg.value >= getPainterUpdateCost(_painterAddr),
"No enough money to update painter"
);
}
for(uint256 i=0; i<_tokenIdList.length;i++){
_updateSinglePainter(_tokenIdList[i], _painterAddr);
}
if (msg.sender != owner()){
_incentivizePainter(_painterAddr,msg.value);
}
emit UpdatePainterAddress(msg.sender, _tokenIdList, _painterAddr, msg.value);
}
function updatePainter(address _painterAddr) external payable{
uint256 _balance = balanceOf(msg.sender);
require(_balance>0, "You have no Pets");
if (msg.sender != owner()){
require(
msg.value >= getPainterUpdateCost(_painterAddr),
"No enough money to update painter"
);
}
uint256[] memory _tokenIdList = new uint256[](_balance);
for(uint256 i=0; i<_balance;i++){
uint256 _tokenId = tokenOfOwnerByIndex(msg.sender, i);
tokenToPainterAddr[_tokenId] = _painterAddr;
_tokenIdList[i] = _tokenId;
}
if (msg.sender != owner()){
_incentivizePainter(_painterAddr, msg.value);
}
emit UpdatePainterAddress(msg.sender, _tokenIdList, _painterAddr, msg.value);
}
function paint(uint256 number)external pure override returns(string memory){
uint256 bg1 = (number&65535)%361;
uint256 bg2 = ((number>>16)&65535)%361;
uint256 fg = ((number>>32)&65535)%361;
uint256 angle = ((number>>48)&65535)%361;
string memory fgStr = fg.toString();
string memory textSvg = string(abi.encodePacked(
'<text y="125" fill="hsl(',fgStr,',100%, 80%)"><tspan font-family = "monospace" x="4.34% 8.68% 13.02% 17.36% 21.7% 26.04% 30.38% 34.72% 39.06% 43.4% 47.74% 52.08% 56.42% 60.76% 65.1% 69.44% 73.78% 78.12% 82.46% 86.8% 91.14% 95.48% 4.34% 8.68% 13.02% 17.36% 21.7% 26.04% 30.38% 34.72% 39.06% 43.4% 47.74% 52.08% 56.42% 60.76% 65.1% 69.44% 73.78% 78.12% 82.46% 86.8% 91.14% 95.48% 4.34% 8.68% 13.02% 17.36% 21.7% 26.04% 30.38% 34.72% 39.06% 43.4% 47.74% 52.08% 56.42% 60.76% 65.1% 69.44% 73.78% 78.12% 82.46% 86.8% 91.14% 95.48%" dy="0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 125 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 125 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0">',
number.toHexString(32),
'</tspan></text>'
));
string memory rectsSvg ='';
string[3] memory ys = ["375", "250", "125"];
string[3] memory cys = ["391", "266", "141"];
string[11] memory xs = ["455.7", "412.3", "368.9", "325.5", "282.1", "238.7", "195.3", "151.9", "108.5", "65.1", "21.7"];
uint256 tmp = number;
string memory points ='';
for (uint8 i=0; i<32;i++){
uint256 value = tmp & 255;
uint256 angChrom = uint256(tmp)%361;
if (value < 4){
rectsSvg = string(abi.encodePacked(
'<rect width="32" height="32" fill="hsla(',angChrom.toString(),',69%,22%,1)" x="',xs[i%11],'" y="',ys[i/11],'"/>',
rectsSvg
));
points = string(abi.encodePacked(
points,
xs[i%11],',',cys[i/11],' '
));
}else if (value >= 4 && value <= 58){
rectsSvg = string(abi.encodePacked(
'<circle r="16" fill="hsla(',angChrom.toString(),',69%,22%,1)" cx="',xs[i%11],'" cy="',cys[i/11],'"/>',
rectsSvg
));
points = string(abi.encodePacked(
points,
xs[i%11],',',cys[i/11],' '
));
}
tmp >>= 8;
}
string memory polygon = string(abi.encodePacked(
'<polygon points="',points,'" fill="hsla(',fgStr,', 69%, 22%, 0.57)" stroke="white" stroke-width="20" stroke-opacity="25%"/>'
));
textSvg = string(abi.encodePacked(textSvg, rectsSvg, polygon));
return string(abi.encodePacked(
'<svg xmlns="http://www.w3.org/2000/svg" width="500" height="500" font-size="32" text-anchor="middle">',
'<defs><linearGradient id="nG" gradientTransform="rotate(',angle.toString(),')"><stop offset="5%" stop-color="hsl(',bg1.toString(),',50%, 25%)"/>',
'<stop offset="95%" stop-color="hsl(',bg2.toString(),',50%, 25%)"/></linearGradient></defs>',
'<rect width="500" height="500" fill="url(\'#nG\')"/>',
textSvg,
'</svg>'
));
}
function getPainterImage(uint256 _tokenId)public view returns(string memory){
require(
_exists(_tokenId),
"ERC721Metadata: Image query for nonexistent token"
);
Painter painter = Painter(payable(tokenToPainterAddr[_tokenId]));
return painter.paint(numbers[_tokenId]);
}
function getImageURI(uint256 _tokenId)public view returns(string memory){
return string(abi.encodePacked('data:image/svg+xml;base64,'
,Base64.encode(bytes(
getPainterImage(_tokenId)
))));
}
function getAttributes(uint256 _tokenId) public view returns(string memory){
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
uint256 zeros=0;
uint256 ones=0;
uint256 twos=0;
uint256 threes=0;
(zeros, ones, twos, threes) = getPetTraits(_tokenId);
return string(abi.encodePacked(
'[{"display_type":"number","trait_type":"zeros","value":', zeros.toString(),
'},{"display_type":"number","trait_type":"ones","value":', ones.toString(),
'},{"display_type":"number","trait_type":"twos","value":', twos.toString(),
'},{"display_type":"number","trait_type":"threes","value":', threes.toString(),
'}]'
));
}
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(_tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
return string(abi.encodePacked(
'data:application/json;base64,', Base64.encode(bytes(abi.encodePacked(
'{"name":"',
'Pet Number ',
_tokenId.toString(),
'","description":"',
'Since almost all NFT are encoded in a number, we went ahead and created a Pet Number which is the number itself. ',
'A blank canvas for your imagination. You can turn your Pet Number in a dog, a robot, a sword, etc. ',
'and play with your Pet on all the Pet-friendly games ;) All data is stored onchain. It has 32 bytes and each one represent a feature with up to 256 possibles traits. ',
'The rarity is created per feature (byte) with probabilities of 0.04% for 0, 0.09% for 1, 0.12% for 2, 0.15% for 3 and 0.39% for numbers 4 to 255."',
',"image":"',
getImageURI(_tokenId),'"',
', "attributes":',
getAttributes(_tokenId),
'}')))
));
}
function breed(uint256 _tokenId1, uint256 _tokenId2) public payable {
uint256 supply = totalSupply();
require(supply + 1 + ownerReserved > MAX_INITIAL_SUPPLY, "The total supply is too low");
require(ownerOf(_tokenId1) == msg.sender, "You are not the owner of token 1");
require(ownerOf(_tokenId2) == msg.sender, "You are not the owner of token 2");
require(msg.value >= getBreedingCost(), "Not enought money");
uint256 number1 = getPetNumber(_tokenId1);
uint256 number2 = getPetNumber(_tokenId2);
uint256 numberOut = 0;
for (uint i=0; i<256; i++){
uint b1 = number1 % 2;
number1 = number1 >> 1;
uint b2 = number2 % 2;
number2 = number2 >> 1;
uint256 bOut = b1;
if (b1 != b2){
bOut = random256(randomNumberLink, supply+1+i) % 2;
}
uint256 mutationSpace = random256(randomNumberLink, supply+1+i+block.timestamp) % 2560; //1 in 10 pets get a mutation
if (mutationSpace == 0){
bOut = bOut^1;
}
require(bOut<=1, "Something weird happened");
numberOut = (bOut << i) | numberOut;
}
numbers[supply+1] =numberOut;
_safeMint(msg.sender, supply + 1);
tokenToPainterAddr[supply+1] = defaultPainterAddress;
_sendFundsToGrants();
}
function withdraw() external override onlyOwner {
// Do not remove this otherwise you will not be able to withdraw the funds.
// =============================================================================
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
// =============================================================================
}
function getBalanceGrants()external view returns(uint256){
return address(grantsAddress).balance;
}
}
| Callback function used by VRF Coordinator/ | function fulfillRandomness(bytes32 requestId, uint256 randomness) internal override {
randomNumberLink = randomness;
requestIdLink = requestId;
}
| 13,042,196 |
./full_match/8453/0x69298fFe05627268D32dd32762e364bfeb42206b/sources/src/JoeV21LegacyDexLens.sol | Returns the price of token in USD, scaled with 6 decimals _token The address of the token return price The price of the token in USD, with 6 decimals | function getTokenPriceUSD(address _token) external view override returns (uint256 price) {
return _getTokenWeightedAveragePrice(_USDC, _token);
}
| 11,556,648 |
./full_match/42161/0x471E35C0D689564E31f4476a1f8fa7a7cd626c15/sources/contracts/GaurVault1_ERC4626.sol | Burns exactly shares from owner and sends assets of underlying tokens to receiver. MUST emit the Withdraw event. MUST support a redeem flow where the shares are burned from owner directly where owner is msg.sender. MUST support a redeem flow where the shares are burned from owner directly where msg.sender has ERC-20 approval over the shares of owner. MAY support an additional flow in which the shares are transferred to the Vault contract before the redeem execution, and are accounted for during redeem. MUST revert if all of shares cannot be redeemed (due to withdrawal limit being reached, slippage, the owner not having enough shares, etc). Note that some implementations will require pre-requesting to the Vault before a withdrawal may be performed. Those methods should be performed separately. | function redeem(
uint256 shares,
address receiver,
address owner
) external override returns (uint256 assets) {
if (msg.sender != owner) _spendAllowance(owner, msg.sender, shares);
assets = _withdraw(shares, receiver, owner);
}
| 16,303,434 |
./full_match/5/0xd98398a279434A5ACE8cBB8ed72C4bAeA1221377/sources/contracts/L1/delegation/DelegationManager.sol | Called by a staker to queue a withdraw in the given token and shareAmount from each of the respective given strategies. Stakers will complete their withdrawal by calling the 'completeQueuedWithdrawal' function. User shares are decreased in this function, but the total number of shares in each delegation contract remains the same. The total number of shares is decremented in the 'completeQueuedWithdrawal' function instead, which is where the funds are actually sent to the user through use of the strategies' 'withdrawal' function. This ensures that the value per share reported by each delegation contract will remain consistent, and that the shares will continue to accrue gains during the enforced WITHDRAWAL_WAITING_PERIOD. delegationIndexes is a list of the indices in `investorStrats[msg.sender]` that correspond to the strategies for which `msg.sender` is withdrawing 100% of their shares strategies are removed from `investorStrats` by swapping the last entry with the entry to be removed, then popping off the last entry in `investorStrats`. The simplest way to calculate the correct `delegationIndexes` to input is to order the strategies for which `msg.sender` is withdrawing 100% of their shares from highest index in `investorStrats` to lowest index/ increment the numWithdrawalsQueued of the sender the internal function will return 'true' in the event the delegation contrat was removed from the depositor's array of strategies -- i.e. investorStrats[depositor]increment the loop copy arguments into struct and pull delegation infoupdate storage in mapping of queued withdrawals If the `msg.sender` has withdrawn all of their funds in this transaction, then they can choose to also undelegate Checking that `investorStrats[msg.sender].length == 0` is not strictly necessary here, but prevents reverting very late in logic, in the case that 'undelegate' is set to true but the `msg.sender` still has active deposits./ | function queueWithdrawal(
uint256[] calldata delegationIndexes,
IDelegationShare[] calldata delegationShares,
IERC20[] calldata tokens,
uint256[] calldata shares,
WithdrawerAndNonce calldata withdrawerAndNonce,
bool undelegateIfPossible
)
external
virtual
whenNotPaused
onlyNotFrozen(msg.sender)
nonReentrant
returns (bytes32)
{
require(
withdrawerAndNonce.nonce == numWithdrawalsQueued[msg.sender],
"DelegationManager.queueWithdrawal: provided nonce incorrect"
);
unchecked {
++numWithdrawalsQueued[msg.sender];
}
uint256 delegationIndex;
for (uint256 i = 0; i < delegationShares.length;) {
if (_removeShares(msg.sender, delegationIndexes[delegationIndex], delegationShares[i], shares[i])) {
unchecked {
++delegationIndex;
}
}
unchecked {
++i;
}
}
QueuedWithdrawal memory queuedWithdrawal = QueuedWithdrawal({
delegations: delegationShares,
tokens: tokens,
shares: shares,
depositor: msg.sender,
withdrawerAndNonce: withdrawerAndNonce,
delegatedAddress: delegatedAddress
});
queuedWithdrawals[withdrawalRoot] = WithdrawalStorage({
initTimestamp: uint32(block.timestamp + REASONABLE_STAKES_UPDATE_PERIOD),
withdrawer: withdrawerAndNonce.withdrawer,
unlockTimestamp: QUEUED_WITHDRAWAL_INITIALIZED_VALUE
if (undelegateIfPossible && investorDelegations[msg.sender].length == 0) {
_undelegate(msg.sender);
}
emit WithdrawalQueued(msg.sender, withdrawerAndNonce.withdrawer, delegatedAddress, withdrawalRoot);
return withdrawalRoot;
}
| 7,039,318 |
./full_match/80001/0xc7A7f372D1f1b06CBa2e0CcEaf3e691eF8A7270f/sources/project_/contracts/GreenFinancing.sol | update property data | ) public virtual {
require(
account == _msgSender() || isApprovedForAll(account, _msgSender()),
"ERC1155: caller is not token owner or approved"
);
_burnBatch(account, ids, values);
function burnBatch(
address account,
uint256[] memory ids,
uint256[] memory values
for (uint256 i = 0; i < ids.length; i++) {
TokenProperty storage _token_property = token_property[ids[i]];
Property storage property = properties[_token_property.propertyId];
property.totalBurned++ ;
}
}
| 5,627,544 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.10;
// create one more contract containing
// one random number generation variable
contract Oracle {
address admin;
uint256 public rand;
constructor( ){
admin = msg.sender;
}
function invokeRandomness(uint256 _rand) external {
require(msg.sender == admin, "only admin");
rand = _rand;
}
}
contract RandomNumber{
// set contract instance
Oracle oracle;
uint256 nonce;
constructor(address oracleAddress) {
// initialize the instance with address
oracle = Oracle(oracleAddress);
}
function unsafe_Randness(uint256 mod) external view returns(uint256) {
// this way of random number is not recommended since miner can
// manipulate the variables related to blocks.
return uint(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
msg.sender))) % mod;
}
function safe_Randomness() external returns(uint256) {
uint256 rand = uint256(keccak256(abi.encodePacked(
// add nonce(private var), oracle.rand(another contract var)
// to secure random number
nonce, oracle.rand, block.difficulty, msg.sender
)));
nonce++;
return rand;
}
} | this way of random number is not recommended since miner can manipulate the variables related to blocks. | function unsafe_Randness(uint256 mod) external view returns(uint256) {
return uint(
keccak256(
abi.encodePacked(
block.timestamp,
block.difficulty,
msg.sender))) % mod;
}
| 5,391,845 |
./full_match/1/0x64ab2027CC959120e1f661d46CdD85C336a25b2f/sources/contracts/mixins/AuctionSellingAgreementProvider.sol | see {IExchangeArtNFTMarketAuction - cancelAuctionSellingAgreement}/ Remove the auction. | function cancelAuctionSellingAgreement(
uint256 auctionId
) external nonReentrant {
AuctionBasicState memory auction = auctionIdToAuctionBasicState[auctionId];
IERC721 nftContract = IERC721(auction.nftContract);
auction.callerMustBeSeller(msg.sender);
auction.mustExist();
auction.mustNotHaveBids();
delete nftContractToTokenIdToAuctionId[auction.nftContract][
auction.tokenId
];
delete auctionIdToAuctionBasicState[auctionId];
if (!auction.isStandardAuction) {
delete auctionIdToAuctioAdditionalConfigurations[auctionId];
}
nftContract.transferFrom(address(this), msg.sender, auction.tokenId);
emit AuctionSellingAgreementCancelled(
auction.nftContract,
auction.tokenId,
auctionId,
auction.seller
);
}
| 17,129,102 |
//Address: 0x1bd3435b7db7dd77753b1283e2a9d751f000367b
//Contract name: WitToken
//Balance: 0 Ether
//Verification Date: 6/18/2018
//Transacion Count: 3
// CODE STARTS HERE
pragma solidity 0.4.24;
//@title WitToken
//@author([email protected])
//@dev 该合约参考自openzeppelin的erc20实现
//1.使用openzeppelin的SafeMath库防止运算溢出
//2.使用openzeppelin的Ownable,Roles,RBAC来做权限控制,自定义了ceo,coo,cro等角色
//3.ERC20扩展了ERC20Basic,实现了授权转移
//4.BasicToken,StandardToken,PausableToken均是erc20的具体实现
//5.BlackListToken加入黑名单方法
//6.TwoPhaseToken可以发行和赎回资产,并采用经办复核的二阶段提交
//7.UpgradedStandardToken参考自TetherUSD合约,可以在另一个合约升级erc20的方法
//8.可以设置交易的手续费率
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Roles
* @author Francisco Giordano (@frangio)
* @dev Library for managing addresses assigned to a Role.
* See RBAC.sol for example usage.
*/
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];
}
}
/**
* @title RBAC (Role-Based Access Control)
* @author Matt Condon (@Shrugs)
* @dev Stores and provides setters and getters for roles and addresses.
* Supports unlimited numbers of roles and addresses.
* See //contracts/mocks/RBACMock.sol for an example of usage.
* This RBAC method uses strings to key roles. It may be beneficial
* for you to write your own implementation of this interface using Enums or similar.
* It's also recommended that you define constants in the contract, like ROLE_ADMIN below,
* to avoid typos.
*/
contract RBAC is Ownable {
using Roles for Roles.Role;
mapping (string => Roles.Role) private roles;
event RoleAdded(address addr, string roleName);
event RoleRemoved(address addr, string roleName);
/**
* A constant role name for indicating admins.
*/
string public constant ROLE_CEO = "ceo";
string public constant ROLE_COO = "coo";//运营
string public constant ROLE_CRO = "cro";//风控
string public constant ROLE_MANAGER = "manager";//经办员
string public constant ROLE_REVIEWER = "reviewer";//审核员
/**
* @dev constructor. Sets msg.sender as ceo by default
*/
constructor() public{
addRole(msg.sender, ROLE_CEO);
}
/**
* @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 internal {
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);
}
function ownerAddCeo(address addr) onlyOwner public {
addRole(addr, ROLE_CEO);
}
function ownerRemoveCeo(address addr) onlyOwner public{
removeRole(addr, ROLE_CEO);
}
function ceoAddCoo(address addr) onlyCEO public {
addRole(addr, ROLE_COO);
}
function ceoRemoveCoo(address addr) onlyCEO public{
removeRole(addr, ROLE_COO);
}
function cooAddManager(address addr) onlyCOO public {
addRole(addr, ROLE_MANAGER);
}
function cooRemoveManager(address addr) onlyCOO public {
removeRole(addr, ROLE_MANAGER);
}
function cooAddReviewer(address addr) onlyCOO public {
addRole(addr, ROLE_REVIEWER);
}
function cooRemoveReviewer(address addr) onlyCOO public {
removeRole(addr, ROLE_REVIEWER);
}
function cooAddCro(address addr) onlyCOO public {
addRole(addr, ROLE_CRO);
}
function cooRemoveCro(address addr) onlyCOO public {
removeRole(addr, ROLE_CRO);
}
/**
* @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 ceo
* // reverts
*/
modifier onlyCEO() {
checkRole(msg.sender, ROLE_CEO);
_;
}
/**
* @dev modifier to scope access to coo
* // reverts
*/
modifier onlyCOO() {
checkRole(msg.sender, ROLE_COO);
_;
}
/**
* @dev modifier to scope access to cro
* // reverts
*/
modifier onlyCRO() {
checkRole(msg.sender, ROLE_CRO);
_;
}
/**
* @dev modifier to scope access to manager
* // reverts
*/
modifier onlyMANAGER() {
checkRole(msg.sender, ROLE_MANAGER);
_;
}
/**
* @dev modifier to scope access to reviewer
* // reverts
*/
modifier onlyREVIEWER() {
checkRole(msg.sender, ROLE_REVIEWER);
_;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
*
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic, RBAC {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
uint256 public basisPointsRate;//手续费率
uint256 public maximumFee;//最大手续费
address public assetOwner;//收取的手续费和增发的资产都到这个地址上, 赎回资产时会从这个地址销毁资产
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
uint256 fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
uint256 sendAmount = _value.sub(fee);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
if (fee > 0) {
balances[assetOwner] = balances[assetOwner].add(fee);
emit Transfer(msg.sender, assetOwner, fee);
}
emit Transfer(msg.sender, _to, sendAmount);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
uint256 fee = (_value.mul(basisPointsRate)).div(10000);
if (fee > maximumFee) {
fee = maximumFee;
}
uint256 sendAmount = _value.sub(fee);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(sendAmount);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
if (fee > 0) {
balances[assetOwner] = balances[assetOwner].add(fee);
emit Transfer(_from, assetOwner, fee);
}
emit Transfer(_from, _to, sendAmount);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is RBAC {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the ceo to pause, triggers stopped state
*/
function pause() onlyCEO whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the ceo to unpause, returns to normal state
*/
function unpause() onlyCEO whenPaused public {
paused = false;
emit Unpause();
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
contract BlackListToken is PausableToken {
function getBlackListStatus(address _maker) external view returns (bool) {
return isBlackListed[_maker];
}
mapping (address => bool) public isBlackListed;
function addBlackList (address _evilUser) public onlyCRO {
isBlackListed[_evilUser] = true;
emit AddedBlackList(_evilUser);
}
function removeBlackList (address _clearedUser) public onlyCRO {
isBlackListed[_clearedUser] = false;
emit RemovedBlackList(_clearedUser);
}
function destroyBlackFunds (address _blackListedUser) public onlyCEO {
require(isBlackListed[_blackListedUser]);
uint dirtyFunds = balanceOf(_blackListedUser);
balances[_blackListedUser] = 0;
totalSupply_ = totalSupply_.sub(dirtyFunds);
emit DestroyedBlackFunds(_blackListedUser, dirtyFunds);
}
event DestroyedBlackFunds(address _blackListedUser, uint _balance);
event AddedBlackList(address _user);
event RemovedBlackList(address _user);
}
/**
* 增发和赎回token由经办人和复核人配合完成
* 1.由经办人角色先执行submitIssue或submitRedeem;
* 2.复核人角色再来执行comfirmIsses或comfirmRedeem;
* 3.两者提交的参数一致,则增发和赎回才能成功
* 4.经办人提交数据后,复核人执行成功后,需要经办人再次提交才能再次执行
**/
contract TwoPhaseToken is BlackListToken{
//保存经办人提交的参数
struct MethodParam {
string method; //方法名
uint value; //增发或者赎回的数量
bool state; //true表示经办人有提交数据,复核人执行成功后变为false
}
mapping (string => MethodParam) params;
//方法名常量
string public constant ISSUE_METHOD = "issue";
string public constant REDEEM_METHOD = "redeem";
//经办人提交增发数量
function submitIssue(uint _value) public onlyMANAGER {
params[ISSUE_METHOD] = MethodParam(ISSUE_METHOD, _value, true);
emit SubmitIsses(msg.sender,_value);
}
//复核人第二次确认增发数量并执行
function comfirmIsses(uint _value) public onlyREVIEWER {
require(params[ISSUE_METHOD].value == _value);
require(params[ISSUE_METHOD].state == true);
balances[assetOwner]=balances[assetOwner].add(_value);
totalSupply_ = totalSupply_.add(_value);
params[ISSUE_METHOD].state=false;
emit ComfirmIsses(msg.sender,_value);
}
//经办人提交赎回数量
function submitRedeem(uint _value) public onlyMANAGER {
params[REDEEM_METHOD] = MethodParam(REDEEM_METHOD, _value, true);
emit SubmitRedeem(msg.sender,_value);
}
//复核人第二次确认赎回数量并执行
function comfirmRedeem(uint _value) public onlyREVIEWER {
require(params[REDEEM_METHOD].value == _value);
require(params[REDEEM_METHOD].state == true);
balances[assetOwner]=balances[assetOwner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
params[REDEEM_METHOD].state=false;
emit ComfirmIsses(msg.sender,_value);
}
//根据方法名,查看经办人提交的参数
function getMethodValue(string _method) public view returns(uint){
return params[_method].value;
}
//根据方法名,查看经办人是否有提交数据
function getMethodState(string _method) public view returns(bool) {
return params[_method].state;
}
event SubmitRedeem(address submit, uint _value);
event ComfirmRedeem(address comfirm, uint _value);
event SubmitIsses(address submit, uint _value);
event ComfirmIsses(address comfirm, uint _value);
}
contract UpgradedStandardToken {
// those methods are called by the legacy contract
function totalSupplyByLegacy() public view returns (uint256);
function balanceOfByLegacy(address who) public view returns (uint256);
function transferByLegacy(address origSender, address to, uint256 value) public returns (bool);
function allowanceByLegacy(address owner, address spender) public view returns (uint256);
function transferFromByLegacy(address origSender, address from, address to, uint256 value) public returns (bool);
function approveByLegacy(address origSender, address spender, uint256 value) public returns (bool);
function increaseApprovalByLegacy(address origSender, address spender, uint addedValue) public returns (bool);
function decreaseApprovalByLegacy(address origSende, address spender, uint subtractedValue) public returns (bool);
}
contract WitToken is TwoPhaseToken {
string public constant name = "Wealth in Tokens";
string public constant symbol = "WIT";
uint8 public constant decimals = 18;
address public upgradedAddress;
bool public deprecated;
modifier validDestination( address to ) {
require(to != address(0x0));
require(to != address(this));
_;
}
constructor ( uint _totalTokenAmount ) public {
basisPointsRate = 0;
maximumFee = 0;
totalSupply_ = _totalTokenAmount;
balances[msg.sender] = _totalTokenAmount;
deprecated = false;
assetOwner = msg.sender;
emit Transfer(address(0x0), msg.sender, _totalTokenAmount);
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function totalSupply() public view returns (uint256) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).totalSupplyByLegacy();
} else {
return totalSupply_;
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function balanceOf(address _owner) public view returns (uint256 balance) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).balanceOfByLegacy( _owner);
} else {
return super.balanceOf(_owner);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transfer(address _to, uint _value) public validDestination(_to) returns (bool) {
require(!isBlackListed[msg.sender]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value);
} else {
return super.transfer(_to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function allowance(address _owner, address _spender) public view returns (uint256) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).allowanceByLegacy(_owner, _spender);
} else {
return super.allowance(_owner, _spender);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function transferFrom(address _from, address _to, uint _value) public validDestination(_to) returns (bool) {
require(!isBlackListed[_from]);
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value);
} else {
return super.transferFrom(_from, _to, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function approve(address _spender, uint256 _value) public returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value);
} else {
return super.approve(_spender, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function increaseApproval(address _spender, uint _value) public returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).increaseApprovalByLegacy(msg.sender, _spender, _value);
} else {
return super.increaseApproval(_spender, _value);
}
}
// Forward ERC20 methods to upgraded contract if this one is deprecated
function decreaseApproval(address _spender, uint _value) public returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).decreaseApprovalByLegacy(msg.sender, _spender, _value);
} else {
return super.decreaseApproval(_spender, _value);
}
}
// deprecate current contract in favour of a new one
function deprecate(address _upgradedAddress) public onlyCEO whenPaused {
deprecated = true;
upgradedAddress = _upgradedAddress;
emit Deprecate(_upgradedAddress);
}
// Called when contract is deprecated
event Deprecate(address newAddress);
/**
* @dev Set up transaction fees
* @param newBasisPoints A few ten-thousandth (设置手续费率为万分之几)
* @param newMaxFee Maximum fee (设置最大手续费,不需要添加decimals)
*/
function setFeeParams(uint newBasisPoints, uint newMaxFee) public onlyCEO {
basisPointsRate = newBasisPoints;
maximumFee = newMaxFee.mul(uint(10)**decimals);
emit FeeParams(basisPointsRate, maximumFee);
}
function transferAssetOwner(address newAssetOwner) public onlyCEO {
require(newAssetOwner != address(0));
assetOwner = newAssetOwner;
emit TransferAssetOwner(assetOwner, newAssetOwner);
}
event TransferAssetOwner(address assetOwner, address newAssetOwner);
// Called if contract ever adds fees
event FeeParams(uint feeBasisPoints, uint maxFee);
}
| Forward ERC20 methods to upgraded contract if this one is deprecated | function increaseApproval(address _spender, uint _value) public returns (bool) {
if (deprecated) {
return UpgradedStandardToken(upgradedAddress).increaseApprovalByLegacy(msg.sender, _spender, _value);
return super.increaseApproval(_spender, _value);
}
}
| 5,364,940 |
./full_match/1/0x4EbF49cc2d2dd029e5CFDf868316385DfFd94c6A/sources/HOKK_ETH.sol | exclude from receiving dividends | function initDividends(address payable _dividendTracker) public onlyOwner {
require(!isDividendsInitialized, "Dividends have been initialized");
dividendTracker = HOKKDividendTracker(_dividendTracker);
_setAutomatedMarketMakerPair(uniswapV2Pair, true);
dividendTracker.excludeFromDividends(address(dividendTracker));
dividendTracker.excludeFromDividends(address(this));
dividendTracker.excludeFromDividends(owner());
dividendTracker.excludeFromDividends(address(uniswapV2Router));
dividendTracker.excludeFromDividends(address(uniswapV2Pair));
dividendTracker.excludeFromDividends(address(0x000000000000000000000000000000000000dEaD));
isDividendsInitialized = true;
}
| 2,961,125 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity =0.8.11;
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// OpenZeppelin Contracts v4.4.1 (utils/Address.sol)
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [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);
}
}
}
}
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
/**
* @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);
}
}
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol)
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata extension, but not including the Enumerable extension, which is available separately as
* {ERC721Enumerable}.
*/
contract ERC721 is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to owner address
mapping(uint256 => address) private _owners;
// Mapping owner address to token count
mapping(address => uint256) private _balances;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view virtual override returns (uint256) {
require(owner != address(0), "ERC721: balance query for the zero address");
return _balances[owner];
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view virtual override returns (address) {
address owner = _owners[tokenId];
require(owner != address(0), "ERC721: owner query for nonexistent token");
return owner;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token");
string memory baseURI = _baseURI();
return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view virtual override returns (address) {
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public virtual override {
_setApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved");
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer");
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _owners[tokenId] != address(0);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) {
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721.ownerOf(tokenId);
return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner] -= 1;
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner");
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_balances[to] += 1;
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721.ownerOf(tokenId), to, tokenId);
}
/**
* @dev Approve `operator` to operate on all of `owner` tokens
*
* Emits a {ApprovalForAll} event.
*/
function _setApprovalForAll(
address owner,
address operator,
bool approved
) internal virtual {
require(owner != operator, "ERC721: approve to caller");
_operatorApprovals[owner][operator] = approved;
emit ApprovalForAll(owner, operator, approved);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver.onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// OpenZeppelin Contracts v4.4.1 (interfaces/IERC2981.sol)
/**
* @dev Interface for the NFT Royalty Standard.
*
* A standardized way to retrieve royalty payment information for non-fungible tokens (NFTs) to enable universal
* support for royalty payments across all NFT marketplaces and ecosystem participants.
*
* _Available since v4.5._
*/
interface IERC2981 is IERC165 {
/**
* @dev Returns how much royalty is owed and to whom, based on a sale price that may be denominated in any unit of
* exchange. The royalty amount is denominated and should be payed in that same unit of exchange.
*/
function royaltyInfo(uint256 tokenId, uint256 salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// OpenZeppelin Contracts v4.4.0 (token/common/ERC2981.sol)
/**
* @dev Implementation of the NFT Royalty Standard, a standardized way to retrieve royalty payment information.
*
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
*
* Royalty is specified as a fraction of sale price. {_feeDenominator} is overridable but defaults to 10000, meaning the
* fee is specified in basis points by default.
*
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
*
* _Available since v4.5._
*/
abstract contract ERC2981 is IERC2981, ERC165 {
struct RoyaltyInfo {
address receiver;
uint96 royaltyFraction;
}
RoyaltyInfo private _defaultRoyaltyInfo;
mapping(uint256 => RoyaltyInfo) private _tokenRoyaltyInfo;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC165) returns (bool) {
return interfaceId == type(IERC2981).interfaceId || super.supportsInterface(interfaceId);
}
/**
* @inheritdoc IERC2981
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view override returns (address, uint256) {
RoyaltyInfo memory royalty = _tokenRoyaltyInfo[_tokenId];
if (royalty.receiver == address(0)) {
royalty = _defaultRoyaltyInfo;
}
uint256 royaltyAmount = (_salePrice * royalty.royaltyFraction) / _feeDenominator();
return (royalty.receiver, royaltyAmount);
}
/**
* @dev The denominator with which to interpret the fee set in {_setTokenRoyalty} and {_setDefaultRoyalty} as a
* fraction of the sale price. Defaults to 10000 so fees are expressed in basis points, but may be customized by an
* override.
*/
function _feeDenominator() internal pure virtual returns (uint96) {
return 10000;
}
/**
* @dev Sets the royalty information that all ids in this contract will default to.
*
* Requirements:
*
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setDefaultRoyalty(address receiver, uint96 feeNumerator) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: invalid receiver");
_defaultRoyaltyInfo = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Removes default royalty information.
*/
function _deleteDefaultRoyalty() internal virtual {
delete _defaultRoyaltyInfo;
}
/**
* @dev Sets the royalty information for a specific token id, overriding the global default.
*
* Requirements:
*
* - `tokenId` must be already minted.
* - `receiver` cannot be the zero address.
* - `feeNumerator` cannot be greater than the fee denominator.
*/
function _setTokenRoyalty(
uint256 tokenId,
address receiver,
uint96 feeNumerator
) internal virtual {
require(feeNumerator <= _feeDenominator(), "ERC2981: royalty fee will exceed salePrice");
require(receiver != address(0), "ERC2981: Invalid parameters");
_tokenRoyaltyInfo[tokenId] = RoyaltyInfo(receiver, feeNumerator);
}
/**
* @dev Resets royalty information for the token id back to the global default.
*/
function _resetTokenRoyalty(uint256 tokenId) internal virtual {
delete _tokenRoyaltyInfo[tokenId];
}
}
// OpenZeppelin Contracts v4.4.0 (token/ERC721/extensions/ERC721Royalty.sol)
/**
* @dev Extension of ERC721 with the ERC2981 NFT Royalty Standard, a standardized way to retrieve royalty payment
* information.
*
* Royalty information can be specified globally for all token ids via {_setDefaultRoyalty}, and/or individually for
* specific token ids via {_setTokenRoyalty}. The latter takes precedence over the first.
*
* IMPORTANT: ERC-2981 only specifies a way to signal royalty information and does not enforce its payment. See
* https://eips.ethereum.org/EIPS/eip-2981#optional-royalty-payments[Rationale] in the EIP. Marketplaces are expected to
* voluntarily pay royalties together with sales, but note that this standard is not yet widely supported.
*
* _Available since v4.5._
*/
abstract contract ERC721Royalty is ERC2981, ERC721 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC2981) returns (bool) {
return super.supportsInterface(interfaceId);
}
/**
* @dev See {ERC721-_burn}. This override additionally clears the royalty information for the token.
*/
function _burn(uint256 tokenId) internal virtual override {
super._burn(tokenId);
_resetTokenRoyalty(tokenId);
}
}
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
/**
* @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;
}
}
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
contract QUIK is ERC721Royalty, Ownable {
using Counters for Counters.Counter;
using Strings for uint256;
Counters.Counter private _tokenIds;
string public baseUri; //Base uri for metadata
uint256 public mintingFee = 0.08 ether; //Minting Fee
string public TLD; // TLD for domain
// Mapping if certain name string has already been reserved
mapping (string => bool) public registeredDomain;
// Mapping for token id to Domain name
mapping (uint256 => string) public tokenDomain;
//whitelist Address for Pre-minting
mapping (address=>bool) public whitelistedAddress;
bool public isOnlyWhitelist = true;
// quik marketplace
address marketplaceContract;
//event
event DomainMinted(uint256 tokenId,string domain, address minter);
constructor(string memory _name, string memory _symbol, string memory _baseUri, string memory _tld, address _marketplaceContract) ERC721(_name, _symbol) {
baseUri = _baseUri;
TLD = _tld;
marketplaceContract = _marketplaceContract;
}
function validateName(string memory str) internal pure returns (bool){
bytes memory b = bytes(str);
if(b.length < 1) return false;
if(b.length > 49) return false; // Cannot be longer than 49 characters
if(b[0] == 0x20) return false; // Leading space
if (b[b.length - 1] == 0x20) return false; // Trailing space
for(uint i; i<b.length; i++){
bytes1 char = b[i];
if (char == 0x20) return false; // Cannot contain spaces
if(
!(char >= 0x30 && char <= 0x39) && //9-0
!(char >= 0x61 && char <= 0x7A) && //a-z
!(char == 0x2D) //- carriage return
)
return false;
}
return true;
}
///@notice Mints new token with given details
///@param _name domain name to mint
function mintDomain(string memory _name) public payable{
require(!isOnlyWhitelist || whitelistedAddress[msg.sender], "Not open for public minting!");
if(!whitelistedAddress[msg.sender])
require(msg.value >= mintingFee, "Not enough minting fee!");
require(validateName(_name), "Not Valid Name!");
require(!isdomainNameReserved(_name), "Already Registered!");
if(!isApprovedForAll(msg.sender, marketplaceContract))
_setApprovalForAll(msg.sender, marketplaceContract, true);
registeredDomain[_name] = true;
_tokenIds.increment();
uint256 newTokenId = _tokenIds.current();
tokenDomain[newTokenId] = _name;
_mint(msg.sender, newTokenId);
//500 royalty info
_setTokenRoyalty(newTokenId, msg.sender, 500);
emit DomainMinted(newTokenId, _name, msg.sender);
}
///@notice Token URI for metadata for token
///@param _tokenId token id
function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) {
require(_exists(_tokenId), "ERC721Metadata: URI query for nonexistent token");
return bytes(baseUri).length > 0 ? string(abi.encodePacked(baseUri, _tokenId.toString(), ".json")) : "";
}
///@notice Checks if domain name is registered or not
///@param _nameString keccak256 hash for the domain
function isdomainNameReserved(string memory _nameString) public view returns (bool) {
return registeredDomain[_nameString];
}
///@notice Get full domain name for the tokenId
///@param _tokenId token id
function getDomainName(uint256 _tokenId) public view returns (string memory domain){
domain = string(abi.encodePacked(tokenDomain[_tokenId],".",TLD));
}
///@notice Change the public minting
///@param _status status for public minting
function onlyWhitelistAddressMintable(bool _status) external onlyOwner{
isOnlyWhitelist = _status;
}
///@notice Add the wallet for whitelisted address for free minting
///@param _wallet wallet of user
function addWhitelistedAddress(address _wallet) external onlyOwner{
whitelistedAddress[_wallet] = true;
}
///@notice Remove the wallet from whitelisted address for free minting
///@param _wallet wallet of user
function removeWhitelistedAddress(address _wallet) external onlyOwner{
whitelistedAddress[_wallet] = false;
}
///@notice Update Minting fee for token
///@param _mintFee Minitng fee to set
function updateMintFee(uint256 _mintFee) external onlyOwner{
mintingFee = _mintFee;
}
///@notice Update address for marketplace contract
///@param _marketplaceContract marketplace contract address
function updateMarketplace(address _marketplaceContract) external onlyOwner{
marketplaceContract = _marketplaceContract;
}
///@notice Withdraw Ether in the contract by owner
function withdraw() external payable onlyOwner {
(bool os, ) = payable(owner()).call{value: address(this).balance}("");
require(os);
}
} | Change the public minting _status status for public minting | function onlyWhitelistAddressMintable(bool _status) external onlyOwner{
isOnlyWhitelist = _status;
}
| 6,919,611 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
library HodlLib {
// The packed hodl item makes heavy use of bit packing
// to minimize storage costs.
struct PackedHodlItem {
// Contains the fields of a packed `UnpackedHodlItem`. See the struct definition
// below for more information.
uint256 packedData;
//
// Mostly zero
//
// The creator address is only set if different than the `prpsBeneficiary`.
address creator;
// The dubiBeneficiary is only set if different than the `prpsBeneficiary`.
address dubiBeneficiary;
uint96 pendingLockedPrps;
}
// The unpacked hodl item contains the unpacked data of an hodl item from storage.
// It minimizes storage reads, since only a single read from storage is necessary
// in most cases to access all relevant data.
//
// NOTE: The bit-sizes of the fields are rounded up to the nearest Solidity type.
struct UnpackedHodlItem {
// The id of the hodl item is actually a uint20, but stored in a uint24 for
// technical reasons. Allows for 2^20 = 1_048_576 hodls per address
// Actual size: uint20
uint24 id;
// The hodl duration is stored using 9 bits and measured in days.
// Technically, allowing for 2^9 = 512 days, but we cap it to 365 days.
// In the remaining 3 bytes several 1-bit flags are stored like:
// `hasDependentHodlOp` and `hasPendingLockedPrps`, etc.
// Actual size: uint12
uint16 duration;
UnpackedFlags flags;
// The last withdrawal timestamp in unix seconds (block timestamp). Defaults to
// the creation date of the hodl.
uint32 lastWithdrawal;
// Storing the PRPS amount in a uint96 still allows to lock up to ~ 7 billion PRPS
// which is plenty enough.
uint96 lockedPrps;
uint96 burnedLockedPrps;
}
struct UnpackedFlags {
// True, if creator is not the PRPS beneficiary
bool hasDifferentCreator;
// True, if DUBI beneficiary is not the PRPS beneficiary
bool hasDifferentDubiBeneficiary;
bool hasDependentHodlOp;
bool hasPendingLockedPrps;
}
// Struct that contains all unpacked data and the additional almost-always zero fields from
// the packed hodl item - returned from `getHodl()` to be more user-friendly to consume.
struct PrettyHodlItem {
uint24 id;
uint16 duration;
UnpackedFlags flags;
uint32 lastWithdrawal;
uint96 lockedPrps;
uint96 burnedLockedPrps;
address creator;
address dubiBeneficiary;
uint96 pendingLockedPrps;
}
/**
* @dev Pack an unpacked hodl item and return a uint256
*/
function packHodlItem(UnpackedHodlItem memory _unpackedHodlItem)
internal
pure
returns (uint256)
{
//
// Allows for 2^20 = 1_048_576 hodls per address
// uint20 id;
//
// The hodl duration is stored using 9 bits and measured in days.
// Technically, allowing for 2^9 = 512 days, but we only need 365 days anyway.
// uint9 durationAndFlags;
//
// Followed by 4 bits to hold 4 flags:
// - `hasDifferentCreator`
// - `hasDifferentDubiBeneficiarys`
// - `hasDependentHodlOp`
// - `hasPendingLockedPrps`
//
// The last withdrawal timestamp in unix seconds (block timestamp). Defaults to
// the creation date of the hodl and uses 31 bits:
// uint31 lastWithdrawal
//
// The PRPS amounts are stored in a uint96 which can hold up to ~ 7 billion PRPS
// which is plenty enough.
// uint96 lockedPrps;
// uint96 burnedLockedPrps;
//
// Build the packed data according to the spec above.
uint256 packedData;
uint256 offset;
// 1) Set first 20 bits to id
// Since it is stored in a uint24 AND it with a bitmask where the first 20 bits are 1
uint24 id = _unpackedHodlItem.id;
uint24 idMask = (1 << 20) - 1;
packedData |= uint256(id & idMask) << offset;
offset += 20;
// 2) Set next 9 bits to duration.
// Since it is stored in a uint16 AND it with a bitmask where the first 9 bits are 1
uint16 duration = _unpackedHodlItem.duration;
uint16 durationMask = (1 << 9) - 1;
packedData |= uint256(duration & durationMask) << offset;
offset += 9;
// 3) Set next 31 bits to withdrawal time
// Since it is stored in a uint32 AND it with a bitmask where the first 31 bits are 1
uint32 lastWithdrawal = _unpackedHodlItem.lastWithdrawal;
uint32 lastWithdrawalMask = (1 << 31) - 1;
packedData |= uint256(lastWithdrawal & lastWithdrawalMask) << offset;
offset += 31;
// 4) Set the 4 flags in the next 4 bits after lastWithdrawal.
UnpackedFlags memory flags = _unpackedHodlItem.flags;
if (flags.hasDifferentCreator) {
// PRPS beneficiary is not the creator
packedData |= 1 << (offset + 0);
}
if (flags.hasDifferentDubiBeneficiary) {
// PRPS beneficiary is not the DUBI beneficiary
packedData |= 1 << (offset + 1);
}
if (flags.hasDependentHodlOp) {
packedData |= 1 << (offset + 2);
}
if (flags.hasPendingLockedPrps) {
packedData |= 1 << (offset + 3);
}
offset += 4;
// 5) Set next 96 bits to locked PRPS
// We don't need to apply a bitmask here, because it occupies the full 96 bit.
packedData |= uint256(_unpackedHodlItem.lockedPrps) << offset;
offset += 96;
// 6) Set next 96 bits to burned locked PRPS
// We don't need to apply a bitmask here, because it occupies the full 96 bit.
packedData |= uint256(_unpackedHodlItem.burnedLockedPrps) << offset;
offset += 96;
assert(offset == 256);
return packedData;
}
/**
* @dev Unpack a packed hodl item.
*/
function unpackHodlItem(uint256 packedData)
internal
pure
returns (UnpackedHodlItem memory)
{
UnpackedHodlItem memory _unpacked;
uint256 offset;
// 1) Read id from the first 20 bits
uint24 id = uint24(packedData >> offset);
uint24 idMask = (1 << 20) - 1;
_unpacked.id = id & idMask;
offset += 20;
// 2) Read duration from the next 9 bits
uint16 duration = uint16(packedData >> offset);
uint16 durationMask = (1 << 9) - 1;
_unpacked.duration = duration & durationMask;
offset += 9;
// 3) Read lastWithdrawal time from the next 31 bits
uint32 lastWithdrawal = uint32(packedData >> offset);
uint32 lastWithdrawalMask = (1 << 31) - 1;
_unpacked.lastWithdrawal = lastWithdrawal & lastWithdrawalMask;
offset += 31;
// 4) Read the 4 flags from the next 4 bits
UnpackedFlags memory flags = _unpacked.flags;
flags.hasDifferentCreator = (packedData >> (offset + 0)) & 1 == 1;
flags.hasDifferentDubiBeneficiary =
(packedData >> (offset + 1)) & 1 == 1;
flags.hasDependentHodlOp = (packedData >> (offset + 2)) & 1 == 1;
flags.hasPendingLockedPrps = (packedData >> (offset + 3)) & 1 == 1;
offset += 4;
// 5) Read locked PRPS from the next 96 bits
// We don't need to apply a bitmask here, because it occupies the full 96 bit.
_unpacked.lockedPrps = uint96(packedData >> offset);
offset += 96;
// 5) Read burned locked PRPS from the next 96 bits
// We don't need to apply a bitmask here, because it occupies the full 96 bit.
_unpacked.burnedLockedPrps = uint96(packedData >> offset);
offset += 96;
assert(offset == 256);
return _unpacked;
}
//---------------------------------------------------------------
// Pending ops
//---------------------------------------------------------------
struct PendingHodl {
// HodlLib.PackedHodlItem;
address creator;
uint96 amountPrps;
address dubiBeneficiary;
uint96 dubiToMint;
address prpsBeneficiary;
uint24 hodlId;
uint16 duration;
}
struct PendingRelease {
uint24 hodlId;
uint96 releasablePrps;
// Required for look-up of hodl item
address creator;
// prpsBeneficiary is implied
}
struct PendingWithdrawal {
address prpsBeneficiary;
uint96 dubiToMint;
// Required for look-up of hodl item
address creator;
uint24 hodlId;
}
function setLockedPrpsToPending(
HodlLib.PackedHodlItem[] storage hodlsSender,
uint96 amount
) public {
// Sum of the PRPS that got marked pending or removed from pending hodls.
uint96 totalLockedPrpsMarkedPending;
uint256 length = hodlsSender.length;
for (uint256 i = 0; i < length; i++) {
HodlLib.PackedHodlItem storage packed = hodlsSender[i];
HodlLib.UnpackedHodlItem memory unpacked = HodlLib.unpackHodlItem(
packed.packedData
);
// Skip hodls which are occupied by pending releases/withdrawals, but
// allow modifying hodls with already pending locked PRPS.
if (unpacked.flags.hasDependentHodlOp) {
continue;
}
uint96 remainingPendingPrps = amount - totalLockedPrpsMarkedPending;
// Sanity check
assert(remainingPendingPrps <= amount);
// No more PRPS left to mark pending
if (remainingPendingPrps == 0) {
break;
}
// Remaining PRPS on the hodl that can be marked pending
uint96 pendingLockedPrps;
if (unpacked.flags.hasPendingLockedPrps) {
pendingLockedPrps = packed.pendingLockedPrps;
}
uint96 remainingLockedPrps = unpacked.lockedPrps -
unpacked.burnedLockedPrps -
pendingLockedPrps;
// Sanity check
assert(remainingLockedPrps <= unpacked.lockedPrps);
// Skip to next hodl if no PRPS left on hodl
if (remainingLockedPrps == 0) {
continue;
}
// Cap amount if the remaining PRPS on hodl is less than what still needs to be marked pending
if (remainingPendingPrps > remainingLockedPrps) {
remainingPendingPrps = remainingLockedPrps;
}
// Update pending PRPS on hodl
uint96 updatedPendingPrpsOnHodl = pendingLockedPrps +
remainingPendingPrps;
// Total of pending PRPS on hodl may never exceed (locked - burned) PRPS.
assert(
updatedPendingPrpsOnHodl <=
unpacked.lockedPrps - unpacked.burnedLockedPrps
);
totalLockedPrpsMarkedPending += remainingPendingPrps;
// Write updated hodl item to storage
unpacked.flags.hasPendingLockedPrps = true;
packed.pendingLockedPrps = updatedPendingPrpsOnHodl;
packed.packedData = HodlLib.packHodlItem(unpacked);
}
require(totalLockedPrpsMarkedPending == amount, "H-14");
}
function revertLockedPrpsSetToPending(
HodlLib.PackedHodlItem[] storage hodlsSender,
uint96 amount
) public {
require(amount > 0, "H-22");
// Remaining pending PRPS to take from hodls
uint96 remainingPendingLockedPrps = amount;
uint256 length = hodlsSender.length;
// Traverse hodls and remove pending locked PRPS until `amount`
// is filled.
for (uint256 i = 0; i < length; i++) {
HodlLib.PackedHodlItem storage packed = hodlsSender[i];
HodlLib.UnpackedHodlItem memory unpacked = HodlLib.unpackHodlItem(
packed.packedData
);
if (
!unpacked.flags.hasPendingLockedPrps ||
unpacked.flags.hasDependentHodlOp
) {
// Skip hodls without pending locked PRPS or when occupied
// by pending releases and withdrawals
continue;
}
// Hodl has pending locked PRPS
// Ensure we do not remove more than what is needed
uint96 remainingPendingPrpsOnHodl = packed.pendingLockedPrps;
if (remainingPendingPrpsOnHodl > remainingPendingLockedPrps) {
remainingPendingPrpsOnHodl = remainingPendingLockedPrps;
}
// The check above guarantees that this cannot underflow
remainingPendingLockedPrps -= remainingPendingPrpsOnHodl;
packed.pendingLockedPrps -= remainingPendingPrpsOnHodl;
// Update hodl if all pending locked PRPS has been removed
if (remainingPendingPrpsOnHodl == 0) {
unpacked.flags.hasPendingLockedPrps = false;
packed.packedData = HodlLib.packHodlItem(unpacked);
}
// Break loop if the remaining total pending PRPS is zero
if (remainingPendingLockedPrps == 0) {
// Done
break;
}
}
// Sanity check
assert(remainingPendingLockedPrps == 0);
}
}
| Pack an unpacked hodl item and return a uint256/ Allows for 2^20 = 1_048_576 hodls per address uint20 id; The hodl duration is stored using 9 bits and measured in days. Technically, allowing for 2^9 = 512 days, but we only need 365 days anyway. uint9 durationAndFlags; Followed by 4 bits to hold 4 flags: - `hasDifferentCreator` - `hasDifferentDubiBeneficiarys` - `hasDependentHodlOp` - `hasPendingLockedPrps` The last withdrawal timestamp in unix seconds (block timestamp). Defaults to the creation date of the hodl and uses 31 bits: uint31 lastWithdrawal The PRPS amounts are stored in a uint96 which can hold up to ~ 7 billion PRPS which is plenty enough. uint96 lockedPrps; uint96 burnedLockedPrps; Build the packed data according to the spec above. 1) Set first 20 bits to id Since it is stored in a uint24 AND it with a bitmask where the first 20 bits are 1 2) Set next 9 bits to duration. Since it is stored in a uint16 AND it with a bitmask where the first 9 bits are 1 3) Set next 31 bits to withdrawal time Since it is stored in a uint32 AND it with a bitmask where the first 31 bits are 1 4) Set the 4 flags in the next 4 bits after lastWithdrawal. PRPS beneficiary is not the creator PRPS beneficiary is not the DUBI beneficiary | function packHodlItem(UnpackedHodlItem memory _unpackedHodlItem)
internal
pure
returns (uint256)
{
uint256 packedData;
uint256 offset;
uint24 id = _unpackedHodlItem.id;
uint24 idMask = (1 << 20) - 1;
packedData |= uint256(id & idMask) << offset;
offset += 20;
uint16 duration = _unpackedHodlItem.duration;
uint16 durationMask = (1 << 9) - 1;
packedData |= uint256(duration & durationMask) << offset;
offset += 9;
uint32 lastWithdrawal = _unpackedHodlItem.lastWithdrawal;
uint32 lastWithdrawalMask = (1 << 31) - 1;
packedData |= uint256(lastWithdrawal & lastWithdrawalMask) << offset;
offset += 31;
UnpackedFlags memory flags = _unpackedHodlItem.flags;
if (flags.hasDifferentCreator) {
packedData |= 1 << (offset + 0);
}
if (flags.hasDifferentDubiBeneficiary) {
packedData |= 1 << (offset + 1);
}
if (flags.hasDependentHodlOp) {
packedData |= 1 << (offset + 2);
}
if (flags.hasPendingLockedPrps) {
packedData |= 1 << (offset + 3);
}
offset += 4;
offset += 96;
offset += 96;
assert(offset == 256);
return packedData;
}
| 11,796,440 |
/*
B.PROTOCOL TERMS OF USE
=======================
THE TERMS OF USE CONTAINED HEREIN (THESE “TERMS”) GOVERN YOUR USE OF B.PROTOCOL, WHICH IS A DECENTRALIZED PROTOCOL ON THE ETHEREUM BLOCKCHAIN (the “PROTOCOL”) THAT enables a backstop liquidity mechanism FOR DECENTRALIZED LENDING PLATFORMS (“DLPs”).
PLEASE READ THESE TERMS CAREFULLY AT https://github.com/backstop-protocol/Terms-and-Conditions, INCLUDING ALL DISCLAIMERS AND RISK FACTORS, BEFORE USING THE PROTOCOL. BY USING THE PROTOCOL, YOU ARE IRREVOCABLY CONSENTING TO BE BOUND BY THESE TERMS.
IF YOU DO NOT AGREE TO ALL OF THESE TERMS, DO NOT USE THE PROTOCOL. YOUR RIGHT TO USE THE PROTOCOL IS SUBJECT AND DEPENDENT BY YOUR AGREEMENT TO ALL TERMS AND CONDITIONS SET FORTH HEREIN, WHICH AGREEMENT SHALL BE EVIDENCED BY YOUR USE OF THE PROTOCOL.
Minors Prohibited: The Protocol is not directed to individuals under the age of eighteen (18) or the age of majority in your jurisdiction if the age of majority is greater. If you are under the age of eighteen or the age of majority (if greater), you are not authorized to access or use the Protocol. By using the Protocol, you represent and warrant that you are above such age.
License; No Warranties; Limitation of Liability;
(a) The software underlying the Protocol is licensed for use in accordance with the 3-clause BSD License, which can be accessed here: https://opensource.org/licenses/BSD-3-Clause.
(b) THE PROTOCOL IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS", “WITH ALL FAULTS” and “AS AVAILABLE” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
(c) 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.12;
pragma experimental ABIEncoderV2;
contract Math {
// --- Math ---
function add(uint x, int y) internal pure returns (uint z) {
z = x + uint(y);
require(y >= 0 || z <= x);
require(y <= 0 || z >= x);
}
function sub(uint x, int y) internal pure returns (uint z) {
z = x - uint(y);
require(y <= 0 || z <= x);
require(y >= 0 || z >= x);
}
function mul(uint x, int y) internal pure returns (int z) {
z = int(x) * y;
require(int(x) >= 0);
require(y == 0 || z / y == int(x));
}
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
uint constant RAY = 10 ** 27;
function rdiv(uint x, uint y) internal pure returns (uint z) {
z = mul(x, RAY) / y;
}
function rmul(uint x, uint y) internal pure returns (uint z) {
z = mul(x, y) / RAY;
}
function rpow(uint x, uint n, uint b) internal pure returns (uint z) {
assembly {
switch x case 0 {switch n case 0 {z := b} default {z := 0}}
default {
switch mod(n, 2) case 0 { z := b } default { z := x }
let half := div(b, 2) // for rounding.
for { n := div(n, 2) } n { n := div(n,2) } {
let xx := mul(x, x)
if iszero(eq(div(xx, x), x)) { revert(0,0) }
let xxRound := add(xx, half)
if lt(xxRound, xx) { revert(0,0) }
x := div(xxRound, b)
if mod(n,2) {
let zx := mul(z, x)
if and(iszero(iszero(x)), iszero(eq(div(zx, x), z))) { revert(0,0) }
let zxRound := add(zx, half)
if lt(zxRound, zx) { revert(0,0) }
z := div(zxRound, b)
}
}
}
}
}
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0);
}
}
contract LibNote {
event LogNote(
bytes4 indexed sig,
address indexed usr,
bytes32 indexed arg1,
bytes32 indexed arg2,
bytes data
) anonymous;
modifier note {
_;
assembly {
// log an 'anonymous' event with a constant 6 words of calldata
// and four indexed topics: selector, caller, arg1 and arg2
let mark := msize() // end of memory ensures zero
mstore(0x40, add(mark, 288)) // update free memory pointer
mstore(mark, 0x20) // bytes type data offset
mstore(add(mark, 0x20), 224) // bytes size (padded)
calldatacopy(add(mark, 0x40), 0, 224) // bytes payload
log4(mark, 288, // calldata
shl(224, shr(224, calldataload(0))), // msg.sig
caller(), // msg.sender
calldataload(4), // arg1
calldataload(36) // arg2
)
}
}
}
contract BCdpScoreLike {
function updateScore(uint cdp, bytes32 ilk, int dink, int dart, uint time) external;
}
contract BCdpScoreConnector {
BCdpScoreLike public score;
mapping(uint => uint) public left;
constructor(BCdpScoreLike score_) public {
score = score_;
}
function setScore(BCdpScoreLike bcdpScore) internal {
score = bcdpScore;
}
function updateScore(uint cdp, bytes32 ilk, int dink, int dart, uint time) internal {
if(left[cdp] == 0) score.updateScore(cdp, ilk, dink, dart, time);
}
function quitScore(uint cdp) internal {
if(left[cdp] == 0) left[cdp] = now;
}
}
contract UrnHandler {
constructor(address vat) public {
VatLike(vat).hope(msg.sender);
}
}
contract DssCdpManager is LibNote {
address public vat;
uint public cdpi; // Auto incremental
mapping (uint => address) public urns; // CDPId => UrnHandler
mapping (uint => List) public list; // CDPId => Prev & Next CDPIds (double linked list)
mapping (uint => address) public owns; // CDPId => Owner
mapping (uint => bytes32) public ilks; // CDPId => Ilk
mapping (address => uint) public first; // Owner => First CDPId
mapping (address => uint) public last; // Owner => Last CDPId
mapping (address => uint) public count; // Owner => Amount of CDPs
mapping (
address => mapping (
uint => mapping (
address => uint
)
)
) public cdpCan; // Owner => CDPId => Allowed Addr => True/False
mapping (
address => mapping (
address => uint
)
) public urnCan; // Urn => Allowed Addr => True/False
struct List {
uint prev;
uint next;
}
event NewCdp(address indexed usr, address indexed own, uint indexed cdp);
modifier cdpAllowed(
uint cdp
) {
require(msg.sender == owns[cdp] || cdpCan[owns[cdp]][cdp][msg.sender] == 1, "cdp-not-allowed");
_;
}
modifier urnAllowed(
address urn
) {
require(msg.sender == urn || urnCan[urn][msg.sender] == 1, "urn-not-allowed");
_;
}
constructor(address vat_) public {
vat = vat_;
}
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0);
}
// Allow/disallow a usr address to manage the cdp.
function cdpAllow(
uint cdp,
address usr,
uint ok
) public cdpAllowed(cdp) {
cdpCan[owns[cdp]][cdp][usr] = ok;
}
// Allow/disallow a usr address to quit to the the sender urn.
function urnAllow(
address usr,
uint ok
) public {
urnCan[msg.sender][usr] = ok;
}
// Open a new cdp for a given usr address.
function open(
bytes32 ilk,
address usr
) public note returns (uint) {
require(usr != address(0), "usr-address-0");
cdpi = add(cdpi, 1);
urns[cdpi] = address(new UrnHandler(vat));
owns[cdpi] = usr;
ilks[cdpi] = ilk;
// Add new CDP to double linked list and pointers
if (first[usr] == 0) {
first[usr] = cdpi;
}
if (last[usr] != 0) {
list[cdpi].prev = last[usr];
list[last[usr]].next = cdpi;
}
last[usr] = cdpi;
count[usr] = add(count[usr], 1);
emit NewCdp(msg.sender, usr, cdpi);
return cdpi;
}
// Give the cdp ownership to a dst address.
function give(
uint cdp,
address dst
) public note cdpAllowed(cdp) {
require(dst != address(0), "dst-address-0");
require(dst != owns[cdp], "dst-already-owner");
// Remove transferred CDP from double linked list of origin user and pointers
if (list[cdp].prev != 0) {
list[list[cdp].prev].next = list[cdp].next; // Set the next pointer of the prev cdp (if exists) to the next of the transferred one
}
if (list[cdp].next != 0) { // If wasn't the last one
list[list[cdp].next].prev = list[cdp].prev; // Set the prev pointer of the next cdp to the prev of the transferred one
} else { // If was the last one
last[owns[cdp]] = list[cdp].prev; // Update last pointer of the owner
}
if (first[owns[cdp]] == cdp) { // If was the first one
first[owns[cdp]] = list[cdp].next; // Update first pointer of the owner
}
count[owns[cdp]] = sub(count[owns[cdp]], 1);
// Transfer ownership
owns[cdp] = dst;
// Add transferred CDP to double linked list of destiny user and pointers
list[cdp].prev = last[dst];
list[cdp].next = 0;
if (last[dst] != 0) {
list[last[dst]].next = cdp;
}
if (first[dst] == 0) {
first[dst] = cdp;
}
last[dst] = cdp;
count[dst] = add(count[dst], 1);
}
// Frob the cdp keeping the generated DAI or collateral freed in the cdp urn address.
function frob(
uint cdp,
int dink,
int dart
) public note cdpAllowed(cdp) {
address urn = urns[cdp];
VatLike(vat).frob(
ilks[cdp],
urn,
urn,
urn,
dink,
dart
);
}
// Transfer wad amount of cdp collateral from the cdp address to a dst address.
function flux(
uint cdp,
address dst,
uint wad
) public note cdpAllowed(cdp) {
VatLike(vat).flux(ilks[cdp], urns[cdp], dst, wad);
}
// Transfer wad amount of any type of collateral (ilk) from the cdp address to a dst address.
// This function has the purpose to take away collateral from the system that doesn't correspond to the cdp but was sent there wrongly.
function flux(
bytes32 ilk,
uint cdp,
address dst,
uint wad
) public note cdpAllowed(cdp) {
VatLike(vat).flux(ilk, urns[cdp], dst, wad);
}
// Transfer wad amount of DAI from the cdp address to a dst address.
function move(
uint cdp,
address dst,
uint rad
) public note cdpAllowed(cdp) {
VatLike(vat).move(urns[cdp], dst, rad);
}
// Quit the system, migrating the cdp (ink, art) to a different dst urn
function quit(
uint cdp,
address dst
) public note cdpAllowed(cdp) urnAllowed(dst) {
(uint ink, uint art) = VatLike(vat).urns(ilks[cdp], urns[cdp]);
VatLike(vat).fork(
ilks[cdp],
urns[cdp],
dst,
toInt(ink),
toInt(art)
);
}
// Import a position from src urn to the urn owned by cdp
function enter(
address src,
uint cdp
) public note urnAllowed(src) cdpAllowed(cdp) {
(uint ink, uint art) = VatLike(vat).urns(ilks[cdp], src);
VatLike(vat).fork(
ilks[cdp],
src,
urns[cdp],
toInt(ink),
toInt(art)
);
}
// Move a position from cdpSrc urn to the cdpDst urn
function shift(
uint cdpSrc,
uint cdpDst
) public note cdpAllowed(cdpSrc) cdpAllowed(cdpDst) {
require(ilks[cdpSrc] == ilks[cdpDst], "non-matching-cdps");
(uint ink, uint art) = VatLike(vat).urns(ilks[cdpSrc], urns[cdpSrc]);
VatLike(vat).fork(
ilks[cdpSrc],
urns[cdpSrc],
urns[cdpDst],
toInt(ink),
toInt(art)
);
}
}
interface DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) external view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
constructor() public {
owner = msg.sender;
emit LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
emit LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
emit LogSetAuthority(address(authority));
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig), "ds-auth-unauthorized");
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, address(this), sig);
}
}
}
contract VatLike {
function urns(bytes32, address) public view returns (uint, uint);
function hope(address) external;
function flux(bytes32, address, address, uint) public;
function move(address, address, uint) public;
function frob(bytes32, address, address, address, int, int) public;
function fork(bytes32, address, address, int, int) public;
function ilks(bytes32 ilk) public view returns(uint Art, uint rate, uint spot, uint line, uint dust);
function dai(address usr) external view returns(uint);
}
contract CatLike {
function ilks(bytes32) public returns(address flip, uint256 chop, uint256 lump);
}
contract EndLike {
function cat() public view returns(CatLike);
}
contract PriceFeedLike {
function read(bytes32 ilk) external view returns(bytes32);
}
contract LiquidationMachine is DssCdpManager, BCdpScoreConnector, Math {
VatLike public vat;
EndLike public end;
address public pool;
PriceFeedLike public real;
mapping(uint => uint) public tic; // time of bite
mapping(uint => uint) public cushion; // how much was topped in art units
uint constant public GRACE = 1 hours;
uint constant public WAD = 1e18;
mapping (uint => bool) public out;
modifier onlyPool {
require(msg.sender == pool, "not-pool");
_;
}
constructor(VatLike vat_, EndLike end_, address pool_, PriceFeedLike real_) public {
vat = vat_;
end = end_;
pool = pool_;
real = real_;
}
function setPool(address newPool) internal {
pool = newPool;
}
function quitBLiquidation(uint cdp) internal {
untop(cdp);
out[cdp] = true;
}
function topup(uint cdp, uint dtopup) external onlyPool {
if(out[cdp]) return;
address urn = urns[cdp];
bytes32 ilk = ilks[cdp];
(, uint rate,,,) = vat.ilks(ilk);
uint dtab = mul(rate, dtopup);
vat.move(pool, address(this), dtab);
vat.frob(ilk, urn, urn, address(this), 0, -toInt(dtopup));
cushion[cdp] = add(cushion[cdp], dtopup);
}
function bitten(uint cdp) public view returns(bool) {
return tic[cdp] + GRACE > now;
}
function untop(uint cdp) internal {
require(! bitten(cdp), "untop: cdp was already bitten");
uint top = cushion[cdp];
if(top == 0) return; // nothing to do
bytes32 ilk = ilks[cdp];
address urn = urns[cdp];
(, uint rate,,,) = vat.ilks(ilk);
uint dtab = mul(rate, top);
cushion[cdp] = 0;
// move topping to pool
vat.frob(ilk, urn, urn, urn, 0, toInt(top));
vat.move(urn, pool, dtab);
}
function untopByPool(uint cdp) external onlyPool {
untop(cdp);
}
function doBite(uint dart, bytes32 ilk, address urn, uint dink) internal {
(, uint rate,,,) = vat.ilks(ilk);
uint dtab = mul(rate, dart);
vat.move(pool, address(this), dtab);
vat.frob(ilk, urn, urn, address(this), 0, -toInt(dart));
vat.frob(ilk, urn, msg.sender, urn, -toInt(dink), 0);
}
function calcDink(uint dart, uint rate, bytes32 ilk) internal returns(uint dink) {
(, uint chop,) = end.cat().ilks(ilk);
uint tab = mul(mul(dart, rate), chop) / WAD;
bytes32 realtimePrice = real.read(ilk);
dink = rmul(tab, WAD) / uint(realtimePrice);
}
function bite(uint cdp, uint dart) external onlyPool returns(uint dink){
address urn = urns[cdp];
bytes32 ilk = ilks[cdp];
(uint ink, uint art) = vat.urns(ilk, urn);
art = add(art, cushion[cdp]);
(, uint rate, uint spotValue,,) = vat.ilks(ilk);
require(dart <= art, "debt is too low");
// verify cdp is unsafe now
if(! bitten(cdp)) {
require(mul(art, rate) > mul(ink, spotValue), "bite: cdp is safe");
require(cushion[cdp] > 0, "bite: not-topped");
tic[cdp] = now;
}
dink = calcDink(dart, rate, ilk);
updateScore(cdp, ilk, -toInt(dink), -toInt(dart), now);
uint usedCushion = mul(cushion[cdp], dart) / art;
cushion[cdp] = sub(cushion[cdp], usedCushion);
uint bart = sub(dart, usedCushion);
doBite(bart, ilk, urn, dink);
}
}
contract BCdpManager is BCdpScoreConnector, LiquidationMachine, DSAuth {
constructor(address vat_, address end_, address pool_, address real_, address score_) public
DssCdpManager(vat_)
LiquidationMachine(VatLike(vat_), EndLike(end_), pool_, PriceFeedLike(real_))
BCdpScoreConnector(BCdpScoreLike(score_))
{
}
// Frob the cdp keeping the generated DAI or collateral freed in the cdp urn address.
function frob(
uint cdp,
int dink,
int dart
) public cdpAllowed(cdp) {
bytes32 ilk = ilks[cdp];
untop(cdp);
updateScore(cdp, ilk, dink, dart, now);
super.frob(cdp, dink, dart);
}
// Quit the system, migrating the cdp (ink, art) to a different dst urn
function quit(
uint cdp,
address dst
) public cdpAllowed(cdp) urnAllowed(dst) {
address urn = urns[cdp];
bytes32 ilk = ilks[cdp];
untop(cdp);
(uint ink, uint art) = vat.urns(ilk, urn);
updateScore(cdp, ilk, -toInt(ink), -toInt(art), now);
super.quit(cdp, dst);
}
// Import a position from src urn to the urn owned by cdp
function enter(
address src,
uint cdp
) public urnAllowed(src) cdpAllowed(cdp) {
bytes32 ilk = ilks[cdp];
untop(cdp);
(uint ink, uint art) = vat.urns(ilk, src);
updateScore(cdp, ilk, toInt(ink), toInt(art), now);
super.enter(src, cdp);
}
// Move a position from cdpSrc urn to the cdpDst urn
function shift(
uint cdpSrc,
uint cdpDst
) public cdpAllowed(cdpSrc) cdpAllowed(cdpDst) {
bytes32 ilkSrc = ilks[cdpSrc];
untop(cdpSrc);
untop(cdpDst);
address src = urns[cdpSrc];
(uint inkSrc, uint artSrc) = vat.urns(ilkSrc, src);
updateScore(cdpSrc, ilkSrc, -toInt(inkSrc), -toInt(artSrc), now);
updateScore(cdpDst, ilkSrc, toInt(inkSrc), toInt(artSrc), now);
super.shift(cdpSrc, cdpDst);
}
///////////////// B specific control functions /////////////////////////////
function quitB(uint cdp) external cdpAllowed(cdp) note {
quitScore(cdp);
quitBLiquidation(cdp);
}
function setScoreContract(BCdpScoreLike _score) external auth {
super.setScore(_score);
}
function setPoolContract(address _pool) external auth {
super.setPool(_pool);
}
}
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
contract 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;
}
}
contract ScoringMachine is Ownable {
struct AssetScore {
// total score so far
uint score;
// current balance
uint balance;
// time when last update was
uint last;
}
// user is bytes32 (will be the sha3 of address or cdp number)
mapping(bytes32 => mapping(bytes32 => AssetScore[])) public checkpoints;
mapping(bytes32 => mapping(bytes32 => AssetScore)) public userScore;
bytes32 constant public GLOBAL_USER = bytes32(0x0);
uint public start; // start time of the campaign;
function spin() external onlyOwner { // start a new round
start = now;
}
function assetScore(AssetScore storage score, uint time, uint spinStart) internal view returns(uint) {
uint last = score.last;
uint currentScore = score.score;
if(last < spinStart) {
last = spinStart;
currentScore = 0;
}
return add(currentScore, mul(score.balance, sub(time, last)));
}
function addCheckpoint(bytes32 user, bytes32 asset) internal {
checkpoints[user][asset].push(userScore[user][asset]);
}
function updateAssetScore(bytes32 user, bytes32 asset, int dbalance, uint time) internal {
AssetScore storage score = userScore[user][asset];
if(score.last < start) addCheckpoint(user, asset);
score.score = assetScore(score, time, start);
score.balance = add(score.balance, dbalance);
score.last = time;
}
function updateScore(bytes32 user, bytes32 asset, int dbalance, uint time) internal {
updateAssetScore(user, asset, dbalance, time);
updateAssetScore(GLOBAL_USER, asset, dbalance, time);
}
function getScore(bytes32 user, bytes32 asset, uint time, uint spinStart, uint checkPointHint) public view returns(uint score) {
if(time >= userScore[user][asset].last) return assetScore(userScore[user][asset], time, spinStart);
// else - check the checkpoints
uint checkpointsLen = checkpoints[user][asset].length;
if(checkpointsLen == 0) return 0;
// hint is invalid
if(checkpoints[user][asset][checkPointHint].last < time) checkPointHint = checkpointsLen - 1;
for(uint i = checkPointHint ; ; i--){
if(checkpoints[user][asset][i].last <= time) return assetScore(checkpoints[user][asset][i], time, spinStart);
}
// this supposed to be unreachable
return 0;
}
function getCurrentBalance(bytes32 user, bytes32 asset) public view returns(uint balance) {
balance = userScore[user][asset].balance;
}
// Math functions without errors
// ==============================
function add(uint x, uint y) internal pure returns (uint z) {
z = x + y;
if(!(z >= x)) return 0;
return z;
}
function add(uint x, int y) internal pure returns (uint z) {
z = x + uint(y);
if(!(y >= 0 || z <= x)) return 0;
if(!(y <= 0 || z >= x)) return 0;
return z;
}
function sub(uint x, uint y) internal pure returns (uint z) {
if(!(y <= x)) return 0;
z = x - y;
return z;
}
function mul(uint x, uint y) internal pure returns (uint z) {
if (x == 0) return 0;
z = x * y;
if(!(z / x == y)) return 0;
return z;
}
}
contract BCdpScore is ScoringMachine {
BCdpManager public manager;
modifier onlyManager {
require(msg.sender == address(manager), "not-manager");
_;
}
function setManager(address newManager) external onlyOwner {
manager = BCdpManager(newManager);
}
function user(uint cdp) public pure returns(bytes32) {
return keccak256(abi.encodePacked("BCdpScore", cdp));
}
function artAsset(bytes32 ilk) public pure returns(bytes32) {
return keccak256(abi.encodePacked("BCdpScore", "art", ilk));
}
function updateScore(uint cdp, bytes32 ilk, int dink, int dart, uint time) external onlyManager {
dink; // shh compiler warning
updateScore(user(cdp), artAsset(ilk), dart, time);
}
function slashScore(uint maliciousCdp) external {
address urn = manager.urns(maliciousCdp);
bytes32 ilk = manager.ilks(maliciousCdp);
(, uint realArt) = manager.vat().urns(ilk, urn);
bytes32 maliciousUser = user(maliciousCdp);
bytes32 asset = artAsset(ilk);
uint left = BCdpScoreConnector(address(manager)).left(maliciousCdp);
realArt = left > 0 ? 0 : realArt;
uint startTime = left > 0 ? left : now;
uint calculatedArt = getCurrentBalance(maliciousUser, asset);
require(realArt < calculatedArt, "slashScore-cdp-is-ok");
int dart = int(realArt) - int(calculatedArt);
uint time = sub(startTime, 30 days);
if(time < start) time = start;
updateScore(maliciousUser, asset, dart, time);
}
function getArtScore(uint cdp, bytes32 ilk, uint time, uint spinStart) public view returns(uint) {
return getScore(user(cdp), artAsset(ilk), time, spinStart, 0);
}
function getArtGlobalScore(bytes32 ilk, uint time, uint spinStart) public view returns(uint) {
return getScore(GLOBAL_USER, artAsset(ilk), time, spinStart, 0);
}
}
contract JarConnector is Math {
BCdpScore public score;
BCdpManager public man;
bytes32[] public ilks;
// ilk => supported
mapping(bytes32 => bool) public milks;
// end of every round
uint[2] public end;
// start time of every round
uint[2] public start;
uint public round;
constructor(
bytes32[] memory _ilks,
uint[2] memory _duration
) public {
ilks = _ilks;
for(uint i = 0; i < _ilks.length; i++) {
milks[_ilks[i]] = true;
}
end[0] = now + _duration[0];
end[1] = now + _duration[0] + _duration[1];
round = 0;
}
function setManager(address _manager) public {
require(man == BCdpManager(0), "manager-already-set");
man = BCdpManager(_manager);
score = BCdpScore(address(man.score()));
}
// callable by anyone
function spin() public {
if(round == 0) {
round++;
score.spin();
start[0] = score.start();
}
if(round == 1 && now > end[0]) {
round++;
score.spin();
start[1] = score.start();
}
if(round == 2 && now > end[1]) {
round++;
// score is not counted anymore, and this must be followed by contract upgrade
score.spin();
}
}
function getUserScore(bytes32 user) external view returns (uint) {
if(round == 0) return 0;
uint cdp = uint(user);
bytes32 ilk = man.ilks(cdp);
// Should return 0 score for unsupported ilk
if( ! milks[ilk]) return 0;
if(round == 1) return 2 * score.getArtScore(cdp, ilk, now, start[0]);
uint firstRoundScore = 2 * score.getArtScore(cdp, ilk, start[1], start[0]);
uint time = now;
if(round > 2) time = end[1];
return add(score.getArtScore(cdp, ilk, time, start[1]), firstRoundScore);
}
function getGlobalScore() external view returns (uint) {
if(round == 0) return 0;
if(round == 1) return 2 * getArtGlobalScore(now, start[0]);
uint firstRoundScore = 2 * getArtGlobalScore(start[1], start[0]);
uint time = now;
if(round > 2) time = end[1];
return add(getArtGlobalScore(time, start[1]), firstRoundScore);
}
function getGlobalScore(bytes32 ilk) external view returns (uint) {
if(round == 0) return 0;
if(round == 1) return 2 * score.getArtGlobalScore(ilk, now, start[0]);
uint firstRoundScore = 2 * score.getArtGlobalScore(ilk, start[1], start[0]);
uint time = now;
if(round > 2) time = end[1];
return add(score.getArtGlobalScore(ilk, time, start[1]), firstRoundScore);
}
function getArtGlobalScore(uint time, uint spinStart) internal view returns (uint totalScore) {
for(uint i = 0; i < ilks.length; i++) {
totalScore = add(totalScore, score.getArtGlobalScore(ilks[i], time, spinStart));
}
}
function toUser(bytes32 user) external view returns (address) {
return man.owns(uint(user));
}
}
contract JugLike {
function ilks(bytes32 ilk) public view returns(uint duty, uint rho);
function base() public view returns(uint);
}
contract SpotLike {
function par() external view returns (uint256);
function ilks(bytes32 ilk) external view returns (address pip, uint mat);
}
contract OSMLike {
function peep() external view returns(bytes32, bool);
function hop() external view returns(uint16);
function zzz() external view returns(uint64);
}
contract DaiToUsdPriceFeed {
function getMarketPrice(uint marketId) public view returns (uint);
}
contract Pool is Math, DSAuth, LibNote {
uint public constant DAI_MARKET_ID = 3;
address[] public members;
mapping(bytes32 => bool) public ilks;
uint public minArt; // min debt to share among members
uint public shrn; // share profit % numerator
uint public shrd; // share profit % denumerator
mapping(address => uint) public rad; // mapping from member to its dai balance in rad
VatLike public vat;
BCdpManager public man;
SpotLike public spot;
JugLike public jug;
address public jar;
DaiToUsdPriceFeed public dai2usd;
mapping(uint => CdpData) internal cdpData;
mapping(bytes32 => OSMLike) public osm; // mapping from ilk to osm
struct CdpData {
uint art; // topup in art units
uint cushion; // cushion in rad units
address[] members; // liquidators that are in
uint[] bite; // how much was already bitten
}
modifier onlyMember {
bool member = false;
for(uint i = 0 ; i < members.length ; i++) {
if(members[i] == msg.sender) {
member = true;
break;
}
}
require(member, "not-member");
_;
}
constructor(address vat_, address jar_, address spot_, address jug_, address dai2usd_) public {
spot = SpotLike(spot_);
jug = JugLike(jug_);
vat = VatLike(vat_);
jar = jar_;
dai2usd = DaiToUsdPriceFeed(dai2usd_);
}
function getCdpData(uint cdp) external view returns(uint art, uint cushion, address[] memory members_, uint[] memory bite) {
art = cdpData[cdp].art;
cushion = cdpData[cdp].cushion;
members_ = cdpData[cdp].members;
bite = cdpData[cdp].bite;
}
function setCdpManager(BCdpManager man_) external auth note {
man = man_;
vat.hope(address(man));
}
function setOsm(bytes32 ilk_, address osm_) external auth note {
osm[ilk_] = OSMLike(osm_);
}
function setMembers(address[] calldata members_) external auth note {
members = members_;
}
function setIlk(bytes32 ilk, bool set) external auth note {
ilks[ilk] = set;
}
function setMinArt(uint minArt_) external auth note {
minArt = minArt_;
}
function setDaiToUsdPriceFeed(address dai2usd_) external auth note {
dai2usd = DaiToUsdPriceFeed(dai2usd_);
}
function setProfitParams(uint num, uint den) external auth note {
require(num < den, "invalid-profit-params");
shrn = num;
shrd = den;
}
function emergencyExecute(address target, bytes calldata data) external auth note {
(bool succ,) = target.call(data);
require(succ, "emergencyExecute: failed");
}
function deposit(uint radVal) external onlyMember note {
vat.move(msg.sender, address(this), radVal);
rad[msg.sender] = add(rad[msg.sender], radVal);
}
function withdraw(uint radVal) external note {
require(rad[msg.sender] >= radVal, "withdraw: insufficient-balance");
rad[msg.sender] = sub(rad[msg.sender], radVal);
vat.move(address(this), msg.sender, radVal);
}
function getIndex(address[] storage array, address elm) internal view returns(uint) {
for(uint i = 0 ; i < array.length ; i++) {
if(array[i] == elm) return i;
}
return uint(-1);
}
function removeElement(address[] memory array, uint index) internal pure returns(address[] memory newArray) {
if(index >= array.length) {
newArray = array;
}
else {
newArray = new address[](array.length - 1);
for(uint i = 0 ; i < array.length ; i++) {
if(i == index) continue;
if(i < index) newArray[i] = array[i];
else newArray[i-1] = array[i];
}
}
}
function chooseMember(uint cdp, uint radVal, address[] memory candidates) public view returns(address[] memory winners) {
if(candidates.length == 0) return candidates;
// A bit of randomness to choose winners. We don't need pure randomness, its ok even if a
// liquidator can predict his winning in the future.
uint chosen = uint(keccak256(abi.encodePacked(cdp, now / 1 hours))) % candidates.length;
address winner = candidates[chosen];
if(rad[winner] < radVal) return chooseMember(cdp, radVal, removeElement(candidates, chosen));
winners = new address[](1);
winners[0] = candidates[chosen];
return winners;
}
function chooseMembers(uint radVal, address[] memory candidates) public view returns(address[] memory winners) {
if(candidates.length == 0) return candidates;
uint need = add(1, radVal / candidates.length);
for(uint i = 0 ; i < candidates.length ; i++) {
if(rad[candidates[i]] < need) {
return chooseMembers(radVal, removeElement(candidates, i));
}
}
winners = candidates;
}
function calcCushion(bytes32 ilk, uint ink, uint art, uint nextSpot) public view returns(uint dart, uint dtab) {
(, uint prev, uint currSpot,,) = vat.ilks(ilk);
if(currSpot <= nextSpot) return (0, 0);
uint hop = uint(osm[ilk].hop());
uint next = add(uint(osm[ilk].zzz()), hop);
(uint duty, uint rho) = jug.ilks(ilk);
require(next >= rho, "calcCushion: next-in-the-past");
// note that makerdao governance could change jug.base() before the actual
// liquidation happens. but there is 48 hours time lock on makerdao votes
// so liquidators should withdraw their funds if they think such event will
// happen
uint nextRate = rmul(rpow(add(jug.base(), duty), next - rho, RAY), prev);
uint nextnextRate = rmul(rpow(add(jug.base(), duty), hop, RAY), nextRate);
if(mul(nextRate, art) > mul(ink, currSpot)) return (0, 0); // prevent L attack
if(mul(nextRate, art) <= mul(ink, nextSpot)) return (0, 0);
uint maxArt = mul(ink, nextSpot) / nextnextRate;
dart = sub(art, maxArt);
dart = add(1 ether, dart); // compensate for rounding errors
dtab = mul(dart, prev); // provide a cushion according to current rate
}
function hypoTopAmount(uint cdp) internal view returns(uint dart, uint dtab, uint art, bool should) {
address urn = man.urns(cdp);
bytes32 ilk = man.ilks(cdp);
uint ink;
(ink, art) = vat.urns(ilk, urn);
if(! ilks[ilk]) return (0, 0, art, false);
(bytes32 peep, bool valid) = osm[ilk].peep();
// price feed invalid
if(! valid) return (0, 0, art, false);
// too early to topup
should = (now >= add(uint(osm[ilk].zzz()), uint(osm[ilk].hop())/2));
(, uint mat) = spot.ilks(ilk);
uint par = spot.par();
uint nextVatSpot = rdiv(rdiv(mul(uint(peep), uint(10 ** 9)), par), mat);
(dart, dtab) = calcCushion(ilk, ink, art, nextVatSpot);
}
function topAmount(uint cdp) public view returns(uint dart, uint dtab, uint art) {
bool should;
(dart, dtab, art, should) = hypoTopAmount(cdp);
if(! should) return (0, 0, art);
}
function resetCdp(uint cdp) internal {
address[] memory winners = cdpData[cdp].members;
if(winners.length == 0) return;
uint art = cdpData[cdp].art;
uint cushion = cdpData[cdp].cushion;
uint perUserArt = cdpData[cdp].art / winners.length;
for(uint i = 0 ; i < winners.length ; i++) {
if(perUserArt <= cdpData[cdp].bite[i]) continue; // nothing to refund
uint refundArt = sub(perUserArt, cdpData[cdp].bite[i]);
rad[winners[i]] = add(rad[winners[i]], mul(refundArt, cushion)/art);
}
cdpData[cdp].art = 0;
cdpData[cdp].cushion = 0;
delete cdpData[cdp].members;
delete cdpData[cdp].bite;
}
function setCdp(uint cdp, address[] memory winners, uint art, uint dradVal) internal {
uint drad = add(1, dradVal / winners.length); // round up
for(uint i = 0 ; i < winners.length ; i++) {
rad[winners[i]] = sub(rad[winners[i]], drad);
}
cdpData[cdp].art = art;
cdpData[cdp].cushion = dradVal;
cdpData[cdp].members = winners;
cdpData[cdp].bite = new uint[](winners.length);
}
function topupInfo(uint cdp) public view returns(uint dart, uint dtab, uint art, bool should, address[] memory winners) {
(dart, dtab, art, should) = hypoTopAmount(cdp);
if(art < minArt) {
winners = chooseMember(cdp, uint(dtab), members);
}
else winners = chooseMembers(uint(dtab), members);
}
function topup(uint cdp) external onlyMember note {
require(man.cushion(cdp) == 0, "topup: already-topped");
require(! man.bitten(cdp), "topup: already-bitten");
(uint dart, uint dtab, uint art, bool should, address[] memory winners) = topupInfo(cdp);
require(should, "topup: no-need");
require(dart > 0, "topup: 0-dart");
resetCdp(cdp);
require(winners.length > 0, "topup: members-are-broke");
// for small amounts, only winner can topup
if(art < minArt) require(winners[0] == msg.sender, "topup: only-winner-can-topup");
setCdp(cdp, winners, uint(art), uint(dtab));
man.topup(cdp, uint(dart));
}
function untop(uint cdp) external onlyMember note {
require(man.cushion(cdp) == 0, "untop: should-be-untopped-by-user");
resetCdp(cdp);
}
function bite(uint cdp, uint dart, uint minInk) external onlyMember note returns(uint dMemberInk){
uint index = getIndex(cdpData[cdp].members, msg.sender);
uint availBite = availBite(cdp, index);
require(dart <= availBite, "bite: debt-too-small");
cdpData[cdp].bite[index] = add(cdpData[cdp].bite[index], dart);
uint dink = man.bite(cdp, dart);
// update user rad
bytes32 ilk = man.ilks(cdp);
(,uint rate,,,) = vat.ilks(ilk);
uint cushionPortion = mul(cdpData[cdp].cushion, dart) / cdpData[cdp].art;
rad[msg.sender] = sub(rad[msg.sender], sub(mul(dart, rate), cushionPortion));
// DAI to USD rate, scale 1e18
uint d2uPrice = dai2usd.getMarketPrice(DAI_MARKET_ID);
// dMemberInk = debt * 1.065 * d2uPrice
// dMemberInk = dink * (shrn/shrd) * (d2uPrice/1e18)
dMemberInk = mul(mul(dink, shrn), d2uPrice) / mul(shrd, uint(1 ether));
// To protect edge case when 1 DAI > 1.13 USD
if(dMemberInk > dink) dMemberInk = dink;
// Remaining to Jar
uint userInk = sub(dink, dMemberInk);
require(dMemberInk >= minInk, "bite: low-dink");
vat.flux(ilk, address(this), jar, userInk);
vat.flux(ilk, address(this), msg.sender, dMemberInk);
}
function availBite(uint cdp, address member) public view returns (uint) {
uint index = getIndex(cdpData[cdp].members, member);
return availBite(cdp, index);
}
function availBite(uint cdp, uint index) internal view returns (uint) {
if(index == uint(-1)) return 0;
uint numMembers = cdpData[cdp].members.length;
uint maxArt = cdpData[cdp].art / numMembers;
// give dust to first member
if(index == 0) {
uint dust = cdpData[cdp].art % numMembers;
maxArt = add(maxArt, dust);
}
uint availArt = sub(maxArt, cdpData[cdp].bite[index]);
address urn = man.urns(cdp);
bytes32 ilk = man.ilks(cdp);
(,uint art) = vat.urns(ilk, urn);
uint remainingArt = add(art, man.cushion(cdp));
return availArt < remainingArt ? availArt : remainingArt;
}
}
contract ChainlinkLike {
function latestAnswer() external view returns (int256);
}
contract LiquidatorInfo is Math {
struct VaultInfo {
bytes32 collateralType;
uint collateralInWei;
uint debtInDaiWei;
uint liquidationPrice;
uint expectedEthReturnWithCurrentPrice;
bool expectedEthReturnBetterThanChainlinkPrice;
}
struct CushionInfo {
uint cushionSizeInWei;
uint numLiquidators;
uint cushionSizeInWeiIfAllHaveBalance;
uint numLiquidatorsIfAllHaveBalance;
bool shouldProvideCushion;
bool shouldProvideCushionIfAllHaveBalance;
uint minimumTimeBeforeCallingTopup;
bool canCallTopupNow;
bool shouldCallUntop;
bool isToppedUp;
}
struct BiteInfo {
uint availableBiteInArt;
uint availableBiteInDaiWei;
uint minimumTimeBeforeCallingBite;
bool canCallBiteNow;
}
struct CdpInfo {
uint cdp;
uint blockNumber;
VaultInfo vault;
CushionInfo cushion;
BiteInfo bite;
}
// Struct to store local vars. This avoid stack too deep error
struct CdpDataVars {
uint cdpArt;
uint cushion;
address[] cdpWinners;
uint[] bite;
}
LiquidationMachine manager;
VatLike public vat;
Pool pool;
SpotLike spot;
ChainlinkLike chainlink;
uint constant RAY = 1e27;
constructor(LiquidationMachine manager_, address chainlink_) public {
manager = manager_;
vat = VatLike(address(manager.vat()));
pool = Pool(manager.pool());
spot = SpotLike(address(pool.spot()));
chainlink = ChainlinkLike(chainlink_);
}
function getExpectedEthReturn(bytes32 collateralType, uint daiDebt, uint currentPriceFeedValue) public returns(uint) {
// get chope value
(,uint chop,) = manager.end().cat().ilks(collateralType);
uint biteIlk = mul(chop, daiDebt) / currentPriceFeedValue;
// DAI to USD rate, scale 1e18
uint d2uPrice = pool.dai2usd().getMarketPrice(pool.DAI_MARKET_ID());
uint shrn = pool.shrn();
uint shrd = pool.shrd();
return mul(mul(biteIlk, shrn), d2uPrice) / mul(shrd, uint(1 ether));
}
function getVaultInfo(uint cdp, uint currentPriceFeedValue) public returns(VaultInfo memory info) {
address urn = manager.urns(cdp);
info.collateralType = manager.ilks(cdp);
uint cushion = manager.cushion(cdp);
uint art;
(info.collateralInWei, art) = vat.urns(info.collateralType, urn);
if(info.collateralInWei == 0) return info;
(,uint rate,,,) = vat.ilks(info.collateralType);
info.debtInDaiWei = mul(add(art, cushion), rate) / RAY;
(, uint mat) = spot.ilks(info.collateralType);
info.liquidationPrice = mul(info.debtInDaiWei, mat) / mul(info.collateralInWei, RAY / 1e18);
if(currentPriceFeedValue > 0) {
info.expectedEthReturnWithCurrentPrice = getExpectedEthReturn(info.collateralType, info.debtInDaiWei, currentPriceFeedValue);
}
int chainlinkPrice = chainlink.latestAnswer();
uint chainlinkEthReturn = 0;
if(chainlinkPrice > 0) {
chainlinkEthReturn = mul(info.debtInDaiWei, uint(chainlinkPrice)) / 1 ether;
}
info.expectedEthReturnBetterThanChainlinkPrice =
info.expectedEthReturnWithCurrentPrice > chainlinkEthReturn;
}
function getCushionInfo(uint cdp, address me, uint numMembers) public view returns(CushionInfo memory info) {
CdpDataVars memory c;
(c.cdpArt, c.cushion, c.cdpWinners, c.bite) = pool.getCdpData(cdp);
for(uint i = 0 ; i < c.cdpWinners.length ; i++) {
if(me == c.cdpWinners[i]) {
uint perUserArt = c.cdpArt / c.cdpWinners.length;
info.shouldCallUntop = manager.cushion(cdp) == 0 && c.cushion > 0 && c.bite[i] < perUserArt;
info.isToppedUp = c.bite[i] < perUserArt;
break;
}
}
(uint dart, uint dtab, uint art, bool should, address[] memory winners) = pool.topupInfo(cdp);
info.numLiquidators = winners.length;
info.cushionSizeInWei = dtab / RAY;
if(dart == 0) {
if(info.isToppedUp) {
info.numLiquidatorsIfAllHaveBalance = winners.length;
info.cushionSizeInWei = c.cushion / RAY;
}
return info;
}
if(art < pool.minArt()) {
info.cushionSizeInWeiIfAllHaveBalance = info.cushionSizeInWei;
info.numLiquidatorsIfAllHaveBalance = 1;
info.shouldProvideCushion = false;
for(uint i = 0 ; i < winners.length ; i++) {
if(me == winners[i]) info.shouldProvideCushion = true;
}
uint chosen = uint(keccak256(abi.encodePacked(cdp, now / 1 hours))) % numMembers;
info.shouldProvideCushionIfAllHaveBalance = (pool.members(chosen) == me);
}
else {
info.cushionSizeInWeiIfAllHaveBalance = info.cushionSizeInWei / numMembers;
info.numLiquidatorsIfAllHaveBalance = numMembers;
info.shouldProvideCushion = true;
info.shouldProvideCushionIfAllHaveBalance = true;
}
info.canCallTopupNow = !info.isToppedUp && should && info.shouldProvideCushion;
bytes32 ilk = manager.ilks(cdp);
uint topupTime = add(uint(pool.osm(ilk).zzz()), uint(pool.osm(ilk).hop())/2);
info.minimumTimeBeforeCallingTopup = (now >= topupTime) ? 0 : sub(topupTime, now);
}
function getBiteInfo(uint cdp, address me) public view returns(BiteInfo memory info) {
info.availableBiteInArt = pool.availBite(cdp, me);
bytes32 ilk = manager.ilks(cdp);
uint priceUpdateTime = add(uint(pool.osm(ilk).zzz()), uint(pool.osm(ilk).hop()));
info.minimumTimeBeforeCallingBite = (now >= priceUpdateTime) ? 0 : sub(priceUpdateTime, now);
if(info.availableBiteInArt == 0) return info;
address u = manager.urns(cdp);
(,uint rate, uint currSpot,,) = vat.ilks(ilk);
info.availableBiteInDaiWei = mul(rate, info.availableBiteInArt) / RAY;
(uint ink, uint art) = vat.urns(ilk, u);
uint cushion = manager.cushion(cdp);
info.canCallBiteNow = (mul(ink, currSpot) < mul(add(art, cushion), rate)) || manager.bitten(cdp);
}
function getNumMembers() public returns(uint) {
for(uint i = 0 ; /* infinite loop */ ; i++) {
(bool result,) = address(pool).call(abi.encodeWithSignature("members(uint256)", i));
if(! result) return i;
}
}
function getCdpData(uint startCdp, uint endCdp, address me, uint currentPriceFeedValue) public returns(CdpInfo[] memory info) {
uint numMembers = getNumMembers();
info = new CdpInfo[](add(sub(endCdp, startCdp), uint(1)));
for(uint cdp = startCdp ; cdp <= endCdp ; cdp++) {
uint index = cdp - startCdp;
info[index].cdp = cdp;
info[index].blockNumber = block.number;
info[index].vault = getVaultInfo(cdp, currentPriceFeedValue);
info[index].cushion = getCushionInfo(cdp, me, numMembers);
info[index].bite = getBiteInfo(cdp, me);
}
}
}
contract FlatLiquidatorInfo is LiquidatorInfo {
constructor(LiquidationMachine manager_, address chainlink_) public LiquidatorInfo(manager_, chainlink_) {}
function getVaultInfoFlat(uint cdp, uint currentPriceFeedValue) external
returns(bytes32 collateralType, uint collateralInWei, uint debtInDaiWei, uint liquidationPrice,
uint expectedEthReturnWithCurrentPrice, bool expectedEthReturnBetterThanChainlinkPrice) {
VaultInfo memory info = getVaultInfo(cdp, currentPriceFeedValue);
collateralType = info.collateralType;
collateralInWei = info.collateralInWei;
debtInDaiWei = info.debtInDaiWei;
liquidationPrice = info.liquidationPrice;
expectedEthReturnWithCurrentPrice = info.expectedEthReturnWithCurrentPrice;
expectedEthReturnBetterThanChainlinkPrice = info.expectedEthReturnBetterThanChainlinkPrice;
}
function getCushionInfoFlat(uint cdp, address me, uint numMembers) external view
returns(uint cushionSizeInWei, uint numLiquidators, uint cushionSizeInWeiIfAllHaveBalance,
uint numLiquidatorsIfAllHaveBalance, bool shouldProvideCushion, bool shouldProvideCushionIfAllHaveBalance,
bool canCallTopupNow, bool shouldCallUntop, uint minimumTimeBeforeCallingTopup,
bool isToppedUp) {
CushionInfo memory info = getCushionInfo(cdp, me, numMembers);
cushionSizeInWei = info.cushionSizeInWei;
numLiquidators = info.numLiquidators;
cushionSizeInWeiIfAllHaveBalance = info.cushionSizeInWeiIfAllHaveBalance;
numLiquidatorsIfAllHaveBalance = info.numLiquidatorsIfAllHaveBalance;
shouldProvideCushion = info.shouldProvideCushion;
shouldProvideCushionIfAllHaveBalance = info.shouldProvideCushionIfAllHaveBalance;
canCallTopupNow = info.canCallTopupNow;
shouldCallUntop = info.shouldCallUntop;
minimumTimeBeforeCallingTopup = info.minimumTimeBeforeCallingTopup;
isToppedUp = info.isToppedUp;
}
function getBiteInfoFlat(uint cdp, address me) external view
returns(uint availableBiteInArt, uint availableBiteInDaiWei, bool canCallBiteNow,uint minimumTimeBeforeCallingBite) {
BiteInfo memory info = getBiteInfo(cdp, me);
availableBiteInArt = info.availableBiteInArt;
availableBiteInDaiWei = info.availableBiteInDaiWei;
canCallBiteNow = info.canCallBiteNow;
minimumTimeBeforeCallingBite = info.minimumTimeBeforeCallingBite;
}
}
contract ERC20Like {
function balanceOf(address guy) public view returns(uint);
}
contract VatBalanceLike {
function gem(bytes32 ilk, address user) external view returns(uint);
function dai(address user) external view returns(uint);
}
contract LiquidatorBalanceInfo {
struct BalanceInfo {
uint blockNumber;
uint ethBalance;
uint wethBalance;
uint daiBalance;
uint vatDaiBalanceInWei;
uint vatEthBalanceInWei;
uint poolDaiBalanceInWei;
}
uint constant RAY = 1e27;
function getBalanceInfo(address me, address pool, address vat, bytes32 ilk, address dai, address weth)
public view returns(BalanceInfo memory info) {
info.blockNumber = block.number;
info.ethBalance = me.balance;
info.wethBalance = ERC20Like(weth).balanceOf(me);
info.daiBalance = ERC20Like(dai).balanceOf(me);
info.vatDaiBalanceInWei = VatBalanceLike(vat).dai(me) / RAY;
info.vatEthBalanceInWei = VatBalanceLike(vat).gem(ilk, me);
info.poolDaiBalanceInWei = Pool(pool).rad(me) / RAY;
}
function getBalanceInfoFlat(address me, address pool, address vat, bytes32 ilk, address dai, address weth)
public view returns(uint blockNumber, uint ethBalance, uint wethBalance, uint daiBalance, uint vatDaiBalanceInWei,
uint vatEthBalanceInWei, uint poolDaiBalanceInWei) {
BalanceInfo memory info = getBalanceInfo(me, pool, vat, ilk, dai, weth);
blockNumber = info.blockNumber;
ethBalance = info.ethBalance;
wethBalance = info.wethBalance;
daiBalance = info.daiBalance;
vatDaiBalanceInWei = info.vatDaiBalanceInWei;
vatEthBalanceInWei = info.vatEthBalanceInWei;
poolDaiBalanceInWei = info.poolDaiBalanceInWei;
}
} | Allow/disallow a usr address to manage the cdp. | function cdpAllow(
uint cdp,
address usr,
uint ok
) public cdpAllowed(cdp) {
cdpCan[owns[cdp]][cdp][usr] = ok;
}
| 2,205,287 |
./full_match/1/0xE60a57cc57b51C4e801Ee8a0E6Df675F94abC0af/sources/contracts/ShopXReserveNFT.sol | totalMintedSupply():Returns the total tokens minted so far. 1 is always subtracted from the Counter since it tracks the next available tokenId. Note. totalSupply() is the count of valid NFTs tracked by this contract, where each one of them has an assigned and queryable owner not equal to the zero address totalSupply(): NFTs minted so far - NFTs burned so far (totalCirculatingSupply) See {IERC721Enumerable-totalSupply}/ | function totalMintedSupply() public view returns (uint256) {
return _totalMinted();
}
| 4,887,304 |
./partial_match/1/0x5625E1Bbe09AB07a0E2a73f2bB5D169838Fd5CCb/sources/home/liam/EtherProjects/YFN/core/contracts/YFNOEngine.sol | Safe yfno transfer function, just in case if rounding error causes pool to not have enough LEMONs. | function safeYfnoTransfer(address _to, uint256 _amount) internal {
uint256 yfnoBal = yfno.balanceOf(address(this));
if (_amount > yfnoBal) {
yfno.transfer(_to, yfnoBal);
yfno.transfer(_to, _amount);
}
}
| 15,734,147 |
./full_match/10200/0x70056a74c9b33474d2A93e34D16315623f9fF710/sources/project_/contracts/SBCDepositContract.sol | Claim withdrawal amounts for an array of addresses _addresses Addresses to transfer withdrawable tokens/ | function claimWithdrawals(address[] calldata _addresses) external {
for (uint256 i = 0; i < _addresses.length; ++i) {
claimWithdrawal(_addresses[i]);
}
}
| 3,785,661 |
pragma solidity ^0.5.3;
import "openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./LinkedList.sol";
import "./SortedLinkedList.sol";
/**
* @title Maintains a sorted list of unsigned ints keyed by bytes32.
*/
library SortedLinkedListWithMedian {
using SafeMath for uint256;
using SortedLinkedList for SortedLinkedList.List;
enum MedianAction { None, Lesser, Greater }
enum MedianRelation { Undefined, Lesser, Greater, Equal }
struct List {
SortedLinkedList.List list;
bytes32 median;
mapping(bytes32 => MedianRelation) relation;
}
/**
* @notice Inserts an element into a doubly linked list.
* @param key The key of the element to insert.
* @param value The element value.
* @param lesserKey The key of the element less than the element to insert.
* @param greaterKey The key of the element greater than the element to insert.
*/
function insert(
List storage list,
bytes32 key,
uint256 value,
bytes32 lesserKey,
bytes32 greaterKey
) public {
list.list.insert(key, value, lesserKey, greaterKey);
LinkedList.Element storage element = list.list.list.elements[key];
MedianAction action = MedianAction.None;
if (list.list.list.numElements == 1) {
list.median = key;
list.relation[key] = MedianRelation.Equal;
} else if (list.list.list.numElements % 2 == 1) {
// When we have an odd number of elements, and the element that we inserted is less than
// the previous median, we need to slide the median down one element, since we had previously
// selected the greater of the two middle elements.
if (
element.previousKey == bytes32(0) ||
list.relation[element.previousKey] == MedianRelation.Lesser
) {
action = MedianAction.Lesser;
list.relation[key] = MedianRelation.Lesser;
} else {
list.relation[key] = MedianRelation.Greater;
}
} else {
// When we have an even number of elements, and the element that we inserted is greater than
// the previous median, we need to slide the median up one element, since we always select
// the greater of the two middle elements.
if (
element.nextKey == bytes32(0) || list.relation[element.nextKey] == MedianRelation.Greater
) {
action = MedianAction.Greater;
list.relation[key] = MedianRelation.Greater;
} else {
list.relation[key] = MedianRelation.Lesser;
}
}
updateMedian(list, action);
}
/**
* @notice Removes an element from the doubly linked list.
* @param key The key of the element to remove.
*/
function remove(List storage list, bytes32 key) public {
MedianAction action = MedianAction.None;
if (list.list.list.numElements == 0) {
list.median = bytes32(0);
} else if (list.list.list.numElements % 2 == 0) {
// When we have an even number of elements, we always choose the higher of the two medians.
// Thus, if the element we're removing is greaterKey than or equal to the median we need to
// slide the median left by one.
if (
list.relation[key] == MedianRelation.Greater || list.relation[key] == MedianRelation.Equal
) {
action = MedianAction.Lesser;
}
} else {
// When we don't have an even number of elements, we just choose the median value.
// Thus, if the element we're removing is less than or equal to the median, we need to slide
// median right by one.
if (
list.relation[key] == MedianRelation.Lesser || list.relation[key] == MedianRelation.Equal
) {
action = MedianAction.Greater;
}
}
updateMedian(list, action);
list.list.remove(key);
}
/**
* @notice Updates an element in the list.
* @param key The element key.
* @param value The element value.
* @param lesserKey The key of the element will be just left of `key` after the update.
* @param greaterKey The key of the element will be just right of `key` after the update.
* @dev Note that only one of "lesserKey" or "greaterKey" needs to be correct to reduce friction.
*/
function update(
List storage list,
bytes32 key,
uint256 value,
bytes32 lesserKey,
bytes32 greaterKey
) public {
// TODO(asa): Optimize by not making any changes other than value if lesserKey and greaterKey
// don't change.
// TODO(asa): Optimize by not updating lesserKey/greaterKey for key
remove(list, key);
insert(list, key, value, lesserKey, greaterKey);
}
/**
* @notice Inserts an element at the tail of the doubly linked list.
* @param key The key of the element to insert.
*/
function push(List storage list, bytes32 key) public {
insert(list, key, 0, bytes32(0), list.list.list.tail);
}
/**
* @notice Removes N elements from the head of the list and returns their keys.
* @param n The number of elements to pop.
* @return The keys of the popped elements.
*/
function popN(List storage list, uint256 n) public returns (bytes32[] memory) {
require(n <= list.list.list.numElements);
bytes32[] memory keys = new bytes32[](n);
for (uint256 i = 0; i < n; i++) {
bytes32 key = list.list.list.head;
keys[i] = key;
remove(list, key);
}
return keys;
}
/**
* @notice Returns whether or not a particular key is present in the sorted list.
* @param key The element key.
* @return Whether or not the key is in the sorted list.
*/
function contains(List storage list, bytes32 key) public view returns (bool) {
return list.list.contains(key);
}
/**
* @notice Returns the value for a particular key in the sorted list.
* @param key The element key.
* @return The element value.
*/
function getValue(List storage list, bytes32 key) public view returns (uint256) {
return list.list.values[key];
}
/**
* @notice Returns the median value of the sorted list.
* @return The median value.
*/
function getMedianValue(List storage list) public view returns (uint256) {
return getValue(list, list.median);
}
/**
* @notice Returns the key of the first element in the list.
* @return The key of the first element in the list.
*/
function getHead(List storage list) external view returns (bytes32) {
return list.list.list.head;
}
/**
* @notice Returns the key of the median element in the list.
* @return The key of the median element in the list.
*/
function getMedian(List storage list) external view returns (bytes32) {
return list.median;
}
/**
* @notice Returns the key of the last element in the list.
* @return The key of the last element in the list.
*/
function getTail(List storage list) external view returns (bytes32) {
return list.list.list.tail;
}
/**
* @notice Returns the number of elements in the list.
* @return The number of elements in the list.
*/
function getNumElements(List storage list) external view returns (uint256) {
return list.list.list.numElements;
}
/**
* @notice Gets all elements from the doubly linked list.
* @return An unpacked list of elements from largest to smallest.
*/
function getElements(List storage list)
public
view
returns (bytes32[] memory, uint256[] memory, MedianRelation[] memory)
{
bytes32[] memory keys = getKeys(list);
uint256[] memory values = new uint256[](keys.length);
MedianRelation[] memory relations = new MedianRelation[](keys.length);
for (uint256 i = 0; i < keys.length; i = i.add(1)) {
values[i] = list.list.values[keys[i]];
relations[i] = list.relation[keys[i]];
}
return (keys, values, relations);
}
/**
* @notice Gets all element keys from the doubly linked list.
* @return All element keys from head to tail.
*/
function getKeys(List storage list) public view returns (bytes32[] memory) {
return list.list.getKeys();
}
/**
* @notice Moves the median pointer right or left of its current value.
* @param action Which direction to move the median pointer.
*/
function updateMedian(List storage list, MedianAction action) private {
LinkedList.Element storage previousMedian = list.list.list.elements[list.median];
if (action == MedianAction.Lesser) {
list.relation[list.median] = MedianRelation.Greater;
list.median = previousMedian.previousKey;
} else if (action == MedianAction.Greater) {
list.relation[list.median] = MedianRelation.Lesser;
list.median = previousMedian.nextKey;
}
list.relation[list.median] = MedianRelation.Equal;
}
}
| Returns the value for a particular key in the sorted list. key The element key. return The element value./ | function getValue(List storage list, bytes32 key) public view returns (uint256) {
return list.list.values[key];
}
| 12,855,714 |
./full_match/1/0x68c4cc21378301cfdd5702D66D58a036D7bAFE28/sources/src/RealitioForeignArbitrationProxyWithAppeals.sol | Gets contributions to the answers that are fully funded. _arbitrationID The ID of the arbitration. _round The round to query. _contributor The address whose contributions to query. return fundedAnswers IDs of the answers that are fully funded. return contributions The amount contributed to each funded answer by the contributor./ | function getContributionsToSuccessfulFundings(
uint256 _arbitrationID,
uint256 _round,
address _contributor
) external view returns (uint256[] memory fundedAnswers, uint256[] memory contributions) {
address requester = arbitrationIDToRequester[_arbitrationID];
ArbitrationRequest storage arbitration = arbitrationRequests[_arbitrationID][requester];
Round storage round = arbitration.rounds[_round];
fundedAnswers = round.fundedAnswers;
contributions = new uint256[](round.fundedAnswers.length);
for (uint256 i = 0; i < contributions.length; i++) {
contributions[i] = round.contributions[_contributor][fundedAnswers[i]];
}
}
| 8,333,671 |
pragma solidity ^0.4.24;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title DetailedERC20 token
* @dev The decimals are only for visualization purposes.
* All the operations are done using the smallest and indivisible token unit,
* just as on Ethereum all the operations are done in wei.
*/
contract DetailedERC20 is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
constructor(string _name, string _symbol, uint8 _decimals) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
}
}
/**
* @title Interface for the ST20 token standard
*/
contract IST20 is StandardToken, DetailedERC20 {
// off-chain hash
string public tokenDetails;
//transfer, transferFrom must respect use respect the result of verifyTransfer
function verifyTransfer(address _from, address _to, uint256 _amount) public returns (bool success);
/**
* @notice mints new tokens and assigns them to the target _investor.
* Can only be called by the STO attached to the token (Or by the ST owner if there's no STO attached yet)
*/
function mint(address _investor, uint256 _amount) public returns (bool success);
/**
* @notice Burn function used to burn the securityToken
* @param _value No. of token that get burned
*/
function burn(uint256 _value) public;
event Minted(address indexed to, uint256 amount);
event Burnt(address indexed _burner, uint256 _value);
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title Interface for all security tokens
*/
contract ISecurityToken is IST20, Ownable {
uint8 public constant PERMISSIONMANAGER_KEY = 1;
uint8 public constant TRANSFERMANAGER_KEY = 2;
uint8 public constant STO_KEY = 3;
uint8 public constant CHECKPOINT_KEY = 4;
uint256 public granularity;
// Value of current checkpoint
uint256 public currentCheckpointId;
// Total number of non-zero token holders
uint256 public investorCount;
// List of token holders
address[] public investors;
// Permissions this to a Permission module, which has a key of 1
// If no Permission return false - note that IModule withPerm will allow ST owner all permissions anyway
// this allows individual modules to override this logic if needed (to not allow ST owner all permissions)
function checkPermission(address _delegate, address _module, bytes32 _perm) public view returns(bool);
/**
* @notice returns module list for a module type
* @param _moduleType is which type of module we are trying to remove
* @param _moduleIndex is the index of the module within the chosen type
*/
function getModule(uint8 _moduleType, uint _moduleIndex) public view returns (bytes32, address);
/**
* @notice returns module list for a module name - will return first match
* @param _moduleType is which type of module we are trying to remove
* @param _name is the name of the module within the chosen type
*/
function getModuleByName(uint8 _moduleType, bytes32 _name) public view returns (bytes32, address);
/**
* @notice Queries totalSupply as of a defined checkpoint
* @param _checkpointId Checkpoint ID to query as of
*/
function totalSupplyAt(uint256 _checkpointId) public view returns(uint256);
/**
* @notice Queries balances as of a defined checkpoint
* @param _investor Investor to query balance for
* @param _checkpointId Checkpoint ID to query as of
*/
function balanceOfAt(address _investor, uint256 _checkpointId) public view returns(uint256);
/**
* @notice Creates a checkpoint that can be used to query historical balances / totalSuppy
*/
function createCheckpoint() public returns(uint256);
/**
* @notice gets length of investors array
* NB - this length may differ from investorCount if list has not been pruned of zero balance investors
* @return length
*/
function getInvestorsLength() public view returns(uint256);
}
/**
* @title Interface that any module factory contract should implement
*/
contract IModuleFactory is Ownable {
ERC20 public polyToken;
uint256 public setupCost;
uint256 public usageCost;
uint256 public monthlySubscriptionCost;
event LogChangeFactorySetupFee(uint256 _oldSetupcost, uint256 _newSetupCost, address _moduleFactory);
event LogChangeFactoryUsageFee(uint256 _oldUsageCost, uint256 _newUsageCost, address _moduleFactory);
event LogChangeFactorySubscriptionFee(uint256 _oldSubscriptionCost, uint256 _newMonthlySubscriptionCost, address _moduleFactory);
event LogGenerateModuleFromFactory(address _module, bytes32 indexed _moduleName, address indexed _moduleFactory, address _creator, uint256 _timestamp);
/**
* @notice Constructor
* @param _polyAddress Address of the polytoken
*/
constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public {
polyToken = ERC20(_polyAddress);
setupCost = _setupCost;
usageCost = _usageCost;
monthlySubscriptionCost = _subscriptionCost;
}
//Should create an instance of the Module, or throw
function deploy(bytes _data) external returns(address);
/**
* @notice Type of the Module factory
*/
function getType() public view returns(uint8);
/**
* @notice Get the name of the Module
*/
function getName() public view returns(bytes32);
/**
* @notice Get the description of the Module
*/
function getDescription() public view returns(string);
/**
* @notice Get the title of the Module
*/
function getTitle() public view returns(string);
/**
* @notice Get the Instructions that helped to used the module
*/
function getInstructions() public view returns (string);
/**
* @notice Get the tags related to the module factory
*/
function getTags() public view returns (bytes32[]);
//Pull function sig from _data
function getSig(bytes _data) internal pure returns (bytes4 sig) {
uint len = _data.length < 4 ? _data.length : 4;
for (uint i = 0; i < len; i++) {
sig = bytes4(uint(sig) + uint(_data[i]) * (2 ** (8 * (len - 1 - i))));
}
}
/**
* @notice used to change the fee of the setup cost
* @param _newSetupCost new setup cost
*/
function changeFactorySetupFee(uint256 _newSetupCost) public onlyOwner {
emit LogChangeFactorySetupFee(setupCost, _newSetupCost, address(this));
setupCost = _newSetupCost;
}
/**
* @notice used to change the fee of the usage cost
* @param _newUsageCost new usage cost
*/
function changeFactoryUsageFee(uint256 _newUsageCost) public onlyOwner {
emit LogChangeFactoryUsageFee(usageCost, _newUsageCost, address(this));
usageCost = _newUsageCost;
}
/**
* @notice used to change the fee of the subscription cost
* @param _newSubscriptionCost new subscription cost
*/
function changeFactorySubscriptionFee(uint256 _newSubscriptionCost) public onlyOwner {
emit LogChangeFactorySubscriptionFee(monthlySubscriptionCost, _newSubscriptionCost, address(this));
monthlySubscriptionCost = _newSubscriptionCost;
}
}
/**
* @title Interface that any module contract should implement
*/
contract IModule {
address public factory;
address public securityToken;
bytes32 public constant FEE_ADMIN = "FEE_ADMIN";
ERC20 public polyToken;
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
*/
constructor (address _securityToken, address _polyAddress) public {
securityToken = _securityToken;
factory = msg.sender;
polyToken = ERC20(_polyAddress);
}
/**
* @notice This function returns the signature of configure function
*/
function getInitFunction() public pure returns (bytes4);
//Allows owner, factory or permissioned delegate
modifier withPerm(bytes32 _perm) {
bool isOwner = msg.sender == ISecurityToken(securityToken).owner();
bool isFactory = msg.sender == factory;
require(isOwner||isFactory||ISecurityToken(securityToken).checkPermission(msg.sender, address(this), _perm), "Permission check failed");
_;
}
modifier onlyOwner {
require(msg.sender == ISecurityToken(securityToken).owner(), "Sender is not owner");
_;
}
modifier onlyFactory {
require(msg.sender == factory, "Sender is not factory");
_;
}
modifier onlyFactoryOwner {
require(msg.sender == IModuleFactory(factory).owner(), "Sender is not factory owner");
_;
}
/**
* @notice Return the permissions flag that are associated with Module
*/
function getPermissions() public view returns(bytes32[]);
/**
* @notice used to withdraw the fee by the factory owner
*/
function takeFee(uint256 _amount) public withPerm(FEE_ADMIN) returns(bool) {
require(polyToken.transferFrom(address(this), IModuleFactory(factory).owner(), _amount), "Unable to take fee");
return true;
}
}
/**
* @title Interface to be implemented by all checkpoint modules
*/
contract ICheckpoint is IModule {
}
/**
* @title Math
* @dev Assorted math operations
*/
library Math {
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
}
/////////////////////
// Module permissions
/////////////////////
// Owner DISTRIBUTE
// pushDividendPaymentToAddresses X X
// pushDividendPayment X X
// createDividend X
// createDividendWithCheckpoint X
// reclaimDividend X
/**
* @title Checkpoint module for issuing ether dividends
*/
contract EtherDividendCheckpoint is ICheckpoint {
using SafeMath for uint256;
bytes32 public constant DISTRIBUTE = "DISTRIBUTE";
struct Dividend {
uint256 checkpointId;
uint256 created; // Time at which the dividend was created
uint256 maturity; // Time after which dividend can be claimed - set to 0 to bypass
uint256 expiry; // Time until which dividend can be claimed - after this time any remaining amount can be withdrawn by issuer - set to very high value to bypass
uint256 amount; // Dividend amount in WEI
uint256 claimedAmount; // Amount of dividend claimed so far
uint256 totalSupply; // Total supply at the associated checkpoint (avoids recalculating this)
bool reclaimed;
mapping (address => bool) claimed; // List of addresses which have claimed dividend
}
// List of all dividends
Dividend[] public dividends;
event EtherDividendDeposited(address indexed _depositor, uint256 _checkpointId, uint256 _created, uint256 _maturity, uint256 _expiry, uint256 _amount, uint256 _totalSupply, uint256 _dividendIndex);
event EtherDividendClaimed(address indexed _payee, uint256 _dividendIndex, uint256 _amount);
event EtherDividendReclaimed(address indexed _claimer, uint256 _dividendIndex, uint256 _claimedAmount);
event EtherDividendClaimFailed(address indexed _payee, uint256 _dividendIndex, uint256 _amount);
modifier validDividendIndex(uint256 _dividendIndex) {
require(_dividendIndex < dividends.length, "Incorrect dividend index");
require(now >= dividends[_dividendIndex].maturity, "Dividend maturity is in the future");
require(now < dividends[_dividendIndex].expiry, "Dividend expiry is in the past");
require(!dividends[_dividendIndex].reclaimed, "Dividend has been reclaimed by issuer");
_;
}
/**
* @notice Constructor
* @param _securityToken Address of the security token
* @param _polyAddress Address of the polytoken
*/
constructor (address _securityToken, address _polyAddress) public
IModule(_securityToken, _polyAddress)
{
}
/**
* @notice Init function i.e generalise function to maintain the structure of the module contract
* @return bytes4
*/
function getInitFunction() public pure returns (bytes4) {
return bytes4(0);
}
/**
* @notice Creates a dividend and checkpoint for the dividend
* @param _maturity Time from which dividend can be paid
* @param _expiry Time until dividend can no longer be paid, and can be reclaimed by issuer
*/
function createDividend(uint256 _maturity, uint256 _expiry) payable public onlyOwner {
require(_expiry > _maturity);
require(_expiry > now);
require(msg.value > 0);
uint256 dividendIndex = dividends.length;
uint256 checkpointId = ISecurityToken(securityToken).createCheckpoint();
uint256 currentSupply = ISecurityToken(securityToken).totalSupply();
dividends.push(
Dividend(
checkpointId,
now,
_maturity,
_expiry,
msg.value,
0,
currentSupply,
false
)
);
emit EtherDividendDeposited(msg.sender, checkpointId, now, _maturity, _expiry, msg.value, currentSupply, dividendIndex);
}
/**
* @notice Creates a dividend with a provided checkpoint
* @param _maturity Time from which dividend can be paid
* @param _expiry Time until dividend can no longer be paid, and can be reclaimed by issuer
* @param _checkpointId Id of the checkpoint from which to issue dividend
*/
function createDividendWithCheckpoint(uint256 _maturity, uint256 _expiry, uint256 _checkpointId) payable public onlyOwner {
require(_expiry > _maturity);
require(_expiry > now);
require(msg.value > 0);
require(_checkpointId <= ISecurityToken(securityToken).currentCheckpointId());
uint256 dividendIndex = dividends.length;
uint256 currentSupply = ISecurityToken(securityToken).totalSupplyAt(_checkpointId);
dividends.push(
Dividend(
_checkpointId,
now,
_maturity,
_expiry,
msg.value,
0,
currentSupply,
false
)
);
emit EtherDividendDeposited(msg.sender, _checkpointId, now, _maturity, _expiry, msg.value, currentSupply, dividendIndex);
}
/**
* @notice Issuer can push dividends to provided addresses
* @param _dividendIndex Dividend to push
* @param _payees Addresses to which to push the dividend
*/
function pushDividendPaymentToAddresses(uint256 _dividendIndex, address[] _payees) public withPerm(DISTRIBUTE) validDividendIndex(_dividendIndex) {
Dividend storage dividend = dividends[_dividendIndex];
for (uint256 i = 0; i < _payees.length; i++) {
if (!dividend.claimed[_payees[i]]) {
_payDividend(_payees[i], dividend, _dividendIndex);
}
}
}
/**
* @notice Issuer can push dividends using the investor list from the security token
* @param _dividendIndex Dividend to push
* @param _start Index in investor list at which to start pushing dividends
* @param _iterations Number of addresses to push dividends for
*/
function pushDividendPayment(uint256 _dividendIndex, uint256 _start, uint256 _iterations) public withPerm(DISTRIBUTE) validDividendIndex(_dividendIndex) {
Dividend storage dividend = dividends[_dividendIndex];
uint256 numberInvestors = ISecurityToken(securityToken).getInvestorsLength();
for (uint256 i = _start; i < Math.min256(numberInvestors, _start.add(_iterations)); i++) {
address payee = ISecurityToken(securityToken).investors(i);
if (!dividend.claimed[payee]) {
_payDividend(payee, dividend, _dividendIndex);
}
}
}
/**
* @notice Investors can pull their own dividends
* @param _dividendIndex Dividend to pull
*/
function pullDividendPayment(uint256 _dividendIndex) public validDividendIndex(_dividendIndex)
{
Dividend storage dividend = dividends[_dividendIndex];
require(!dividend.claimed[msg.sender], "Dividend already reclaimed");
_payDividend(msg.sender, dividend, _dividendIndex);
}
/**
* @notice Internal function for paying dividends
* @param _payee address of investor
* @param _dividend storage with previously issued dividends
* @param _dividendIndex Dividend to pay
*/
function _payDividend(address _payee, Dividend storage _dividend, uint256 _dividendIndex) internal {
uint256 claim = calculateDividend(_dividendIndex, _payee);
_dividend.claimed[_payee] = true;
_dividend.claimedAmount = claim.add(_dividend.claimedAmount);
if (claim > 0) {
if (_payee.send(claim)) {
emit EtherDividendClaimed(_payee, _dividendIndex, claim);
} else {
_dividend.claimed[_payee] = false;
emit EtherDividendClaimFailed(_payee, _dividendIndex, claim);
}
}
}
/**
* @notice Issuer can reclaim remaining unclaimed dividend amounts, for expired dividends
* @param _dividendIndex Dividend to reclaim
*/
function reclaimDividend(uint256 _dividendIndex) public onlyOwner {
require(_dividendIndex < dividends.length, "Incorrect dividend index");
require(now >= dividends[_dividendIndex].expiry, "Dividend expiry is in the future");
require(!dividends[_dividendIndex].reclaimed, "Dividend already claimed");
Dividend storage dividend = dividends[_dividendIndex];
dividend.reclaimed = true;
uint256 remainingAmount = dividend.amount.sub(dividend.claimedAmount);
msg.sender.transfer(remainingAmount);
emit EtherDividendReclaimed(msg.sender, _dividendIndex, remainingAmount);
}
/**
* @notice Calculate amount of dividends claimable
* @param _dividendIndex Dividend to calculate
* @param _payee Affected investor address
* @return unit256
*/
function calculateDividend(uint256 _dividendIndex, address _payee) public view returns(uint256) {
Dividend storage dividend = dividends[_dividendIndex];
if (dividend.claimed[_payee]) {
return 0;
}
uint256 balance = ISecurityToken(securityToken).balanceOfAt(_payee, dividend.checkpointId);
return balance.mul(dividend.amount).div(dividend.totalSupply);
}
/**
* @notice Get the index according to the checkpoint id
* @param _checkpointId Checkpoint id to query
* @return uint256
*/
function getDividendIndex(uint256 _checkpointId) public view returns(uint256[]) {
uint256 counter = 0;
for(uint256 i = 0; i < dividends.length; i++) {
if (dividends[i].checkpointId == _checkpointId) {
counter++;
}
}
uint256[] memory index = new uint256[](counter);
counter = 0;
for(uint256 j = 0; j < dividends.length; j++) {
if (dividends[j].checkpointId == _checkpointId) {
index[counter] = j;
counter++;
}
}
return index;
}
/**
* @notice Return the permissions flag that are associated with STO
* @return bytes32 array
*/
function getPermissions() public view returns(bytes32[]) {
bytes32[] memory allPermissions = new bytes32[](1);
allPermissions[0] = DISTRIBUTE;
return allPermissions;
}
}
/**
* @title Factory for deploying EtherDividendCheckpoint module
*/
contract EtherDividendCheckpointFactory is IModuleFactory {
/**
* @notice Constructor
* @param _polyAddress Address of the polytoken
* @param _setupCost Setup cost of the module
* @param _usageCost Usage cost of the module
* @param _subscriptionCost Subscription cost of the module
*/
constructor (address _polyAddress, uint256 _setupCost, uint256 _usageCost, uint256 _subscriptionCost) public
IModuleFactory(_polyAddress, _setupCost, _usageCost, _subscriptionCost)
{
}
/**
* @notice used to launch the Module with the help of factory
* @return address Contract address of the Module
*/
function deploy(bytes /* _data */) external returns(address) {
if(setupCost > 0)
require(polyToken.transferFrom(msg.sender, owner, setupCost), "Failed transferFrom because of sufficent Allowance is not provided");
return address(new EtherDividendCheckpoint(msg.sender, address(polyToken)));
}
/**
* @notice Type of the Module factory
*/
function getType() public view returns(uint8) {
return 4;
}
/**
* @notice Get the name of the Module
*/
function getName() public view returns(bytes32) {
return "EtherDividendCheckpoint";
}
/**
* @notice Get the description of the Module
*/
function getDescription() public view returns(string) {
return "Create ETH dividends for token holders at a specific checkpoint";
}
/**
* @notice Get the title of the Module
*/
function getTitle() public view returns(string) {
return "Ether Dividend Checkpoint";
}
/**
* @notice Get the Instructions that helped to used the module
*/
function getInstructions() public view returns(string) {
return "Create a dividend which will be paid out to token holders proportional to their balances at the point the dividend is created";
}
/**
* @notice Get the tags related to the module factory
*/
function getTags() public view returns(bytes32[]) {
bytes32[] memory availableTags = new bytes32[](3);
availableTags[0] = "ETH";
availableTags[1] = "Checkpoint";
availableTags[2] = "Dividend";
return availableTags;
}
} | Get the description of the Module/ | function getDescription() public view returns(string) {
return "Create ETH dividends for token holders at a specific checkpoint";
}
| 7,866,406 |
./partial_match/1/0x645BA45dBe3c6942c812A46f9EE8115C89B524EC/sources/VersionManager.sol | Internal Methods / | function _isFeatureAuthorisedForWallet(address _wallet, address _feature) private view returns (bool) {
return isFeatureInVersion[_feature][walletVersions[_wallet]];
}
| 11,031,014 |
/**
*Submitted for verification at Etherscan.io on 2022-01-19
*/
// Sources flattened with hardhat v2.8.2 https://hardhat.org
// File contracts/solidity/proxy/IBeacon.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev This is the interface that {BeaconProxy} expects of its beacon.
*/
interface IBeacon {
/**
* @dev Must return an address that can be used as a delegate call target.
*
* {BeaconProxy} will check that this address is a contract.
*/
function childImplementation() external view returns (address);
function upgradeChildTo(address newImplementation) external;
}
// File contracts/solidity/interface/INFTXVaultFactory.sol
pragma solidity ^0.8.0;
interface INFTXVaultFactory is IBeacon {
// Read functions.
function numVaults() external view returns (uint256);
function zapContract() external view returns (address);
function feeDistributor() external view returns (address);
function eligibilityManager() external view returns (address);
function vault(uint256 vaultId) external view returns (address);
function allVaults() external view returns (address[] memory);
function vaultsForAsset(address asset) external view returns (address[] memory);
function isLocked(uint256 id) external view returns (bool);
function excludedFromFees(address addr) external view returns (bool);
function factoryMintFee() external view returns (uint64);
function factoryRandomRedeemFee() external view returns (uint64);
function factoryTargetRedeemFee() external view returns (uint64);
function factoryRandomSwapFee() external view returns (uint64);
function factoryTargetSwapFee() external view returns (uint64);
function vaultFees(uint256 vaultId) external view returns (uint256, uint256, uint256, uint256, uint256);
event NewFeeDistributor(address oldDistributor, address newDistributor);
event NewZapContract(address oldZap, address newZap);
event FeeExclusion(address feeExcluded, bool excluded);
event NewEligibilityManager(address oldEligManager, address newEligManager);
event NewVault(uint256 indexed vaultId, address vaultAddress, address assetAddress);
event UpdateVaultFees(uint256 vaultId, uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee);
event DisableVaultFees(uint256 vaultId);
event UpdateFactoryFees(uint256 mintFee, uint256 randomRedeemFee, uint256 targetRedeemFee, uint256 randomSwapFee, uint256 targetSwapFee);
// Write functions.
function __NFTXVaultFactory_init(address _vaultImpl, address _feeDistributor) external;
function createVault(
string calldata name,
string calldata symbol,
address _assetAddress,
bool is1155,
bool allowAllItems
) external returns (uint256);
function setFeeDistributor(address _feeDistributor) external;
function setEligibilityManager(address _eligibilityManager) external;
function setZapContract(address _zapContract) external;
function setFeeExclusion(address _excludedAddr, bool excluded) external;
function setFactoryFees(
uint256 mintFee,
uint256 randomRedeemFee,
uint256 targetRedeemFee,
uint256 randomSwapFee,
uint256 targetSwapFee
) external;
function setVaultFees(
uint256 vaultId,
uint256 mintFee,
uint256 randomRedeemFee,
uint256 targetRedeemFee,
uint256 randomSwapFee,
uint256 targetSwapFee
) external;
function disableVaultFees(uint256 vaultId) external;
}
// File contracts/solidity/interface/INFTXLPStaking.sol
pragma solidity ^0.8.0;
interface INFTXLPStaking {
function nftxVaultFactory() external view returns (address);
function rewardDistTokenImpl() external view returns (address);
function stakingTokenProvider() external view returns (address);
function vaultToken(address _stakingToken) external view returns (address);
function stakingToken(address _vaultToken) external view returns (address);
function rewardDistributionToken(uint256 vaultId) external view returns (address);
function newRewardDistributionToken(uint256 vaultId) external view returns (address);
function oldRewardDistributionToken(uint256 vaultId) external view returns (address);
function unusedRewardDistributionToken(uint256 vaultId) external view returns (address);
function rewardDistributionTokenAddr(address stakedToken, address rewardToken) external view returns (address);
// Write functions.
function __NFTXLPStaking__init(address _stakingTokenProvider) external;
function setNFTXVaultFactory(address newFactory) external;
function setStakingTokenProvider(address newProvider) external;
function addPoolForVault(uint256 vaultId) external;
function updatePoolForVault(uint256 vaultId) external;
function updatePoolForVaults(uint256[] calldata vaultId) external;
function receiveRewards(uint256 vaultId, uint256 amount) external returns (bool);
function deposit(uint256 vaultId, uint256 amount) external;
function timelockDepositFor(uint256 vaultId, address account, uint256 amount, uint256 timelockLength) external;
function exit(uint256 vaultId, uint256 amount) external;
function rescue(uint256 vaultId) external;
function withdraw(uint256 vaultId, uint256 amount) external;
function claimRewards(uint256 vaultId) external;
}
// File contracts/solidity/interface/INFTXFeeDistributor.sol
pragma solidity ^0.8.0;
interface INFTXFeeDistributor {
struct FeeReceiver {
uint256 allocPoint;
address receiver;
bool isContract;
}
function nftxVaultFactory() external returns (address);
function lpStaking() external returns (address);
function treasury() external returns (address);
function defaultTreasuryAlloc() external returns (uint256);
function defaultLPAlloc() external returns (uint256);
function allocTotal(uint256 vaultId) external returns (uint256);
function specificTreasuryAlloc(uint256 vaultId) external returns (uint256);
// Write functions.
function __FeeDistributor__init__(address _lpStaking, address _treasury) external;
function rescueTokens(address token) external;
function distribute(uint256 vaultId) external;
function addReceiver(uint256 _vaultId, uint256 _allocPoint, address _receiver, bool _isContract) external;
function initializeVaultReceivers(uint256 _vaultId) external;
function changeMultipleReceiverAlloc(
uint256[] memory _vaultIds,
uint256[] memory _receiverIdxs,
uint256[] memory allocPoints
) external;
function changeMultipleReceiverAddress(
uint256[] memory _vaultIds,
uint256[] memory _receiverIdxs,
address[] memory addresses,
bool[] memory isContracts
) external;
function changeReceiverAlloc(uint256 _vaultId, uint256 _idx, uint256 _allocPoint) external;
function changeReceiverAddress(uint256 _vaultId, uint256 _idx, address _address, bool _isContract) external;
function removeReceiver(uint256 _vaultId, uint256 _receiverIdx) external;
// Configuration functions.
function setTreasuryAddress(address _treasury) external;
function setDefaultTreasuryAlloc(uint256 _allocPoint) external;
function setSpecificTreasuryAlloc(uint256 _vaultId, uint256 _allocPoint) external;
function setLPStakingAddress(address _lpStaking) external;
function setNFTXVaultFactory(address _factory) external;
function setDefaultLPAlloc(uint256 _allocPoint) external;
}
// File contracts/solidity/proxy/ClonesUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for
* deploying minimal proxy contracts, also known as "clones".
*
* > To simply and cheaply clone contract functionality in an immutable way, this standard specifies
* > a minimal bytecode implementation that delegates all calls to a known, fixed address.
*
* The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2`
* (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the
* deterministic method.
*
* _Available since v3.4._
*/
library ClonesUpgradeable {
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create opcode, which should never revert.
*/
function clone(address implementation) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create(0, ptr, 0x37)
}
require(instance != address(0), "ERC1167: create failed");
}
/**
* @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`.
*
* This function uses the create2 opcode and a `salt` to deterministically deploy
* the clone. Using the same `implementation` and `salt` multiple time will revert, since
* the clones cannot be deployed twice at the same address.
*/
function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
instance := create2(0, ptr, 0x37, salt)
}
require(instance != address(0), "ERC1167: create2 failed");
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt, address deployer) internal pure returns (address predicted) {
// solhint-disable-next-line no-inline-assembly
assembly {
let ptr := mload(0x40)
mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(ptr, 0x14), shl(0x60, implementation))
mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000)
mstore(add(ptr, 0x38), shl(0x60, deployer))
mstore(add(ptr, 0x4c), salt)
mstore(add(ptr, 0x6c), keccak256(ptr, 0x37))
predicted := keccak256(add(ptr, 0x37), 0x55)
}
}
/**
* @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}.
*/
function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) {
return predictDeterministicAddress(implementation, salt, address(this));
}
}
// File contracts/solidity/proxy/Proxy.sol
pragma solidity ^0.8.0;
/**
* @dev This abstract contract provides a fallback function that delegates all calls to another contract using the EVM
* instruction `delegatecall`. We refer to the second contract as the _implementation_ behind the proxy, and it has to
* be specified by overriding the virtual {_implementation} function.
*
* Additionally, delegation to the implementation can be triggered manually through the {_fallback} function, or to a
* different contract through the {_delegate} function.
*
* The success and return data of the delegated call will be returned back to the caller of the proxy.
*/
abstract contract Proxy {
/**
* @dev Delegates the current call to `implementation`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
// solhint-disable-next-line no-inline-assembly
assembly {
// Copy msg.data. We take full control of memory in this inline assembly
// block because it will not return to Solidity code. We overwrite the
// Solidity scratch pad at memory position 0.
calldatacopy(0, 0, calldatasize())
// Call the implementation.
// out and outsize are 0 because we don't know the size yet.
let result := delegatecall(gas(), implementation, 0, calldatasize(), 0, 0)
// Copy the returned data.
returndatacopy(0, 0, returndatasize())
switch result
// delegatecall returns 0 on error.
case 0 { revert(0, returndatasize()) }
default { return(0, returndatasize()) }
}
}
/**
* @dev This is a virtual function that should be overriden so it returns the address to which the fallback function
* and {_fallback} should delegate.
*/
function _implementation() internal view virtual returns (address);
/**
* @dev Delegates the current call to the address returned by `_implementation()`.
*
* This function does not return to its internall call site, it will return directly to the external caller.
*/
function _fallback() internal virtual {
_beforeFallback();
_delegate(_implementation());
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if no other
* function in the contract matches the call data.
*/
fallback () external payable virtual {
_fallback();
}
/**
* @dev Fallback function that delegates calls to the address returned by `_implementation()`. Will run if call data
* is empty.
*/
receive () external payable virtual {
_fallback();
}
/**
* @dev Hook that is called before falling back to the implementation. Can happen as part of a manual `_fallback`
* call, or as part of the Solidity `fallback` or `receive` functions.
*
* If overriden should call `super._beforeFallback()`.
*/
function _beforeFallback() internal virtual {
}
}
// File contracts/solidity/util/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;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File contracts/solidity/proxy/BeaconProxy.sol
pragma solidity ^0.8.0;
/**
* @dev This contract implements a proxy that gets the implementation address for each call from a {UpgradeableBeacon}.
*
* The beacon address is stored in storage slot `uint256(keccak256('eip1967.proxy.beacon')) - 1`, so that it doesn't
* conflict with the storage layout of the implementation behind the proxy.
*
* _Available since v3.4._
*/
contract BeaconProxy is Proxy {
/**
* @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy.
* This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor.
*/
bytes32 private constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Initializes the proxy with `beacon`.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon. This
* will typically be an encoded function call, and allows initializating the storage of the proxy like a Solidity
* constructor.
*
* Requirements:
*
* - `beacon` must be a contract with the interface {IBeacon}.
*/
constructor(address beacon, bytes memory data) payable {
assert(_BEACON_SLOT == bytes32(uint256(keccak256("eip1967.proxy.beacon")) - 1));
_setBeacon(beacon, data);
}
/**
* @dev Returns the current beacon address.
*/
function _beacon() internal view virtual returns (address beacon) {
bytes32 slot = _BEACON_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
beacon := sload(slot)
}
}
/**
* @dev Returns the current implementation address of the associated beacon.
*/
function _implementation() internal view virtual override returns (address) {
return IBeacon(_beacon()).childImplementation();
}
/**
* @dev Changes the proxy to use a new beacon.
*
* If `data` is nonempty, it's used as data in a delegate call to the implementation returned by the beacon.
*
* Requirements:
*
* - `beacon` must be a contract.
* - The implementation returned by `beacon` must be a contract.
*/
function _setBeacon(address beacon, bytes memory data) internal virtual {
require(
Address.isContract(beacon),
"BeaconProxy: beacon is not a contract"
);
require(
Address.isContract(IBeacon(beacon).childImplementation()),
"BeaconProxy: beacon implementation is not a contract"
);
bytes32 slot = _BEACON_SLOT;
// solhint-disable-next-line no-inline-assembly
assembly {
sstore(slot, beacon)
}
if (data.length > 0) {
Address.functionDelegateCall(_implementation(), data, "BeaconProxy: function call failed");
}
}
}
// File contracts/solidity/proxy/Initializable.sol
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
}
// File contracts/solidity/util/ContextUpgradeable.sol
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// File contracts/solidity/util/OwnableUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// File contracts/solidity/proxy/UpgradeableBeacon.sol
pragma solidity ^0.8.0;
/**
* @dev This contract is used in conjunction with one or more instances of {BeaconProxy} to determine their
* implementation contract, which is where they will delegate all function calls.
*
* An owner is able to change the implementation the beacon points to, thus upgrading the proxies that use this beacon.
*/
contract UpgradeableBeacon is IBeacon, OwnableUpgradeable {
address private _childImplementation;
/**
* @dev Emitted when the child implementation returned by the beacon is changed.
*/
event Upgraded(address indexed childImplementation);
/**
* @dev Sets the address of the initial implementation, and the deployer account as the owner who can upgrade the
* beacon.
*/
function __UpgradeableBeacon__init(address childImplementation_) public initializer {
_setChildImplementation(childImplementation_);
}
/**
* @dev Returns the current child implementation address.
*/
function childImplementation() public view virtual override returns (address) {
return _childImplementation;
}
/**
* @dev Upgrades the beacon to a new implementation.
*
* Emits an {Upgraded} event.
*
* Requirements:
*
* - msg.sender must be the owner of the contract.
* - `newChildImplementation` must be a contract.
*/
function upgradeChildTo(address newChildImplementation) public virtual override onlyOwner {
_setChildImplementation(newChildImplementation);
}
/**
* @dev Sets the implementation contract address for this beacon
*
* Requirements:
*
* - `newChildImplementation` must be a contract.
*/
function _setChildImplementation(address newChildImplementation) private {
require(Address.isContract(newChildImplementation), "UpgradeableBeacon: child implementation is not a contract");
_childImplementation = newChildImplementation;
emit Upgraded(newChildImplementation);
}
}
// File contracts/solidity/util/PausableUpgradeable.sol
pragma solidity ^0.8.0;
contract PausableUpgradeable is OwnableUpgradeable {
function __Pausable_init() internal initializer {
__Ownable_init();
}
event SetPaused(uint256 lockId, bool paused);
event SetIsGuardian(address addr, bool isGuardian);
mapping(address => bool) public isGuardian;
mapping(uint256 => bool) public isPaused;
// 0 : createVault
// 1 : mint
// 2 : redeem
// 3 : swap
// 4 : flashloan
function onlyOwnerIfPaused(uint256 lockId) public view virtual {
require(!isPaused[lockId] || msg.sender == owner(), "Paused");
}
function unpause(uint256 lockId)
public
virtual
onlyOwner
{
isPaused[lockId] = false;
emit SetPaused(lockId, false);
}
function pause(uint256 lockId) public virtual {
require(isGuardian[msg.sender], "Can't pause");
isPaused[lockId] = true;
emit SetPaused(lockId, true);
}
function setIsGuardian(address addr, bool _isGuardian) public virtual onlyOwner {
isGuardian[addr] = _isGuardian;
emit SetIsGuardian(addr, _isGuardian);
}
}
// File contracts/solidity/interface/INFTXEligibility.sol
pragma solidity ^0.8.0;
interface INFTXEligibility {
// Read functions.
function name() external pure returns (string memory);
function finalized() external view returns (bool);
function targetAsset() external pure returns (address);
function checkAllEligible(uint256[] calldata tokenIds)
external
view
returns (bool);
function checkEligible(uint256[] calldata tokenIds)
external
view
returns (bool[] memory);
function checkAllIneligible(uint256[] calldata tokenIds)
external
view
returns (bool);
function checkIsEligible(uint256 tokenId) external view returns (bool);
// Write functions.
function __NFTXEligibility_init_bytes(bytes calldata configData) external;
function beforeMintHook(uint256[] calldata tokenIds) external;
function afterMintHook(uint256[] calldata tokenIds) external;
function beforeRedeemHook(uint256[] calldata tokenIds) external;
function afterRedeemHook(uint256[] calldata tokenIds) external;
}
// File contracts/solidity/token/IERC20Upgradeable.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);
}
// File contracts/solidity/interface/INFTXVault.sol
pragma solidity ^0.8.0;
interface INFTXVault is IERC20Upgradeable {
function manager() external view returns (address);
function assetAddress() external view returns (address);
function vaultFactory() external view returns (INFTXVaultFactory);
function eligibilityStorage() external view returns (INFTXEligibility);
function is1155() external view returns (bool);
function allowAllItems() external view returns (bool);
function enableMint() external view returns (bool);
function enableRandomRedeem() external view returns (bool);
function enableTargetRedeem() external view returns (bool);
function enableRandomSwap() external view returns (bool);
function enableTargetSwap() external view returns (bool);
function vaultId() external view returns (uint256);
function nftIdAt(uint256 holdingsIndex) external view returns (uint256);
function allHoldings() external view returns (uint256[] memory);
function totalHoldings() external view returns (uint256);
function mintFee() external view returns (uint256);
function randomRedeemFee() external view returns (uint256);
function targetRedeemFee() external view returns (uint256);
function randomSwapFee() external view returns (uint256);
function targetSwapFee() external view returns (uint256);
function vaultFees() external view returns (uint256, uint256, uint256, uint256, uint256);
event VaultInit(
uint256 indexed vaultId,
address assetAddress,
bool is1155,
bool allowAllItems
);
event ManagerSet(address manager);
event EligibilityDeployed(uint256 moduleIndex, address eligibilityAddr);
// event CustomEligibilityDeployed(address eligibilityAddr);
event EnableMintUpdated(bool enabled);
event EnableRandomRedeemUpdated(bool enabled);
event EnableTargetRedeemUpdated(bool enabled);
event EnableRandomSwapUpdated(bool enabled);
event EnableTargetSwapUpdated(bool enabled);
event Minted(uint256[] nftIds, uint256[] amounts, address to);
event Redeemed(uint256[] nftIds, uint256[] specificIds, address to);
event Swapped(
uint256[] nftIds,
uint256[] amounts,
uint256[] specificIds,
uint256[] redeemedIds,
address to
);
function __NFTXVault_init(
string calldata _name,
string calldata _symbol,
address _assetAddress,
bool _is1155,
bool _allowAllItems
) external;
function finalizeVault() external;
function setVaultMetadata(
string memory name_,
string memory symbol_
) external;
function setVaultFeatures(
bool _enableMint,
bool _enableRandomRedeem,
bool _enableTargetRedeem,
bool _enableRandomSwap,
bool _enableTargetSwap
) external;
function setFees(
uint256 _mintFee,
uint256 _randomRedeemFee,
uint256 _targetRedeemFee,
uint256 _randomSwapFee,
uint256 _targetSwapFee
) external;
function disableVaultFees() external;
// This function allows for an easy setup of any eligibility module contract from the EligibilityManager.
// It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow
// a similar interface.
function deployEligibilityStorage(
uint256 moduleIndex,
bytes calldata initData
) external returns (address);
// The manager has control over options like fees and features
function setManager(address _manager) external;
function mint(
uint256[] calldata tokenIds,
uint256[] calldata amounts /* ignored for ERC721 vaults */
) external returns (uint256);
function mintTo(
uint256[] calldata tokenIds,
uint256[] calldata amounts, /* ignored for ERC721 vaults */
address to
) external returns (uint256);
function redeem(uint256 amount, uint256[] calldata specificIds)
external
returns (uint256[] calldata);
function redeemTo(
uint256 amount,
uint256[] calldata specificIds,
address to
) external returns (uint256[] calldata);
function swap(
uint256[] calldata tokenIds,
uint256[] calldata amounts, /* ignored for ERC721 vaults */
uint256[] calldata specificIds
) external returns (uint256[] calldata);
function swapTo(
uint256[] calldata tokenIds,
uint256[] calldata amounts, /* ignored for ERC721 vaults */
uint256[] calldata specificIds,
address to
) external returns (uint256[] calldata);
function allValidNFTs(uint256[] calldata tokenIds)
external
view
returns (bool);
}
// File contracts/solidity/interface/INFTXEligibilityManager.sol
pragma solidity ^0.8.0;
interface INFTXEligibilityManager {
function nftxVaultFactory() external returns (address);
function eligibilityImpl() external returns (address);
function deployEligibility(uint256 vaultId, bytes calldata initData)
external
returns (address);
}
// File contracts/solidity/interface/IERC3156Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC3156 FlashBorrower, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*/
interface IERC3156FlashBorrowerUpgradeable {
/**
* @dev Receive a flash loan.
* @param initiator The initiator of the loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param fee The additional amount of tokens to repay.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
* @return The keccak256 hash of "ERC3156FlashBorrower.onFlashLoan"
*/
function onFlashLoan(
address initiator,
address token,
uint256 amount,
uint256 fee,
bytes calldata data
) external returns (bytes32);
}
/**
* @dev Interface of the ERC3156 FlashLender, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*/
interface IERC3156FlashLenderUpgradeable {
/**
* @dev The amount of currency available to be lended.
* @param token The loan currency.
* @return The amount of `token` that can be borrowed.
*/
function maxFlashLoan(
address token
) external view returns (uint256);
/**
* @dev The fee to be charged for a given loan.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @return The amount of `token` to be charged for the loan, on top of the returned principal.
*/
function flashFee(
address token,
uint256 amount
) external view returns (uint256);
/**
* @dev Initiate a flash loan.
* @param receiver The receiver of the tokens in the loan, and the receiver of the callback.
* @param token The loan currency.
* @param amount The amount of tokens lent.
* @param data Arbitrary data structure, intended to contain user-defined parameters.
*/
function flashLoan(
IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes calldata data
) external returns (bool);
}
// File contracts/solidity/token/IERC20Metadata.sol
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is 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);
}
// File contracts/solidity/token/ERC20Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
}
function _setMetadata(string memory name_, string memory symbol_) internal {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `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);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
_balances[account] = accountBalance - amount;
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[45] private __gap;
}
// File contracts/solidity/token/ERC20FlashMintUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the ERC3156 Flash loans extension, as defined in
* https://eips.ethereum.org/EIPS/eip-3156[ERC-3156].
*
* Adds the {flashLoan} method, which provides flash loan support at the token
* level. By default there is no fee, but this can be changed by overriding {flashFee}.
*/
abstract contract ERC20FlashMintUpgradeable is Initializable, ERC20Upgradeable, IERC3156FlashLenderUpgradeable {
function __ERC20FlashMint_init() internal initializer {
__Context_init_unchained();
__ERC20FlashMint_init_unchained();
}
function __ERC20FlashMint_init_unchained() internal initializer {
}
bytes32 constant private RETURN_VALUE = keccak256("ERC3156FlashBorrower.onFlashLoan");
/**
* @dev Returns the maximum amount of tokens available for loan.
* @param token The address of the token that is requested.
* @return The amont of token that can be loaned.
*/
function maxFlashLoan(address token) public view override returns (uint256) {
return token == address(this) ? type(uint256).max - totalSupply() : 0;
}
/**
* @dev Returns the fee applied when doing flash loans. By default this
* implementation has 0 fees. This function can be overloaded to make
* the flash loan mechanism deflationary.
* @param token The token to be flash loaned.
* @param amount The amount of tokens to be loaned.
* @return The fees applied to the corresponding flash loan.
*/
function flashFee(address token, uint256 amount) public view virtual override returns (uint256) {
require(token == address(this), "ERC20FlashMint: wrong token");
// silence warning about unused variable without the addition of bytecode.
amount;
return 0;
}
/**
* @dev Performs a flash loan. New tokens are minted and sent to the
* `receiver`, who is required to implement the {IERC3156FlashBorrower}
* interface. By the end of the flash loan, the receiver is expected to own
* amount + fee tokens and have them approved back to the token contract itself so
* they can be burned.
* @param receiver The receiver of the flash loan. Should implement the
* {IERC3156FlashBorrower.onFlashLoan} interface.
* @param token The token to be flash loaned. Only `address(this)` is
* supported.
* @param amount The amount of tokens to be loaned.
* @param data An arbitrary datafield that is passed to the receiver.
* @return `true` is the flash loan was successfull.
*/
function flashLoan(
IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes memory data
)
public virtual override returns (bool)
{
uint256 fee = flashFee(token, amount);
_mint(address(receiver), amount);
require(receiver.onFlashLoan(msg.sender, token, amount, fee, data) == RETURN_VALUE, "ERC20FlashMint: invalid return value");
uint256 currentAllowance = allowance(address(receiver), address(this));
require(currentAllowance >= amount + fee, "ERC20FlashMint: allowance does not allow refund");
_approve(address(receiver), address(this), currentAllowance - amount - fee);
_burn(address(receiver), amount + fee);
return true;
}
uint256[50] private __gap;
}
// File contracts/solidity/token/IERC721ReceiverUpgradeable.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 `IERC721.onERC721Received.selector`.
*/
function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4);
}
// File contracts/solidity/token/ERC721SafeHolderUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC721Receiver} interface.
*
* Accepts all token transfers.
* Make sure the contract is able to use its token with {IERC721-safeTransferFrom}, {IERC721-approve} or {IERC721-setApprovalForAll}.
*/
contract ERC721SafeHolderUpgradeable is IERC721ReceiverUpgradeable {
/**
* @dev See {IERC721Receiver-onERC721Received}.
*
* Always returns `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address,
uint256,
bytes memory
) public virtual override returns (bytes4) {
return this.onERC721Received.selector;
}
}
// File contracts/solidity/interface/IERC165Upgradeable.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);
}
// File contracts/solidity/token/IERC1155ReceiverUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev _Available since v3.1._
*/
interface IERC1155ReceiverUpgradeable is IERC165Upgradeable {
/**
@dev Handles the receipt of a single ERC1155 token type. This function is
called at the end of a `safeTransferFrom` after the balance has been updated.
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);
}
// File contracts/solidity/util/ERC165Upgradeable.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 ERC165Upgradeable is IERC165Upgradeable {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165Upgradeable).interfaceId;
}
}
// File contracts/solidity/token/ERC1155ReceiverUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155ReceiverUpgradeable is ERC165Upgradeable, IERC1155ReceiverUpgradeable {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) {
return interfaceId == type(IERC1155ReceiverUpgradeable).interfaceId
|| super.supportsInterface(interfaceId);
}
}
// File contracts/solidity/token/ERC1155SafeHolderUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev _Available since v3.1._
*/
abstract contract ERC1155SafeHolderUpgradeable is ERC1155ReceiverUpgradeable {
function onERC1155Received(address operator, address, uint256, uint256, bytes memory) public virtual override returns (bytes4) {
return this.onERC1155Received.selector;
}
function onERC1155BatchReceived(address operator, address, uint256[] memory, uint256[] memory, bytes memory) public virtual override returns (bytes4) {
return this.onERC1155BatchReceived.selector;
}
}
// File contracts/solidity/token/IERC721Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @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;
}
// File contracts/solidity/token/IERC1155Upgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC1155 compliant contract, as defined in the
* https://eips.ethereum.org/EIPS/eip-1155[EIP].
*
* _Available since v3.1._
*/
interface IERC1155Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`.
*/
event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value);
/**
* @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all
* transfers.
*/
event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values);
/**
* @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to
* `approved`.
*/
event ApprovalForAll(address indexed account, address indexed operator, bool approved);
/**
* @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI.
*
* If an {URI} event was emitted for `id`, the standard
* https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value
* returned by {IERC1155MetadataURI-uri}.
*/
event URI(string value, uint256 indexed id);
/**
* @dev Returns the amount of tokens of token type `id` owned by `account`.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function balanceOf(address account, uint256 id) external view returns (uint256);
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}.
*
* Requirements:
*
* - `accounts` and `ids` must have the same length.
*/
function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory);
/**
* @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`,
*
* Emits an {ApprovalForAll} event.
*
* Requirements:
*
* - `operator` cannot be the caller.
*/
function setApprovalForAll(address operator, bool approved) external;
/**
* @dev Returns true if `operator` is approved to transfer ``account``'s tokens.
*
* See {setApprovalForAll}.
*/
function isApprovedForAll(address account, address operator) external view returns (bool);
/**
* @dev Transfers `amount` tokens of token type `id` from `from` to `to`.
*
* Emits a {TransferSingle} event.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}.
* - `from` must have a balance of tokens of type `id` of at least `amount`.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the
* acceptance magic value.
*/
function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external;
/**
* @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}.
*
* Emits a {TransferBatch} event.
*
* Requirements:
*
* - `ids` and `amounts` must have the same length.
* - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the
* acceptance magic value.
*/
function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external;
}
// File contracts/solidity/util/ReentrancyGuardUpgradeable.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 ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// File contracts/solidity/util/EnumerableSetUpgradeable.sol
pragma solidity ^0.8.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
if (lastIndex != toDeleteIndex) {
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = valueIndex; // Replace lastvalue's index to valueIndex
}
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) {
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index) internal view returns (bytes32) {
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File contracts/solidity/NFTXVaultUpgradeable.sol
pragma solidity ^0.8.0;
// Authors: @0xKiwi_ and @alexgausman.
contract NFTXVaultUpgradeable is
OwnableUpgradeable,
ERC20FlashMintUpgradeable,
ReentrancyGuardUpgradeable,
ERC721SafeHolderUpgradeable,
ERC1155SafeHolderUpgradeable,
INFTXVault
{
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
uint256 constant base = 10**18;
uint256 public override vaultId;
address public override manager;
address public override assetAddress;
INFTXVaultFactory public override vaultFactory;
INFTXEligibility public override eligibilityStorage;
uint256 randNonce;
uint256 private UNUSED_FEE1;
uint256 private UNUSED_FEE2;
uint256 private UNUSED_FEE3;
bool public override is1155;
bool public override allowAllItems;
bool public override enableMint;
bool public override enableRandomRedeem;
bool public override enableTargetRedeem;
EnumerableSetUpgradeable.UintSet holdings;
mapping(uint256 => uint256) quantity1155;
bool public override enableRandomSwap;
bool public override enableTargetSwap;
function __NFTXVault_init(
string memory _name,
string memory _symbol,
address _assetAddress,
bool _is1155,
bool _allowAllItems
) public override virtual initializer {
__Ownable_init();
__ERC20_init(_name, _symbol);
require(_assetAddress != address(0), "Asset != address(0)");
assetAddress = _assetAddress;
vaultFactory = INFTXVaultFactory(msg.sender);
vaultId = vaultFactory.numVaults();
is1155 = _is1155;
allowAllItems = _allowAllItems;
emit VaultInit(vaultId, _assetAddress, _is1155, _allowAllItems);
setVaultFeatures(true /*enableMint*/, true /*enableRandomRedeem*/, true /*enableTargetRedeem*/, true /*enableRandomSwap*/, true /*enableTargetSwap*/);
}
function finalizeVault() external override virtual {
setManager(address(0));
}
// Added in v1.0.3.
function setVaultMetadata(
string calldata name_,
string calldata symbol_
) external override virtual {
onlyPrivileged();
_setMetadata(name_, symbol_);
}
function setVaultFeatures(
bool _enableMint,
bool _enableRandomRedeem,
bool _enableTargetRedeem,
bool _enableRandomSwap,
bool _enableTargetSwap
) public override virtual {
onlyPrivileged();
enableMint = _enableMint;
enableRandomRedeem = _enableRandomRedeem;
enableTargetRedeem = _enableTargetRedeem;
enableRandomSwap = _enableRandomSwap;
enableTargetSwap = _enableTargetSwap;
emit EnableMintUpdated(_enableMint);
emit EnableRandomRedeemUpdated(_enableRandomRedeem);
emit EnableTargetRedeemUpdated(_enableTargetRedeem);
emit EnableRandomSwapUpdated(_enableRandomSwap);
emit EnableTargetSwapUpdated(_enableTargetSwap);
}
function setFees(
uint256 _mintFee,
uint256 _randomRedeemFee,
uint256 _targetRedeemFee,
uint256 _randomSwapFee,
uint256 _targetSwapFee
) public override virtual {
onlyPrivileged();
vaultFactory.setVaultFees(vaultId, _mintFee, _randomRedeemFee, _targetRedeemFee, _randomSwapFee, _targetSwapFee);
}
function disableVaultFees() public override virtual {
onlyPrivileged();
vaultFactory.disableVaultFees(vaultId);
}
// This function allows for an easy setup of any eligibility module contract from the EligibilityManager.
// It takes in ABI encoded parameters for the desired module. This is to make sure they can all follow
// a similar interface.
function deployEligibilityStorage(
uint256 moduleIndex,
bytes calldata initData
) external override virtual returns (address) {
onlyPrivileged();
require(
address(eligibilityStorage) == address(0),
"NFTXVault: eligibility already set"
);
INFTXEligibilityManager eligManager = INFTXEligibilityManager(
vaultFactory.eligibilityManager()
);
address _eligibility = eligManager.deployEligibility(
moduleIndex,
initData
);
eligibilityStorage = INFTXEligibility(_eligibility);
// Toggle this to let the contract know to check eligibility now.
allowAllItems = false;
emit EligibilityDeployed(moduleIndex, _eligibility);
return _eligibility;
}
// // This function allows for the manager to set their own arbitrary eligibility contract.
// // Once eligiblity is set, it cannot be unset or changed.
// Disabled for launch.
// function setEligibilityStorage(address _newEligibility) public virtual {
// onlyPrivileged();
// require(
// address(eligibilityStorage) == address(0),
// "NFTXVault: eligibility already set"
// );
// eligibilityStorage = INFTXEligibility(_newEligibility);
// // Toggle this to let the contract know to check eligibility now.
// allowAllItems = false;
// emit CustomEligibilityDeployed(address(_newEligibility));
// }
// The manager has control over options like fees and features
function setManager(address _manager) public override virtual {
onlyPrivileged();
manager = _manager;
emit ManagerSet(_manager);
}
function mint(
uint256[] calldata tokenIds,
uint256[] calldata amounts /* ignored for ERC721 vaults */
) external override virtual returns (uint256) {
return mintTo(tokenIds, amounts, msg.sender);
}
function mintTo(
uint256[] memory tokenIds,
uint256[] memory amounts, /* ignored for ERC721 vaults */
address to
) public override virtual nonReentrant returns (uint256) {
onlyOwnerIfPaused(1);
require(enableMint, "Minting not enabled");
// Take the NFTs.
uint256 count = receiveNFTs(tokenIds, amounts);
// Mint to the user.
_mint(to, base * count);
uint256 totalFee = mintFee() * count;
_chargeAndDistributeFees(to, totalFee);
emit Minted(tokenIds, amounts, to);
return count;
}
function redeem(uint256 amount, uint256[] calldata specificIds)
external
override
virtual
returns (uint256[] memory)
{
return redeemTo(amount, specificIds, msg.sender);
}
function redeemTo(uint256 amount, uint256[] memory specificIds, address to)
public
override
virtual
nonReentrant
returns (uint256[] memory)
{
onlyOwnerIfPaused(2);
require(
amount == specificIds.length || enableRandomRedeem,
"NFTXVault: Random redeem not enabled"
);
require(
specificIds.length == 0 || enableTargetRedeem,
"NFTXVault: Target redeem not enabled"
);
// We burn all from sender and mint to fee receiver to reduce costs.
_burn(msg.sender, base * amount);
// Pay the tokens + toll.
(, uint256 _randomRedeemFee, uint256 _targetRedeemFee, ,) = vaultFees();
uint256 totalFee = (_targetRedeemFee * specificIds.length) + (
_randomRedeemFee * (amount - specificIds.length)
);
_chargeAndDistributeFees(msg.sender, totalFee);
// Withdraw from vault.
uint256[] memory redeemedIds = withdrawNFTsTo(amount, specificIds, to);
emit Redeemed(redeemedIds, specificIds, to);
return redeemedIds;
}
function swap(
uint256[] calldata tokenIds,
uint256[] calldata amounts, /* ignored for ERC721 vaults */
uint256[] calldata specificIds
) external override virtual returns (uint256[] memory) {
return swapTo(tokenIds, amounts, specificIds, msg.sender);
}
function swapTo(
uint256[] memory tokenIds,
uint256[] memory amounts, /* ignored for ERC721 vaults */
uint256[] memory specificIds,
address to
) public override virtual nonReentrant returns (uint256[] memory) {
onlyOwnerIfPaused(3);
uint256 count;
if (is1155) {
for (uint256 i; i < tokenIds.length; ++i) {
uint256 amount = amounts[i];
require(amount != 0, "NFTXVault: transferring < 1");
count += amount;
}
} else {
count = tokenIds.length;
}
require(
count == specificIds.length || enableRandomSwap,
"NFTXVault: Random swap disabled"
);
require(
specificIds.length == 0 || enableTargetSwap,
"NFTXVault: Target swap disabled"
);
(, , ,uint256 _randomSwapFee, uint256 _targetSwapFee) = vaultFees();
uint256 totalFee = (_targetSwapFee * specificIds.length) + (
_randomSwapFee * (count - specificIds.length)
);
_chargeAndDistributeFees(msg.sender, totalFee);
// Give the NFTs first, so the user wont get the same thing back, just to be nice.
uint256[] memory ids = withdrawNFTsTo(count, specificIds, to);
receiveNFTs(tokenIds, amounts);
emit Swapped(tokenIds, amounts, specificIds, ids, to);
return ids;
}
function flashLoan(
IERC3156FlashBorrowerUpgradeable receiver,
address token,
uint256 amount,
bytes memory data
) public override virtual returns (bool) {
onlyOwnerIfPaused(4);
return super.flashLoan(receiver, token, amount, data);
}
function mintFee() public view override virtual returns (uint256) {
(uint256 _mintFee, , , ,) = vaultFactory.vaultFees(vaultId);
return _mintFee;
}
function randomRedeemFee() public view override virtual returns (uint256) {
(, uint256 _randomRedeemFee, , ,) = vaultFactory.vaultFees(vaultId);
return _randomRedeemFee;
}
function targetRedeemFee() public view override virtual returns (uint256) {
(, , uint256 _targetRedeemFee, ,) = vaultFactory.vaultFees(vaultId);
return _targetRedeemFee;
}
function randomSwapFee() public view override virtual returns (uint256) {
(, , , uint256 _randomSwapFee, ) = vaultFactory.vaultFees(vaultId);
return _randomSwapFee;
}
function targetSwapFee() public view override virtual returns (uint256) {
(, , , ,uint256 _targetSwapFee) = vaultFactory.vaultFees(vaultId);
return _targetSwapFee;
}
function vaultFees() public view override virtual returns (uint256, uint256, uint256, uint256, uint256) {
return vaultFactory.vaultFees(vaultId);
}
function allValidNFTs(uint256[] memory tokenIds)
public
view
override
virtual
returns (bool)
{
if (allowAllItems) {
return true;
}
INFTXEligibility _eligibilityStorage = eligibilityStorage;
if (address(_eligibilityStorage) == address(0)) {
return false;
}
return _eligibilityStorage.checkAllEligible(tokenIds);
}
function nftIdAt(uint256 holdingsIndex) external view override virtual returns (uint256) {
return holdings.at(holdingsIndex);
}
// Added in v1.0.3.
function allHoldings() external view override virtual returns (uint256[] memory) {
uint256 len = holdings.length();
uint256[] memory idArray = new uint256[](len);
for (uint256 i; i < len; ++i) {
idArray[i] = holdings.at(i);
}
return idArray;
}
// Added in v1.0.3.
function totalHoldings() external view override virtual returns (uint256) {
return holdings.length();
}
// Added in v1.0.3.
function version() external pure returns (string memory) {
return "v1.0.5";
}
// We set a hook to the eligibility module (if it exists) after redeems in case anything needs to be modified.
function afterRedeemHook(uint256[] memory tokenIds) internal virtual {
INFTXEligibility _eligibilityStorage = eligibilityStorage;
if (address(_eligibilityStorage) == address(0)) {
return;
}
_eligibilityStorage.afterRedeemHook(tokenIds);
}
function receiveNFTs(uint256[] memory tokenIds, uint256[] memory amounts)
internal
virtual
returns (uint256)
{
require(allValidNFTs(tokenIds), "NFTXVault: not eligible");
uint256 length = tokenIds.length;
if (is1155) {
// This is technically a check, so placing it before the effect.
IERC1155Upgradeable(assetAddress).safeBatchTransferFrom(
msg.sender,
address(this),
tokenIds,
amounts,
""
);
uint256 count;
for (uint256 i; i < length; ++i) {
uint256 tokenId = tokenIds[i];
uint256 amount = amounts[i];
require(amount != 0, "NFTXVault: transferring < 1");
if (quantity1155[tokenId] == 0) {
holdings.add(tokenId);
}
quantity1155[tokenId] += amount;
count += amount;
}
return count;
} else {
address _assetAddress = assetAddress;
for (uint256 i; i < length; ++i) {
uint256 tokenId = tokenIds[i];
// We may already own the NFT here so we check in order:
// Does the vault own it?
// - If so, check if its in holdings list
// - If so, we reject. This means the NFT has already been claimed for.
// - If not, it means we have not yet accounted for this NFT, so we continue.
// -If not, we "pull" it from the msg.sender and add to holdings.
transferFromERC721(_assetAddress, tokenId);
holdings.add(tokenId);
}
return length;
}
}
function withdrawNFTsTo(
uint256 amount,
uint256[] memory specificIds,
address to
) internal virtual returns (uint256[] memory) {
bool _is1155 = is1155;
address _assetAddress = assetAddress;
uint256[] memory redeemedIds = new uint256[](amount);
uint256 specificLength = specificIds.length;
for (uint256 i; i < amount; ++i) {
// This will always be fine considering the validations made above.
uint256 tokenId = i < specificLength ?
specificIds[i] : getRandomTokenIdFromVault();
redeemedIds[i] = tokenId;
if (_is1155) {
quantity1155[tokenId] -= 1;
if (quantity1155[tokenId] == 0) {
holdings.remove(tokenId);
}
IERC1155Upgradeable(_assetAddress).safeTransferFrom(
address(this),
to,
tokenId,
1,
""
);
} else {
holdings.remove(tokenId);
transferERC721(_assetAddress, to, tokenId);
}
}
afterRedeemHook(redeemedIds);
return redeemedIds;
}
function _chargeAndDistributeFees(address user, uint256 amount) internal virtual {
// Do not charge fees if the zap contract is calling
// Added in v1.0.3. Changed to mapping in v1.0.5.
INFTXVaultFactory _vaultFactory = vaultFactory;
if (_vaultFactory.excludedFromFees(msg.sender)) {
return;
}
// Mint fees directly to the distributor and distribute.
if (amount > 0) {
address feeDistributor = _vaultFactory.feeDistributor();
// Changed to a _transfer() in v1.0.3.
_transfer(user, feeDistributor, amount);
INFTXFeeDistributor(feeDistributor).distribute(vaultId);
}
}
function transferERC721(address assetAddr, address to, uint256 tokenId) internal virtual {
address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;
address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB;
bytes memory data;
if (assetAddr == kitties) {
// Changed in v1.0.4.
data = abi.encodeWithSignature("transfer(address,uint256)", to, tokenId);
} else if (assetAddr == punks) {
// CryptoPunks.
data = abi.encodeWithSignature("transferPunk(address,uint256)", to, tokenId);
} else {
// Default.
data = abi.encodeWithSignature("safeTransferFrom(address,address,uint256)", address(this), to, tokenId);
}
(bool success, bytes memory returnData) = address(assetAddr).call(data);
require(success, string(returnData));
}
function transferFromERC721(address assetAddr, uint256 tokenId) internal virtual {
address kitties = 0x06012c8cf97BEaD5deAe237070F9587f8E7A266d;
address punks = 0xb47e3cd837dDF8e4c57F05d70Ab865de6e193BBB;
bytes memory data;
if (assetAddr == kitties) {
// Cryptokitties.
data = abi.encodeWithSignature("transferFrom(address,address,uint256)", msg.sender, address(this), tokenId);
} else if (assetAddr == punks) {
// CryptoPunks.
// Fix here for frontrun attack. Added in v1.0.2.
bytes memory punkIndexToAddress = abi.encodeWithSignature("punkIndexToAddress(uint256)", tokenId);
(bool checkSuccess, bytes memory result) = address(assetAddr).staticcall(punkIndexToAddress);
(address nftOwner) = abi.decode(result, (address));
require(checkSuccess && nftOwner == msg.sender, "Not the NFT owner");
data = abi.encodeWithSignature("buyPunk(uint256)", tokenId);
} else {
// Default.
// Allow other contracts to "push" into the vault, safely.
// If we already have the token requested, make sure we don't have it in the list to prevent duplicate minting.
if (IERC721Upgradeable(assetAddress).ownerOf(tokenId) == address(this)) {
require(!holdings.contains(tokenId), "Trying to use an owned NFT");
return;
} else {
data = abi.encodeWithSignature("safeTransferFrom(address,address,uint256)", msg.sender, address(this), tokenId);
}
}
(bool success, bytes memory resultData) = address(assetAddr).call(data);
require(success, string(resultData));
}
function getRandomTokenIdFromVault() internal virtual returns (uint256) {
uint256 randomIndex = uint256(
keccak256(
abi.encodePacked(
blockhash(block.number - 1),
randNonce,
block.coinbase,
block.difficulty,
block.timestamp
)
)
) % holdings.length();
++randNonce;
return holdings.at(randomIndex);
}
function onlyPrivileged() internal view {
if (manager == address(0)) {
require(msg.sender == owner(), "Not owner");
} else {
require(msg.sender == manager, "Not manager");
}
}
function onlyOwnerIfPaused(uint256 lockId) internal view {
require(!vaultFactory.isLocked(lockId) || msg.sender == owner(), "Paused");
}
}
// File contracts/solidity/NFTXVaultFactoryUpgradeable.sol
pragma solidity ^0.8.0;
// Authors: @0xKiwi_ and @alexgausman.
contract NFTXVaultFactoryUpgradeable is
PausableUpgradeable,
UpgradeableBeacon,
INFTXVaultFactory
{
uint256 private NOT_USED1; // Removed, no longer needed.
address public override zapContract; // No longer needed, but keeping for compatibility.
address public override feeDistributor;
address public override eligibilityManager;
mapping(uint256 => address) private NOT_USED3; // Removed, no longer needed.
mapping(address => address[]) _vaultsForAsset;
address[] internal vaults;
// v1.0.1
mapping(address => bool) public override excludedFromFees;
// v1.0.2
struct VaultFees {
bool active;
uint64 mintFee;
uint64 randomRedeemFee;
uint64 targetRedeemFee;
uint64 randomSwapFee;
uint64 targetSwapFee;
}
mapping(uint256 => VaultFees) private _vaultFees;
uint64 public override factoryMintFee;
uint64 public override factoryRandomRedeemFee;
uint64 public override factoryTargetRedeemFee;
uint64 public override factoryRandomSwapFee;
uint64 public override factoryTargetSwapFee;
function __NFTXVaultFactory_init(address _vaultImpl, address _feeDistributor) public override initializer {
__Pausable_init();
// We use a beacon proxy so that every child contract follows the same implementation code.
__UpgradeableBeacon__init(_vaultImpl);
setFeeDistributor(_feeDistributor);
setFactoryFees(0.1 ether, 0.05 ether, 0.1 ether, 0.05 ether, 0.1 ether);
}
function createVault(
string memory name,
string memory symbol,
address _assetAddress,
bool is1155,
bool allowAllItems
) external virtual override returns (uint256) {
onlyOwnerIfPaused(0);
require(feeDistributor != address(0), "NFTX: Fee receiver unset");
require(childImplementation() != address(0), "NFTX: Vault implementation unset");
address vaultAddr = deployVault(name, symbol, _assetAddress, is1155, allowAllItems);
uint256 _vaultId = vaults.length;
_vaultsForAsset[_assetAddress].push(vaultAddr);
vaults.push(vaultAddr);
INFTXFeeDistributor(feeDistributor).initializeVaultReceivers(_vaultId);
emit NewVault(_vaultId, vaultAddr, _assetAddress);
return _vaultId;
}
function setFactoryFees(
uint256 mintFee,
uint256 randomRedeemFee,
uint256 targetRedeemFee,
uint256 randomSwapFee,
uint256 targetSwapFee
) public onlyOwner virtual override {
require(mintFee <= 0.5 ether, "Cannot > 0.5 ether");
require(randomRedeemFee <= 0.5 ether, "Cannot > 0.5 ether");
require(targetRedeemFee <= 0.5 ether, "Cannot > 0.5 ether");
require(randomSwapFee <= 0.5 ether, "Cannot > 0.5 ether");
require(targetSwapFee <= 0.5 ether, "Cannot > 0.5 ether");
factoryMintFee = uint64(mintFee);
factoryRandomRedeemFee = uint64(randomRedeemFee);
factoryTargetRedeemFee = uint64(targetRedeemFee);
factoryRandomSwapFee = uint64(randomSwapFee);
factoryTargetSwapFee = uint64(targetSwapFee);
emit UpdateFactoryFees(mintFee, randomRedeemFee, targetRedeemFee, randomSwapFee, targetSwapFee);
}
function setVaultFees(
uint256 vaultId,
uint256 mintFee,
uint256 randomRedeemFee,
uint256 targetRedeemFee,
uint256 randomSwapFee,
uint256 targetSwapFee
) public virtual override {
if (msg.sender != owner()) {
address vaultAddr = vaults[vaultId];
require(msg.sender == vaultAddr, "Not from vault");
}
require(mintFee <= 0.5 ether, "Cannot > 0.5 ether");
require(randomRedeemFee <= 0.5 ether, "Cannot > 0.5 ether");
require(targetRedeemFee <= 0.5 ether, "Cannot > 0.5 ether");
require(randomSwapFee <= 0.5 ether, "Cannot > 0.5 ether");
require(targetSwapFee <= 0.5 ether, "Cannot > 0.5 ether");
_vaultFees[vaultId] = VaultFees(
true,
uint64(mintFee),
uint64(randomRedeemFee),
uint64(targetRedeemFee),
uint64(randomSwapFee),
uint64(targetSwapFee)
);
emit UpdateVaultFees(vaultId, mintFee, randomRedeemFee, targetRedeemFee, randomSwapFee, targetSwapFee);
}
function disableVaultFees(uint256 vaultId) public virtual override {
if (msg.sender != owner()) {
address vaultAddr = vaults[vaultId];
require(msg.sender == vaultAddr, "Not vault");
}
delete _vaultFees[vaultId];
emit DisableVaultFees(vaultId);
}
function setFeeDistributor(address _feeDistributor) public onlyOwner virtual override {
require(_feeDistributor != address(0));
emit NewFeeDistributor(feeDistributor, _feeDistributor);
feeDistributor = _feeDistributor;
}
function setZapContract(address _zapContract) public onlyOwner virtual override {
emit NewZapContract(zapContract, _zapContract);
zapContract = _zapContract;
}
function setFeeExclusion(address _excludedAddr, bool excluded) public onlyOwner virtual override {
emit FeeExclusion(_excludedAddr, excluded);
excludedFromFees[_excludedAddr] = excluded;
}
function setEligibilityManager(address _eligibilityManager) external onlyOwner virtual override {
emit NewEligibilityManager(eligibilityManager, _eligibilityManager);
eligibilityManager = _eligibilityManager;
}
function vaultFees(uint256 vaultId) external view virtual override returns (uint256, uint256, uint256, uint256, uint256) {
VaultFees memory fees = _vaultFees[vaultId];
if (fees.active) {
return (
uint256(fees.mintFee),
uint256(fees.randomRedeemFee),
uint256(fees.targetRedeemFee),
uint256(fees.randomSwapFee),
uint256(fees.targetSwapFee)
);
}
return (uint256(factoryMintFee), uint256(factoryRandomRedeemFee), uint256(factoryTargetRedeemFee), uint256(factoryRandomSwapFee), uint256(factoryTargetSwapFee));
}
function isLocked(uint256 lockId) external view override virtual returns (bool) {
return isPaused[lockId];
}
function vaultsForAsset(address assetAddress) external view override virtual returns (address[] memory) {
return _vaultsForAsset[assetAddress];
}
function vault(uint256 vaultId) external view override virtual returns (address) {
return vaults[vaultId];
}
function allVaults() external view override virtual returns (address[] memory) {
return vaults;
}
function numVaults() external view override virtual returns (uint256) {
return vaults.length;
}
function deployVault(
string memory name,
string memory symbol,
address _assetAddress,
bool is1155,
bool allowAllItems
) internal returns (address) {
address newBeaconProxy = address(new BeaconProxy(address(this), ""));
NFTXVaultUpgradeable(newBeaconProxy).__NFTXVault_init(name, symbol, _assetAddress, is1155, allowAllItems);
// Manager for configuration.
NFTXVaultUpgradeable(newBeaconProxy).setManager(msg.sender);
// Owner for administrative functions.
NFTXVaultUpgradeable(newBeaconProxy).transferOwnership(owner());
return newBeaconProxy;
}
} | This is technically a check, so placing it before the effect. We may already own the NFT here so we check in order: Does the vault own it? - If so, check if its in holdings list - If so, we reject. This means the NFT has already been claimed for. - If not, it means we have not yet accounted for this NFT, so we continue. -If not, we "pull" it from the msg.sender and add to holdings. | function receiveNFTs(uint256[] memory tokenIds, uint256[] memory amounts)
internal
virtual
returns (uint256)
{
require(allValidNFTs(tokenIds), "NFTXVault: not eligible");
uint256 length = tokenIds.length;
if (is1155) {
IERC1155Upgradeable(assetAddress).safeBatchTransferFrom(
msg.sender,
address(this),
tokenIds,
amounts,
""
);
uint256 count;
for (uint256 i; i < length; ++i) {
uint256 tokenId = tokenIds[i];
uint256 amount = amounts[i];
require(amount != 0, "NFTXVault: transferring < 1");
if (quantity1155[tokenId] == 0) {
holdings.add(tokenId);
}
quantity1155[tokenId] += amount;
count += amount;
}
return count;
address _assetAddress = assetAddress;
for (uint256 i; i < length; ++i) {
uint256 tokenId = tokenIds[i];
transferFromERC721(_assetAddress, tokenId);
holdings.add(tokenId);
}
return length;
}
}
| 2,228,158 |
pragma solidity ^0.5.0;
/**
* @title Tellor Transfer
* @dev Contais the methods related to transfers and ERC20. Tellor.sol and TellorGetters.sol
* reference this library for function's logic.
*/
library TellorTransfer {
using SafeMath for uint256;
event Approval(address indexed _owner, address indexed _spender, uint256 _value); //ERC20 Approval event
event Transfer(address indexed _from, address indexed _to, uint256 _value); //ERC20 Transfer Event
/*Functions*/
/**
* @dev Allows for a transfer of tokens to _to
* @param _to The address to send tokens to
* @param _amount The amount of tokens to send
* @return true if transfer is successful
*/
function transfer(TellorStorage.TellorStorageStruct storage self, address _to, uint256 _amount) public returns (bool success) {
doTransfer(self, msg.sender, _to, _amount);
return true;
}
/**
* @notice Send _amount tokens to _to from _from on the condition it
* is approved by _from
* @param _from The address holding the tokens being transferred
* @param _to The address of the recipient
* @param _amount The amount of tokens to be transferred
* @return True if the transfer was successful
*/
function transferFrom(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount)
public
returns (bool success)
{
require(self.allowed[_from][msg.sender] >= _amount, "Allowance is wrong");
self.allowed[_from][msg.sender] -= _amount;
doTransfer(self, _from, _to, _amount);
return true;
}
/**
* @dev This function approves a _spender an _amount of tokens to use
* @param _spender address
* @param _amount amount the spender is being approved for
* @return true if spender appproved successfully
*/
function approve(TellorStorage.TellorStorageStruct storage self, address _spender, uint256 _amount) public returns (bool) {
require(_spender != address(0), "Spender is 0-address");
self.allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @param _user address of party with the balance
* @param _spender address of spender of parties said balance
* @return Returns the remaining allowance of tokens granted to the _spender from the _user
*/
function allowance(TellorStorage.TellorStorageStruct storage self, address _user, address _spender) public view returns (uint256) {
return self.allowed[_user][_spender];
}
/**
* @dev Completes POWO transfers by updating the balances on the current block number
* @param _from address to transfer from
* @param _to addres to transfer to
* @param _amount to transfer
*/
function doTransfer(TellorStorage.TellorStorageStruct storage self, address _from, address _to, uint256 _amount) public {
require(_amount > 0, "Tried to send non-positive amount");
require(_to != address(0), "Receiver is 0 address");
//allowedToTrade checks the stakeAmount is removed from balance if the _user is staked
require(allowedToTrade(self, _from, _amount), "Stake amount was not removed from balance");
uint256 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);
emit Transfer(_from, _to, _amount);
}
/**
* @dev Gets balance of owner specified
* @param _user is the owner address used to look up the balance
* @return Returns the balance associated with the passed in _user
*/
function balanceOf(TellorStorage.TellorStorageStruct storage self, address _user) public view returns (uint256) {
return balanceOfAt(self, _user, block.number);
}
/**
* @dev Queries the balance of _user at a specific _blockNumber
* @param _user The address from which the balance will be retrieved
* @param _blockNumber The block number when the balance is queried
* @return The balance at _blockNumber specified
*/
function balanceOfAt(TellorStorage.TellorStorageStruct storage self, address _user, 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 This function returns whether or not a given user is allowed to trade a given amount
* and removing the staked amount from their balance if they are staked
* @param _user address of user
* @param _amount to check if the user can spend
* @return true if they are allowed to spend the amount being checked
*/
function allowedToTrade(TellorStorage.TellorStorageStruct storage self, address _user, uint256 _amount) public view returns (bool) {
if (self.stakerDetails[_user].currentStatus > 0) {
//Removes the stakeAmount from balance if the _user is staked
if (balanceOf(self, _user).sub(self.uintVars[keccak256("stakeAmount")]).sub(_amount) >= 0) {
return true;
}
} else if (balanceOf(self, _user).sub(_amount) >= 0) {
return true;
}
return false;
}
/**
* @dev Updates balance for from and to on the current block number via doTransfer
* @param checkpoints gets the mapping for the balances[owner]
* @param _value is the new balance
*/
function updateBalanceAtNow(TellorStorage.Checkpoint[] storage checkpoints, 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);
}
}
}
//import "./SafeMath.sol";
/**
* @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);
event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true
/*Functions*/
/**
* @dev Helps initialize a dispute by assigning it a disputeId
* when a miner returns a false on the validate array(in Tellor.ProofOfWork) it sends the
* invalidated value information to POS voting
* @param _requestId being disputed
* @param _timestamp being disputed
* @param _minerIndex the index of the miner that submitted the value being disputed. Since each official value
* requires 5 miners to submit a value.
*/
function beginDispute(TellorStorage.TellorStorageStruct storage self, 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));
//Ensures that a dispute is not already open for the that miner, requestId and timestamp
require(self.disputeIdByDisputeHash[_hash] == 0, "Dispute is already open");
TellorTransfer.doTransfer(self, msg.sender, address(this), self.uintVars[keccak256("disputeFee")]);
//Increase the dispute count by 1
self.uintVars[keccak256("disputeCount")] = self.uintVars[keccak256("disputeCount")] + 1;
//Sets the new disputeCount as the disputeId
uint256 disputeId = self.uintVars[keccak256("disputeCount")];
//maps the dispute hash to the disputeId
self.disputeIdByDisputeHash[_hash] = disputeId;
//maps the dispute to the Dispute struct
self.disputesById[disputeId] = TellorStorage.Dispute({
hash: _hash,
isPropFork: false,
reportedMiner: _miner,
reportingParty: msg.sender,
proposedForkAddress: address(0),
executed: false,
disputeVotePassed: false,
tally: 0
});
//Saves all the dispute variables for the disputeId
self.disputesById[disputeId].disputeUintVars[keccak256("requestId")] = _requestId;
self.disputesById[disputeId].disputeUintVars[keccak256("timestamp")] = _timestamp;
self.disputesById[disputeId].disputeUintVars[keccak256("value")] = _request.valuesByTimestamp[_timestamp][_minerIndex];
self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days;
self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number;
self.disputesById[disputeId].disputeUintVars[keccak256("minerSlot")] = _minerIndex;
self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")];
//Values are sorted as they come in and the official value is the median of the first five
//So the "official value" miner is always minerIndex==2. If the official value is being
//disputed, it sets its status to inDispute(currentStatus = 3) so that users are made aware it is under dispute
if (_minerIndex == 2) {
self.requestDetails[_requestId].inDispute[_timestamp] = true;
}
self.stakerDetails[_miner].currentStatus = 3;
emit NewDispute(disputeId, _requestId, _timestamp, _miner);
}
/**
* @dev Allows token holders to vote
* @param _disputeId is the dispute id
* @param _supportsDispute is the vote (true=the dispute has basis false = vote against dispute)
*/
function vote(TellorStorage.TellorStorageStruct storage self, 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
uint256 voteWeight = TellorTransfer.balanceOfAt(self, 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;
//Update the quorum by adding the voteWeight
disp.disputeUintVars[keccak256("quorum")] += voteWeight;
//If the user supports the dispute increase the tally for the dispute by the voteWeight
//otherwise decrease it
if (_supportsDispute) {
disp.tally = disp.tally.add(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];
TellorStorage.Request storage _request = self.requestDetails[disp.disputeUintVars[keccak256("requestId")]];
//Ensure this has not already been executed/tallied
require(disp.executed == false, "Dispute has been already executed");
//Ensure the time for voting has elapsed
require(now > disp.disputeUintVars[keccak256("minExecutionDate")], "Time for voting haven't elapsed");
//If the vote is not a proposed fork
if (disp.isPropFork == false) {
TellorStorage.StakeInfo storage stakes = self.stakerDetails[disp.reportedMiner];
//If the vote for disputing a value is succesful(disp.tally >0) then unstake the reported
// miner and transfer the stakeAmount and dispute fee to the reporting party
if (disp.tally > 0) {
//if reported miner stake has not been slashed yet, slash them and return the fee to reporting party
if (stakes.currentStatus == 3) {
//Changing the currentStatus and startDate unstakes the reported miner and allows for the
//transfer of the stakeAmount
stakes.currentStatus = 0;
stakes.startDate = now - (now % 86400);
//Decreases the stakerCount since the miner's stake is being slashed
self.uintVars[keccak256("stakerCount")]--;
updateDisputeFee(self);
//Transfers the StakeAmount from the reporded miner to the reporting party
TellorTransfer.doTransfer(self, disp.reportedMiner, disp.reportingParty, self.uintVars[keccak256("stakeAmount")]);
//Returns the dispute fee to the reportingParty
TellorTransfer.doTransfer(self, address(this), disp.reportingParty, disp.disputeUintVars[keccak256("fee")]);
//if reported miner stake was already slashed, return the fee to other reporting paties
} else{
TellorTransfer.doTransfer(self, address(this), disp.reportingParty, disp.disputeUintVars[keccak256("fee")]);
}
//Set the dispute state to passed/true
disp.disputeVotePassed = true;
//If the dispute was succeful(miner found guilty) then update the timestamp value to zero
//so that users don't use this datapoint
if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) {
_request.finalValues[disp.disputeUintVars[keccak256("timestamp")]] = 0;
}
//If the vote for disputing a value is unsuccesful then update the miner status from being on
//dispute(currentStatus=3) to staked(currentStatus =1) and tranfer the dispute fee to the miner
} else {
//Update the miner's current status to staked(currentStatus = 1)
stakes.currentStatus = 1;
//tranfer the dispute fee to the miner
TellorTransfer.doTransfer(self, address(this), disp.reportedMiner, disp.disputeUintVars[keccak256("fee")]);
if (_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] == true) {
_request.inDispute[disp.disputeUintVars[keccak256("timestamp")]] = false;
}
}
//If the vote is for a proposed fork require a 20% quorum before executing the update to the new tellor contract address
} else {
if (disp.tally > 0) {
require(
disp.disputeUintVars[keccak256("quorum")] > ((self.uintVars[keccak256("total_supply")] * 20) / 100),
"Quorum is not reached"
);
self.addressVars[keccak256("tellorContract")] = disp.proposedForkAddress;
disp.disputeVotePassed = true;
emit NewTellorAddress(disp.proposedForkAddress);
}
}
//update the dispute status to executed
disp.executed = true;
emit DisputeVoteTallied(_disputeId, disp.tally, disp.reportedMiner, disp.reportingParty, disp.disputeVotePassed);
}
/**
* @dev Allows for a fork to be proposed
* @param _propNewTellorAddress address for new proposed Tellor
*/
function proposeFork(TellorStorage.TellorStorageStruct storage self, address _propNewTellorAddress) public {
bytes32 _hash = keccak256(abi.encodePacked(_propNewTellorAddress));
require(self.disputeIdByDisputeHash[_hash] == 0, "");
TellorTransfer.doTransfer(self, msg.sender, address(this), self.uintVars[keccak256("disputeFee")]); //This is the fork fee
self.uintVars[keccak256("disputeCount")]++;
uint256 disputeId = self.uintVars[keccak256("disputeCount")];
self.disputeIdByDisputeHash[_hash] = disputeId;
self.disputesById[disputeId] = TellorStorage.Dispute({
hash: _hash,
isPropFork: true,
reportedMiner: msg.sender,
reportingParty: msg.sender,
proposedForkAddress: _propNewTellorAddress,
executed: false,
disputeVotePassed: false,
tally: 0
});
self.disputesById[disputeId].disputeUintVars[keccak256("blockNumber")] = block.number;
self.disputesById[disputeId].disputeUintVars[keccak256("fee")] = self.uintVars[keccak256("disputeFee")];
self.disputesById[disputeId].disputeUintVars[keccak256("minExecutionDate")] = now + 7 days;
}
/**
* @dev this function allows the dispute fee to fluctuate based on the number of miners on the system.
* The floor for the fee is 15e18.
*/
function updateDisputeFee(TellorStorage.TellorStorageStruct storage self) public {
//if the number of staked miners divided by the target count of staked miners is less than 1
if ((self.uintVars[keccak256("stakerCount")] * 1000) / self.uintVars[keccak256("targetMiners")] < 1000) {
//Set the dispute fee at stakeAmt * (1- stakerCount/targetMiners)
//or at the its minimum of 15e18
self.uintVars[keccak256("disputeFee")] = SafeMath.max(
15e18,
self.uintVars[keccak256("stakeAmount")].mul(
1000 - (self.uintVars[keccak256("stakerCount")] * 1000) / self.uintVars[keccak256("targetMiners")]
) /
1000
);
} else {
//otherwise set the dispute fee at 15e18 (the floor/minimum fee allowed)
self.uintVars[keccak256("disputeFee")] = 15e18;
}
}
}
/**
* itle Tellor Dispute
* @dev Contais the methods related to miners staking and unstaking. Tellor.sol
* references this library for function's logic.
*/
library TellorStake {
event NewStake(address indexed _sender); //Emits upon new staker
event StakeWithdrawn(address indexed _sender); //Emits when a staker is now no longer staked
event StakeWithdrawRequested(address indexed _sender); //Emits when a staker begins the 7 day withdraw period
/*Functions*/
/**
* @dev This function stakes the five initial miners, sets the supply and all the constant variables.
* This function is called by the constructor function on TellorMaster.sol
*/
function init(TellorStorage.TellorStorageStruct storage self) public {
require(self.uintVars[keccak256("decimals")] == 0, "Too many decimals");
//Give this contract 6000 Tellor Tributes so that it can stake the initial 6 miners
TellorTransfer.updateBalanceAtNow(self.balances[address(this)], 2**256 - 1 - 6000e18);
// //the initial 5 miner addresses are specfied below
// //changed payable[5] to 6
address payable[6] memory _initalMiners = [
address(0xE037EC8EC9ec423826750853899394dE7F024fee),
address(0xcdd8FA31AF8475574B8909F135d510579a8087d3),
address(0xb9dD5AfD86547Df817DA2d0Fb89334A6F8eDd891),
address(0x230570cD052f40E14C14a81038c6f3aa685d712B),
address(0x3233afA02644CCd048587F8ba6e99b3C00A34DcC),
address(0xe010aC6e0248790e08F42d5F697160DEDf97E024)
];
//Stake each of the 5 miners specified above
for (uint256 i = 0; i < 6; i++) {
//6th miner to allow for dispute
//Miner balance is set at 1000e18 at the block that this function is ran
TellorTransfer.updateBalanceAtNow(self.balances[_initalMiners[i]], 1000e18);
newStake(self, _initalMiners[i]);
}
//update the total suppply
self.uintVars[keccak256("total_supply")] += 6000e18; //6th miner to allow for dispute
//set Constants
self.uintVars[keccak256("decimals")] = 18;
self.uintVars[keccak256("targetMiners")] = 200;
self.uintVars[keccak256("stakeAmount")] = 1000e18;
self.uintVars[keccak256("disputeFee")] = 970e18;
self.uintVars[keccak256("timeTarget")] = 600;
self.uintVars[keccak256("timeOfLastNewValue")] = now - (now % self.uintVars[keccak256("timeTarget")]);
self.uintVars[keccak256("difficulty")] = 1;
}
/**
* @dev This function allows stakers to request to withdraw their stake (no longer stake)
* once they lock for withdraw(stakes.currentStatus = 2) they are locked for 7 days before they
* can withdraw the deposit
*/
function requestStakingWithdraw(TellorStorage.TellorStorageStruct storage self) public {
TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender];
//Require that the miner is staked
require(stakes.currentStatus == 1, "Miner is not staked");
//Change the miner staked to locked to be withdrawStake
stakes.currentStatus = 2;
//Change the startDate to now since the lock up period begins now
//and the miner can only withdraw 7 days later from now(check the withdraw function)
stakes.startDate = now - (now % 86400);
//Reduce the staker count
self.uintVars[keccak256("stakerCount")] -= 1;
TellorDispute.updateDisputeFee(self);
emit StakeWithdrawRequested(msg.sender);
}
/**
* @dev This function allows users to withdraw their stake after a 7 day waiting period from request
*/
function withdrawStake(TellorStorage.TellorStorageStruct storage self) public {
TellorStorage.StakeInfo storage stakes = self.stakerDetails[msg.sender];
//Require the staker has locked for withdraw(currentStatus ==2) and that 7 days have
//passed by since they locked for withdraw
require(now - (now % 86400) - stakes.startDate >= 7 days, "7 days didn't pass");
require(stakes.currentStatus == 2, "Miner was not locked for withdrawal");
stakes.currentStatus = 0;
emit StakeWithdrawn(msg.sender);
}
/**
* @dev This function allows miners to deposit their stake.
*/
function depositStake(TellorStorage.TellorStorageStruct storage self) public {
newStake(self, msg.sender);
//self adjusting disputeFee
TellorDispute.updateDisputeFee(self);
}
/**
* @dev This function is used by the init function to succesfully stake the initial 5 miners.
* The function updates their status/state and status start date so they are locked it so they can't withdraw
* and updates the number of stakers in the system.
*/
function newStake(TellorStorage.TellorStorageStruct storage self, address staker) internal {
require(TellorTransfer.balanceOf(self, staker) >= self.uintVars[keccak256("stakeAmount")], "Balance is lower than stake 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[staker].currentStatus == 0 || self.stakerDetails[staker].currentStatus == 2, "Miner is in the wrong state");
self.uintVars[keccak256("stakerCount")] += 1;
self.stakerDetails[staker] = TellorStorage.StakeInfo({
currentStatus: 1, //this resets their stake start date to today
startDate: now - (now % 86400)
});
emit NewStake(staker);
}
}
//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?
bool isPropFork; //true for fork proposal NEW
address reportedMiner; //miner who alledgedly submitted the 'bad value' will get disputeFee if dispute vote fails
address reportingParty; //miner reporting the 'bad value'-pay disputeFee will get reportedMiner's stake if dispute vote passes
address proposedForkAddress; //new fork address (if fork proposal)
mapping(bytes32 => 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
}
//Internal struct to allow balances to be queried by blocknumber for voting purposes
struct Checkpoint {
uint128 fromBlock; // fromBlock is the block number that the value was generated from
uint128 value; // value is the amount of tokens at a specific block number
}
struct Request {
string queryString; //id to string api
string dataSymbol; //short name for api request
bytes32 queryHash; //hash of api string and granularity e.g. keccak256(abi.encodePacked(_sapi,_granularity))
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("granularity"); //multiplier for miners
// 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 {
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("_owner");//Tellor Owner 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)
//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) requestIdByQueryHash; // api bytes32 gets an id = to count of requests array
mapping(bytes32 => uint256) disputeIdByDisputeHash; //maps a hash to an ID for each dispute
}
}
//Functions for retrieving min and Max in 51 length array (requestQ)
//Taken partly from: https://github.com/modular-network/ethereum-libraries-array-utils/blob/master/contracts/Array256Lib.sol
library Utilities {
/**
* @dev Returns the minimum value in an array.
*/
function getMax(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;
event NewTellorAddress(address _newTellor); //emmited when a proposed fork is voted true
/*Functions*/
//The next two functions are onlyOwner functions. For Tellor to be truly decentralized, we will need to transfer the Deity to the 0 address.
//Only needs to be in library
/**
* @dev This function allows us to set a new Deity (or remove it)
* @param _newDeity address of the new Deity of the tellor system
*/
function changeDeity(TellorStorage.TellorStorageStruct storage self, address _newDeity) internal {
require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity");
self.addressVars[keccak256("_deity")] = _newDeity;
}
//Only needs to be in library
/**
* @dev This function allows the deity to upgrade the Tellor System
* @param _tellorContract address of new updated TellorCore contract
*/
function changeTellorContract(TellorStorage.TellorStorageStruct storage self, address _tellorContract) internal {
require(self.addressVars[keccak256("_deity")] == msg.sender, "Sender is not deity");
self.addressVars[keccak256("tellorContract")] = _tellorContract;
emit NewTellorAddress(_tellorContract);
}
/*Tellor Getters*/
/**
* @dev This function tells you if a given challenge has been completed by a given miner
* @param _challenge the challenge to search for
* @param _miner address that you want to know if they solved the challenge
* @return true if the _miner address provided solved the
*/
function didMine(TellorStorage.TellorStorageStruct storage self, bytes32 _challenge, address _miner) internal view returns (bool) {
return self.minersByChallenge[_challenge][_miner];
}
/**
* @dev Checks if an address voted in a dispute
* @param _disputeId to look up
* @param _address of voting party to look up
* @return bool of whether or not party voted
*/
function didVote(TellorStorage.TellorStorageStruct storage self, 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 bool isPropFork true if the dispute is a proposed fork
* @return address of reportedMiner
* @return address of reportingParty
* @return address of proposedForkAddress
* @return uint of requestId
* @return uint of timestamp
* @return uint of value
* @return uint of minExecutionDate
* @return uint of numberOfVotes
* @return uint of blocknumber
* @return uint of minerSlot
* @return uint of quorum
* @return uint of fee
* @return int count of the current tally
*/
function getAllDisputeVars(TellorStorage.TellorStorageStruct storage self, uint256 _disputeId)
internal
view
returns (bytes32, bool, bool, bool, address, address, address, uint256[9] memory, int256)
{
TellorStorage.Dispute storage disp = self.disputesById[_disputeId];
return (
disp.hash,
disp.executed,
disp.disputeVotePassed,
disp.isPropFork,
disp.reportedMiner,
disp.reportingParty,
disp.proposedForkAddress,
[
disp.disputeUintVars[keccak256("requestId")],
disp.disputeUintVars[keccak256("timestamp")],
disp.disputeUintVars[keccak256("value")],
disp.disputeUintVars[keccak256("minExecutionDate")],
disp.disputeUintVars[keccak256("numberOfVotes")],
disp.disputeUintVars[keccak256("blockNumber")],
disp.disputeUintVars[keccak256("minerSlot")],
disp.disputeUintVars[keccak256("quorum")],
disp.disputeUintVars[keccak256("fee")]
],
disp.tally
);
}
/**
* @dev Getter function for variables for the requestId being currently mined(currentRequestId)
* @return current challenge, curretnRequestId, level of difficulty, api/query string, and granularity(number of decimals requested), total tip for the request
*/
function getCurrentVariables(TellorStorage.TellorStorageStruct storage self)
internal
view
returns (bytes32, uint256, uint256, string memory, uint256, uint256)
{
return (
self.currentChallenge,
self.uintVars[keccak256("currentRequestId")],
self.uintVars[keccak256("difficulty")],
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("totalTip")]
);
}
/**
* @dev Checks if a given hash of miner,requestId has been disputed
* @param _hash is the sha256(abi.encodePacked(_miners[2],_requestId));
* @return uint disputeId
*/
function getDisputeIdByDisputeHash(TellorStorage.TellorStorageStruct storage self, bytes32 _hash) internal view returns (uint256) {
return self.disputeIdByDisputeHash[_hash];
}
/**
* @dev Checks for uint variables in the disputeUintVars mapping based on the disuputeId
* @param _disputeId is the dispute id;
* @param _data the variable to pull from the mapping. _data = keccak256("variable_name") where variable_name is
* the variables/strings used to save the data in the mapping. The variables names are
* commented out under the disputeUintVars under the Dispute struct
* @return uint value for the bytes32 data submitted
*/
function getDisputeUintVars(TellorStorage.TellorStorageStruct storage self, 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 Get the name of the token
* @return string of the token name
*/
function getName(TellorStorage.TellorStorageStruct storage self) internal pure returns (string memory) {
return "Tellor Tributes";
}
/**
* @dev Counts the number of values that have been submited for the request
* if called for the currentRequest being mined it can tell you how many miners have submitted a value for that
* request so far
* @param _requestId the requestId to look up
* @return uint count of the number of values received for the requestId
*/
function getNewValueCountbyRequestId(TellorStorage.TellorStorageStruct storage self, 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 requestId based on the qeuaryHash
* @param _queryHash hash(of string api and granularity) to check if a request already exists
* @return uint requestId
*/
function getRequestIdByQueryHash(TellorStorage.TellorStorageStruct storage self, bytes32 _queryHash) internal view returns (uint256) {
return self.requestIdByQueryHash[_queryHash];
}
/**
* @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 string of api to query
* @return string of symbol of api to query
* @return bytes32 hash of string
* @return bytes32 of the granularity(decimal places) requested
* @return uint of index in requestQ array
* @return uint of current payout/tip for this requestId
*/
function getRequestVars(TellorStorage.TellorStorageStruct storage self, uint256 _requestId)
internal
view
returns (string memory, string memory, bytes32, uint256, uint256, uint256)
{
TellorStorage.Request storage _request = self.requestDetails[_requestId];
return (
_request.queryString,
_request.dataSymbol,
_request.queryHash,
_request.apiUintVars[keccak256("granularity")],
_request.apiUintVars[keccak256("requestQPosition")],
_request.apiUintVars[keccak256("totalTip")]
);
}
/**
* @dev This function allows users to retireve all information about a staker
* @param _staker address of staker inquiring about
* @return uint current state of staker
* @return uint startDate of staking
*/
function getStakerInfo(TellorStorage.TellorStorageStruct storage self, address _staker) internal view returns (uint256, uint256) {
return (self.stakerDetails[_staker].currentStatus, self.stakerDetails[_staker].startDate);
}
/**
* @dev Gets the 5 miners who mined the value for the specified requestId/_timestamp
* @param _requestId to look up
* @param _timestamp is the timestampt to look up miners for
* @return address[5] array of 5 addresses ofminers that mined the requestId
*/
function getSubmissionsByTimestamp(TellorStorage.TellorStorageStruct storage self, uint256 _requestId, uint256 _timestamp)
internal
view
returns (uint256[5] memory)
{
return self.requestDetails[_requestId].valuesByTimestamp[_timestamp];
}
/**
* @dev Get the symbol of the token
* @return string of the token symbol
*/
function getSymbol(TellorStorage.TellorStorageStruct storage self) internal pure returns (string memory) {
return "TT";
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _requestID is the requestId to look up
* @param _index is the value index to look up
* @return uint timestamp
*/
function getTimestampbyRequestIDandIndex(TellorStorage.TellorStorageStruct storage self, 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, and API query string
*/
function getVariablesOnDeck(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256, uint256, string memory) {
uint256 newRequestId = getTopRequestID(self);
return (
newRequestId,
self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")],
self.requestDetails[newRequestId].queryString
);
}
/**
* @dev Getter function for the request with highest payout. This function is used within the getVariablesOnDeck function
* @return uint _requestId of request with highest payout at the time the function is called
*/
function getTopRequestID(TellorStorage.TellorStorageStruct storage self) internal view returns (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];
}
/**
* @dev Getter for the total_supply of oracle tokens
* @return uint total supply
*/
function totalSupply(TellorStorage.TellorStorageStruct storage self) internal view returns (uint256) {
return self.uintVars[keccak256("total_supply")];
}
}
/**
* @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;
event TipAdded(address indexed _sender, uint256 indexed _requestId, uint256 _tip, uint256 _totalTips);
//Emits upon someone adding value to a pool; msg.sender, amount added, and timestamp incentivized to be mined
event DataRequested(
address indexed _sender,
string _query,
string _querySymbol,
uint256 _granularity,
uint256 indexed _requestId,
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 _currentChallenge,
uint256 indexed _currentRequestId,
uint256 _difficulty,
uint256 _multiplier,
string _query,
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, string _query, bytes32 _onDeckQueryHash, 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, nonce, and value submitted
event NonceSubmitted(address indexed _miner, string _nonce, uint256 indexed _requestId, uint256 _value, bytes32 _currentChallenge);
event OwnershipTransferred(address indexed _previousOwner, address indexed _newOwner);
event OwnershipProposed(address indexed _previousOwner, address indexed _newOwner);
/*Functions*/
/*This is a cheat for demo purposes, will delete upon actual launch*/
/*function theLazyCoon(TellorStorage.TellorStorageStruct storage self,address _address, uint _amount) public {
self.uintVars[keccak256("total_supply")] += _amount;
TellorTransfer.updateBalanceAtNow(self.balances[_address],_amount);
} */
/**
* @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");
//If the tip > 0 transfer the tip to this contract
if (_tip > 0) {
TellorTransfer.doTransfer(self, 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 Request to retreive value from oracle based on timestamp. The tip is not required to be
* greater than 0 because there are no tokens in circulation for the initial(genesis) request
* @param _c_sapi string API being requested be mined
* @param _c_symbol is the short string symbol for the api request
* @param _granularity is the number of decimals miners should include on the submitted value
* @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 requestData(
TellorStorage.TellorStorageStruct storage self,
string memory _c_sapi,
string memory _c_symbol,
uint256 _granularity,
uint256 _tip
) public {
//Require at least one decimal place
require(_granularity > 0, "Too few decimal places");
//But no more than 18 decimal places
require(_granularity <= 1e18, "Too many decimal places");
//If it has been requested before then add the tip to it otherwise create the queryHash for it
string memory _sapi = _c_sapi;
string memory _symbol = _c_symbol;
require(bytes(_sapi).length > 0, "API string length is 0");
require(bytes(_symbol).length < 64, "API string symbol is greater than 64");
bytes32 _queryHash = keccak256(abi.encodePacked(_sapi, _granularity));
//If this is the first time the API and granularity combination has been requested then create the API and granularity hash
//otherwise the tip will be added to the requestId submitted
if (self.requestIdByQueryHash[_queryHash] == 0) {
self.uintVars[keccak256("requestCount")]++;
uint256 _requestId = self.uintVars[keccak256("requestCount")];
self.requestDetails[_requestId] = TellorStorage.Request({
queryString: _sapi,
dataSymbol: _symbol,
queryHash: _queryHash,
requestTimestamps: new uint256[](0)
});
self.requestDetails[_requestId].apiUintVars[keccak256("granularity")] = _granularity;
self.requestDetails[_requestId].apiUintVars[keccak256("requestQPosition")] = 0;
self.requestDetails[_requestId].apiUintVars[keccak256("totalTip")] = 0;
self.requestIdByQueryHash[_queryHash] = _requestId;
//If the tip > 0 it tranfers the tip to this contract
if (_tip > 0) {
TellorTransfer.doTransfer(self, msg.sender, address(this), _tip);
}
updateOnDeck(self, _requestId, _tip);
emit DataRequested(
msg.sender,
self.requestDetails[_requestId].queryString,
self.requestDetails[_requestId].dataSymbol,
_granularity,
_requestId,
_tip
);
//Add tip to existing request id since this is not the first time the api and granularity have been requested
} else {
addTip(self, self.requestIdByQueryHash[_queryHash], _tip);
}
}
/**
* @dev This fucntion 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 _nonce or solution for the PoW for the requestId
* @param _requestId for the current request being mined
*/
function newBlock(TellorStorage.TellorStorageStruct storage self, string memory _nonce, uint256 _requestId) internal {
TellorStorage.Request storage _request = self.requestDetails[_requestId];
// If the difference between the timeTarget and how long it takes to solve the challenge this updates the challenge
//difficulty up or donw by the difference between the target time and how long it took to solve the prevous challenge
//otherwise it sets it to 1
int256 _change = int256(SafeMath.min(1200, (now - self.uintVars[keccak256("timeOfLastNewValue")])));
_change = (int256(self.uintVars[keccak256("difficulty")]) * (int256(self.uintVars[keccak256("timeTarget")]) - _change)) / 4000;
if (_change < 2 && _change > -2) {
if (_change >= 0) {
_change = 1;
} else {
_change = -1;
}
}
if ((int256(self.uintVars[keccak256("difficulty")]) + _change) <= 0) {
self.uintVars[keccak256("difficulty")] = 1;
} else {
self.uintVars[keccak256("difficulty")] = uint256(int256(self.uintVars[keccak256("difficulty")]) + _change);
}
//Sets time of value submission rounded to 1 minute
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++) {
TellorTransfer.doTransfer(self, address(this), a[i].miner, 5e18 + self.uintVars[keccak256("currentTotalTips")] / 5);
}
emit NewValue(
_requestId,
_timeOfLastNewValue,
a[2].value,
self.uintVars[keccak256("currentTotalTips")] - (self.uintVars[keccak256("currentTotalTips")] % 5),
self.currentChallenge
);
//update the total supply
self.uintVars[keccak256("total_supply")] += 275e17;
//pay the dev-share
TellorTransfer.doTransfer(self, address(this), self.addressVars[keccak256("_owner")], 25e17); //The ten there is the devshare
//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) {
//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 challenge
self.currentChallenge = keccak256(abi.encodePacked(_nonce, self.currentChallenge, blockhash(block.number - 1))); // Save hash for next proof
emit NewChallenge(
self.currentChallenge,
_topId,
self.uintVars[keccak256("difficulty")],
self.requestDetails[_topId].apiUintVars[keccak256("granularity")],
self.requestDetails[_topId].queryString,
self.uintVars[keccak256("currentTotalTips")]
);
emit NewRequestOnDeck(
newRequestId,
self.requestDetails[newRequestId].queryString,
self.requestDetails[newRequestId].queryHash,
self.requestDetails[newRequestId].apiUintVars[keccak256("totalTip")]
);
} else {
self.uintVars[keccak256("currentTotalTips")] = 0;
self.currentChallenge = "";
}
}
/**
* @dev Proof of work is called by the miner when they submit the 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(TellorStorage.TellorStorageStruct storage self, string memory _nonce, 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");
//Saving the challenge information as unique by using the msg.sender
require(
uint256(
sha256(abi.encodePacked(ripemd160(abi.encodePacked(keccak256(abi.encodePacked(self.currentChallenge, msg.sender, _nonce))))))
) %
self.uintVars[keccak256("difficulty")] ==
0,
"Challenge information is not saved"
);
//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 NonceSubmitted(msg.sender, _nonce, _requestId, _value, self.currentChallenge);
//If 5 values have been received, adjust the difficulty otherwise sort the values until 5 are received
if (self.uintVars[keccak256("slotProgress")] == 5) {
newBlock(self, _nonce, _requestId);
}
}
/**
* @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(TellorStorage.TellorStorageStruct storage self, address payable _pendingOwner) internal {
require(msg.sender == self.addressVars[keccak256("_owner")], "Sender is not owner");
emit OwnershipProposed(self.addressVars[keccak256("_owner")], _pendingOwner);
self.addressVars[keccak256("pending_owner")] = _pendingOwner;
}
/**
* @dev Allows the new owner to claim control of the contract
*/
function claimOwnership(TellorStorage.TellorStorageStruct storage self) internal {
require(msg.sender == self.addressVars[keccak256("pending_owner")], "Sender is not pending owner");
emit OwnershipTransferred(self.addressVars[keccak256("_owner")], self.addressVars[keccak256("pending_owner")]);
self.addressVars[keccak256("_owner")] = self.addressVars[keccak256("pending_owner")];
}
/**
* @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);
//If the tip >0 update the tip for the requestId
if (_tip > 0) {
_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) {
_request.apiUintVars[keccak256("totalTip")] = 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
emit NewChallenge(
self.currentChallenge,
self.uintVars[keccak256("currentRequestId")],
self.uintVars[keccak256("difficulty")],
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].apiUintVars[keccak256("granularity")],
self.requestDetails[self.uintVars[keccak256("currentRequestId")]].queryString,
self.uintVars[keccak256("currentTotalTips")]
);
} 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")] || (onDeckRequestId == 0)) {
//let everyone know the next on queue has been replaced
emit NewRequestOnDeck(_requestId, _request.queryString, _request.queryHash, _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 || _min == 0) {
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 if (_tip > 0) {
self.requestQ[_request.apiUintVars[keccak256("requestQPosition")]] += _tip;
}
}
}
}
/**
* @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 {
using SafeMath for uint256;
using TellorDispute for TellorStorage.TellorStorageStruct;
using TellorLibrary for TellorStorage.TellorStorageStruct;
using TellorStake for TellorStorage.TellorStorageStruct;
using TellorTransfer for TellorStorage.TellorStorageStruct;
TellorStorage.TellorStorageStruct tellor;
/*Functions*/
/*This is a cheat for demo purposes, will delete upon actual launch*/
/*function theLazyCoon(address _address, uint _amount) public {
tellor.theLazyCoon(_address,_amount);
}*/
/**
* @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 Allows for a fork to be proposed
* @param _propNewTellorAddress address for new proposed Tellor
*/
function proposeFork(address _propNewTellorAddress) external {
tellor.proposeFork(_propNewTellorAddress);
}
/**
* @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 Request to retreive value from oracle based on timestamp. The tip is not required to be
* greater than 0 because there are no tokens in circulation for the initial(genesis) request
* @param _c_sapi string API being requested be mined
* @param _c_symbol is the short string symbol for the api request
* @param _granularity is the number of decimals miners should include on the submitted value
* @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 requestData(string calldata _c_sapi, string calldata _c_symbol, uint256 _granularity, uint256 _tip) external {
tellor.requestData(_c_sapi, _c_symbol, _granularity, _tip);
}
/**
* @dev Proof of work is called by the miner when they submit the 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 {
tellor.submitMiningSolution(_nonce, _requestId, _value);
}
/**
* @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 {
tellor.proposeOwnership(_pendingOwner);
}
/**
* @dev Allows the new owner to claim control of the contract
*/
function claimOwnership() external {
tellor.claimOwnership();
}
/**
* @dev This function allows miners to deposit their stake.
*/
function depositStake() external {
tellor.depositStake();
}
/**
* @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 {
tellor.requestStakingWithdraw();
}
/**
* @dev This function allows users to withdraw their stake after a 7 day waiting period from request
*/
function withdrawStake() external {
tellor.withdrawStake();
}
/**
* @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) {
return tellor.approve(_spender, _amount);
}
/**
* @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) {
return tellor.transfer(_to, _amount);
}
/**
* @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) {
return tellor.transferFrom(_from, _to, _amount);
}
/**
* @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 the a value for the latest timestamp available _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);
return (0, false);
}
}
| 12,861,460 |
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint a, uint b) internal pure returns (uint) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20 {
/// @return total amount of tokens
uint public totalSupply;
/// @param _owner The address from which the balance will be retrieved
/// @return The balance
function balanceOf(address _owner) public constant returns (uint balance);
/// @notice 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 Whether the transfer was successful or not
function transfer(address _to, uint _value) public returns (bool success);
/// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from`
/// @param _from The address of the sender
/// @param _to The address of the recipient
/// @param _value The amount of token to be transferred
/// @return Whether the transfer was successful or not
function transferFrom(address _from, address _to, uint _value) public returns (bool success);
/// @notice `msg.sender` approves `_addr` 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 Whether the approval was successful or not
function approve(address _spender, uint _value) public returns (bool success);
/// @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) public view returns (uint remaining);
event Transfer(address indexed _from, address indexed _to, uint _value);
event Approval(address indexed _owner, address indexed _spender, uint _value);
}
contract BDToken is ERC20 {
using SafeMath for uint;
uint constant private MAX_UINT256 = 2**256 - 1;
uint8 constant public decimals = 18;
string public name;
string public symbol;
address public owner;
// True if transfers are allowed
bool public transferable = true;
/* This creates an array with all balances */
mapping (address => uint) freezes;
mapping (address => uint) balances;
mapping (address => mapping (address => uint)) allowed;
modifier onlyOwner {
require(msg.sender == owner);//"Only owner can call this function."
_;
}
modifier canTransfer() {
require(transferable == true);
_;
}
/* This notifies clients about the amount burnt */
event Burn(address indexed from, uint value);
/* This notifies clients about the amount frozen */
event Freeze(address indexed from, uint value);
/* This notifies clients about the amount unfrozen */
event Unfreeze(address indexed from, uint value);
/* Initializes contract with initial supply tokens to the creator of the contract */
function BDToken() public {
totalSupply = 100*10**26; // Update total supply with the decimal amount
name = "BaoDe Token";
symbol = "BDT";
balances[msg.sender] = totalSupply; // Give the creator all initial tokens
owner = msg.sender;
emit Transfer(address(0), msg.sender, totalSupply);
}
/* Send coins */
function transfer(address _to, uint _value) public canTransfer returns (bool success) {
require(_to != address(0));// Prevent transfer to 0x0 address.
require(_value > 0);
require(balances[msg.sender] >= _value); // Check if the sender has enough
require(balances[_to] + _value >= balances[_to]); // Check for overflows
balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
emit Transfer(msg.sender, _to, _value); // Notify anyone listening that this transfer took place
return true;
}
/* A contract attempts to get the coins */
function transferFrom(address _from, address _to, uint _value) public canTransfer returns (bool success) {
uint allowance = allowed[_from][msg.sender];
require(_to != address(0));// Prevent transfer to 0x0 address.
require(_value > 0);
require(balances[_from] >= _value); // Check if the sender has enough
require(allowance >= _value); // Check allowance
require(balances[_to] + _value >= balances[_to]); // Check for overflows
balances[_from] = balances[_from].sub(_value); // Subtract from the sender
balances[_to] = balances[_to].add(_value); // Add the same to the recipient
if (allowance < MAX_UINT256) {
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
}
emit Transfer(_from, _to, _value);
return true;
}
/* Allow another contract to spend some tokens in your behalf */
function approve(address _spender, uint _value) public canTransfer returns (bool success) {
require(_value >= 0);
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
function balanceOf(address _owner) public view returns (uint balance) {
return balances[_owner];
}
function allowance(address _owner, address _spender) public view returns (uint remaining) {
return allowed[_owner][_spender];
}
function freezeOf(address _owner) public view returns (uint freeze) {
return freezes[_owner];
}
function burn(uint _value) public canTransfer returns (bool success) {
require(balances[msg.sender] >= _value); // Check if the sender has enough
require(_value > 0);
balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender
totalSupply = totalSupply.sub(_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
function freeze(uint _value) public canTransfer returns (bool success) {
require(balances[msg.sender] >= _value); // Check if the sender has enough
require(_value > 0);
require(freezes[msg.sender] + _value >= freezes[msg.sender]); // Check for overflows
balances[msg.sender] = balances[msg.sender].sub(_value); // Subtract from the sender
freezes[msg.sender] = freezes[msg.sender].add(_value);
emit Freeze(msg.sender, _value);
return true;
}
function unfreeze(uint _value) public canTransfer returns (bool success) {
require(freezes[msg.sender] >= _value); // Check if the sender has enough
require(_value > 0);
require(balances[msg.sender] + _value >= balances[msg.sender]); // Check for overflows
freezes[msg.sender] = freezes[msg.sender].sub(_value); // Subtract from the sender
balances[msg.sender] = balances[msg.sender].add(_value);
emit Unfreeze(msg.sender, _value);
return true;
}
/**
* @dev Transfer tokens to multiple addresses
* @param _addresses The addresses that will receieve tokens
* @param _amounts The quantity of tokens that will be transferred
* @return True if the tokens are transferred correctly
*/
function transferForMultiAddresses(address[] _addresses, uint[] _amounts) public canTransfer returns (bool) {
for (uint i = 0; i < _addresses.length; i++) {
require(_addresses[i] != address(0)); // Prevent transfer to 0x0 address.
require(_amounts[i] > 0);
require(balances[msg.sender] >= _amounts[i]); // Check if the sender has enough
require(balances[_addresses[i]] + _amounts[i] >= balances[_addresses[i]]); // Check for overflows
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_amounts[i]);
balances[_addresses[i]] = balances[_addresses[i]].add(_amounts[i]);
emit Transfer(msg.sender, _addresses[i], _amounts[i]);
}
return true;
}
function stop() public onlyOwner {
transferable = false;
}
function start() public onlyOwner {
transferable = true;
}
function transferOwnership(address newOwner) public onlyOwner {
owner = newOwner;
}
// transfer balance to owner
function withdrawEther(uint amount) public onlyOwner {
require(amount > 0);
owner.transfer(amount);
}
// can accept ether
function() public payable {
}
} | Initializes contract with initial supply tokens to the creator of the contract / | function BDToken() public {
name = "BaoDe Token";
symbol = "BDT";
owner = msg.sender;
emit Transfer(address(0), msg.sender, totalSupply);
}
| 479,425 |
//SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import { SafeMath } from "@openzeppelin/contracts/math/SafeMath.sol";
import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol";
import { DAI } from "./mock-tokens/DAI.sol";
import { WBTC } from "./mock-tokens/WBTC.sol";
// API3
import { ExampleClient } from "./ExampleClient.sol";
contract CDP is Ownable {
using SafeMath for uint;
uint currentLendId;
uint currentBorrowId;
// @notice - "Lend" also mean "Collateral" and "Deposit"
struct Lend { // Lend ID
uint daiAmountLended;
uint startBlock;
uint endBlock;
}
struct Borrow { // Borrow ID
uint lendId; // Because available borrowing amount is based on lending amount
uint wbtcAmountBorrowed;
uint startBlock;
uint endBlock;
}
mapping(address => mapping(uint => Lend)) lends; // User address -> Lend ID
mapping(address => mapping(uint => Borrow)) borrows; // User address -> Borrow ID
// Rate
uint interestRateForLending = 5; // APR: 5 (%) <- Calculated every block
uint interestRateForBorrowing = 10; // APR: 10 (%) <- Calculated every block
uint borrowLimitRate = 50; // APR: 50 (%) of collateral asset amount
DAI public dai;
WBTC public wbtc;
constructor(DAI _dai, WBTC _wbtc) public {
dai = _dai;
wbtc = _wbtc;
}
/**
* @notice - Fund WBTC for initial phase
*/
function fundWBTC(uint fundWBTCAmount) public onlyOwner returns (bool) {
wbtc.transferFrom(msg.sender, address(this), fundWBTCAmount);
}
/**
* @notice - Lend DAI as a collateral
*/
function lendDAI(uint daiAmount) public returns (bool) {
dai.transferFrom(msg.sender, address(this), daiAmount);
_lend(daiAmount);
}
/**
* @notice - A user can borrow WBTC until 50% of collateralized-DAI amount
* @notice - BTC price is retrieved via API3 oracle
* @param btcPrice - BTC/USD price that is retrieved via API3 oracle. (eg. bitcoin price is 35548 USD)
*/
function borrowWBTC(uint lendId, uint btcPrice, uint borrowWBTCAmount) public returns (bool) {
address borrower = msg.sender;
Lend memory lend = lends[borrower][lendId];
uint daiAmountLended = lend.daiAmountLended; // Collateralized-amount
uint borrowLimit = daiAmountLended.div(btcPrice).mul(borrowLimitRate).div(100);
require(borrowWBTCAmount <= borrowLimit, "WBTC amount borrowing must be less that the limit amount borrowing");
wbtc.transfer(borrower, borrowWBTCAmount);
_borrow(lendId, borrowWBTCAmount);
}
function repayWBTC(uint borrowId, uint repaymentAmount) public returns (bool) {
// Execute repayment
wbtc.transferFrom(msg.sender, address(this), repaymentAmount);
// Save repayment
_repay(borrowId);
// Calculate interest amount of borrowing by every block
address borrower = msg.sender;
Borrow memory borrow = borrows[borrower][borrowId];
uint wbtcAmountBorrowed = borrow.wbtcAmountBorrowed; // Principle
uint startBlock = borrow.startBlock;
uint endBlock = borrow.endBlock;
uint OneYearAsSecond = 1 days * 365;
uint interestRateForBorrowingPerSecond = interestRateForBorrowing.div(OneYearAsSecond);
uint interestRateForBorrowingPerBlock = interestRateForBorrowingPerSecond.mul(15); // [Note]: 1 block == 15 seconds
uint interestAmountForBorrowing = wbtcAmountBorrowed.mul(interestRateForBorrowingPerBlock).div(100).mul(endBlock.sub(startBlock));
// Update a WBTC amount that msg.sender must repay
_updateRepaymentAmount(borrowId, repaymentAmount, interestAmountForBorrowing);
}
function withdrawDAI(uint lendId, uint withdrawalAmount) public returns (bool) {
_withdraw(lendId);
// Calculate earned-interests amount of lending by every block
address lender = msg.sender;
Lend memory lend = lends[lender][lendId];
uint daiAmountLended = lend.daiAmountLended; // Principle
uint startBlock = lend.startBlock;
uint endBlock = lend.endBlock;
uint OneYearAsSecond = 1 days * 365;
uint interestRateForLendingPerSecond = interestRateForLending.div(OneYearAsSecond);
uint interestRateForLendingPerBlock = interestRateForLendingPerSecond.mul(15); // [Note]: 1 block == 15 seconds
uint interestAmountForLending = daiAmountLended.mul(interestRateForLendingPerBlock).div(100).mul(endBlock.sub(startBlock));
// Update a DAI amount that msg.sender lended
_updateWithdrawalAmount(lendId, withdrawalAmount, interestAmountForLending);
}
//------------------
// Internal methods
//------------------
function _lend(uint daiAmountLended) public returns (bool) {
currentLendId++;
Lend storage lend = lends[msg.sender][currentLendId];
lend.daiAmountLended = daiAmountLended;
lend.startBlock = block.number;
}
function _borrow(uint lendId, uint wbtcAmountBorrowed) public returns (bool) {
currentBorrowId++;
Borrow storage borrow = borrows[msg.sender][currentBorrowId];
borrow.lendId = lendId;
borrow.wbtcAmountBorrowed = wbtcAmountBorrowed;
borrow.startBlock = block.number;
}
function _repay(uint borrowId) public returns (bool) {
Borrow storage borrow = borrows[msg.sender][borrowId];
borrow.endBlock = block.number;
}
function _updateRepaymentAmount(uint borrowId, uint repaymentAmount, uint interestAmountForBorrowing) public returns (bool) {
Borrow storage borrow = borrows[msg.sender][borrowId];
borrow.wbtcAmountBorrowed = repaymentAmount.sub(interestAmountForBorrowing);
}
function _updateWithdrawalAmount(uint lendId, uint withdrawalAmount, uint interestAmountForLending) public returns (bool) {
Lend storage lend = lends[msg.sender][lendId];
lend.daiAmountLended = withdrawalAmount.sub(interestAmountForLending);
}
function _withdraw(uint lendId) public returns (bool) {
Lend storage lend = lends[msg.sender][lendId];
lend.endBlock = block.number;
}
///-----------------------------------
/// Getter methods
///-----------------------------------
function getLend(uint lendId) public view returns (Lend memory _lend) {
Lend memory lend = lends[msg.sender][lendId];
return lend;
}
function getBorrow(uint borrowId) public view returns (Borrow memory _borrow) {
Borrow memory borrow = borrows[msg.sender][borrowId];
return borrow;
}
function getRepaymentAmount(uint borrowId) public view returns (uint _repaymentAmount) {
Borrow memory borrow = borrows[msg.sender][borrowId];
uint _wbtcAmountBorrowed = borrow.wbtcAmountBorrowed; /// Principle amount borrowed
uint _startBlock = borrow.startBlock;
uint currentBlock = block.number;
uint OneYearAsSecond = 1 days * 365;
uint interestRateForBorrowingPerSecond = interestRateForBorrowing.div(OneYearAsSecond);
uint interestRateForBorrowingPerBlock = interestRateForBorrowingPerSecond.mul(15); // [Note]: 1 block == 15 seconds
uint interestAmountForBorrowing = _wbtcAmountBorrowed.mul(interestRateForBorrowingPerBlock).div(100).mul(currentBlock.sub(_startBlock));
uint repaymentAmount = _wbtcAmountBorrowed.add(interestAmountForBorrowing);
return repaymentAmount;
}
} | Calculate earned-interests amount of lending by every block Update a DAI amount that msg.sender lended | function withdrawDAI(uint lendId, uint withdrawalAmount) public returns (bool) {
_withdraw(lendId);
address lender = msg.sender;
Lend memory lend = lends[lender][lendId];
uint startBlock = lend.startBlock;
uint endBlock = lend.endBlock;
uint OneYearAsSecond = 1 days * 365;
uint interestRateForLendingPerSecond = interestRateForLending.div(OneYearAsSecond);
uint interestAmountForLending = daiAmountLended.mul(interestRateForLendingPerBlock).div(100).mul(endBlock.sub(startBlock));
_updateWithdrawalAmount(lendId, withdrawalAmount, interestAmountForLending);
}
| 12,552,631 |
pragma solidity ^0.4.24;
import "./Owned.sol";
import "./SGDz.sol";
import "./StashFactory.sol";
import "./Bank.sol";
contract Payment is Owned {// Regulator node (MAS) should be the owner
/* pseudo-public */
function releasePmt(bytes32 _txRef) atState(AgentState.Normal) {
/* require(pmtProved(_txRef)); */
require(globalGridlockQueue[_txRef].state == GridlockState.Active ||
globalGridlockQueue[_txRef].state == GridlockState.Inactive);
delete globalGridlockQueue[_txRef];
globalGridlockQueueDepth--;
globalGridlockQueue[_txRef].state = GridlockState.Released;
removeByValue('gridlockQueue', _txRef);
}
/* @pseudo-public */
// need to orchestrate the adding to the global gridlockqueue
function addToGlobalQueue(bytes32 _txRef) atState(AgentState.Normal) {
globalGridlockQueueDepth++;
globalGridlockQueue[_txRef].state = GridlockState.Active;
globalGridlockQueue[_txRef].receiverVote = true;
if (globalGridlockQueueDepth >= maxQueueDepth) nextState();
if (isReceiver(_txRef)) enqueue(_txRef, payments[_txRef].express);
}
event Time(uint remainingTime);
/* @pseudo-public
Determine the resolve sequence, and broadcast gridlocked payments to
receivers */
function lineUp()
atState(AgentState.Lineopen)
//isStashOwner(_stashName)
{
if (lineOpenTime == 0) {lineOpenTime = now;}
resolveSequence.push(msg.sender);
done[bank.getStash(msg.sender)] = false;
Time(lineOpenTime + timeout - now);
if (resolveSequence.length == sf.getStashNameCount()) nextState();
}
function isParticipating(bytes32 _stashName) internal returns (bool) {
for (uint i = 0; i < resolveSequence.length; i++) {
if (bank.getStash(resolveSequence[i]) == _stashName) return true;
}
return false;
}
/* for testing */
event Hash(bytes32 hash, bytes32 a);
function doHash(uint256 _a) {
bytes32 result = keccak256(_a);
Hash(result, bytes32(_a));
}
function doHashBytes(bytes32 _a) {
bytes32 result = keccak256(_a);
Hash(result, _a);
}
function doHashBytes2(bytes32 _a, bytes32 _b) {
bytes32 result = keccak256(_a, _b);
Hash(result, _a);
}
event Answer(bool a);
event Num(uint n);
function verify() {
bytes32 key = 'R1231';
Answer(payments[key].txRef == bytes32(''));
Num(uint(- 1));
}
event Array(bytes32[] a);
bytes32[] array;
function emitArray(bytes32 a, bytes32 b) {
array.push(a);
array.push(b);
Array(array);
}
function bytesArrayInput(bytes32[] _input) {
Array(_input);
}
/* @pseudo-public
THIS METHOD WILL BREAK THE PSEUDO-PUBLIC STATES.
However you should still make a pseudo-public call as we want to update PaymentAgent's
state on all the nodes.
You'll need to call syncPseudoPublicStates after calling this method to sync up
the pseudo-public states. */
event Sync(bytes32[] inactivatedPmtRefs, bytes32[] doneStashes, bytes32[] notDoneStashes);
function doResolveRound()
timedTransitions
atState(AgentState.Resolving)
isYourTurn
returns (bool _didResolution)
{
lastResolveTime = now;
bytes32 currentStash = bank.getStash(resolveSequence[current]);
if (!checkOwnedStash(currentStash)) {return false;}
if (currentStash != bank.centralBank() && isCentralBankNode()) {return false;}
for (uint i = 0; i < gridlockQueue.length; i++) {
Pmt inflow = payments[gridlockQueue[i]];
GridlockedPmt g_inflow = globalGridlockQueue[inflow.txRef];
/* to be changed */
/* deactivate inflows from non-participant*/
if (!isParticipating(inflow.sender) && g_inflow.state == GridlockState.Active) {
g_inflow.state = GridlockState.Inactive;
sf.updatePosition(inflow.receiver, inflow.sender, inflow.amount);
// Stash(stashRegistry[inflow.sender]).inc_position(inflow.amount);
// Stash(stashRegistry[inflow.receiver]).dec_position(inflow.amount);
}
}
/* Bilateral EAF2 */
inactivatedPmtRefs.length = 0;
for (uint j = gridlockQueue.length - 1; j >= 0; j--) {// reverse chronological order
if (sf.getPosition(currentStash) >= 0) break;
// LSM liquidity partition
Pmt pmt = payments[gridlockQueue[j]];
GridlockedPmt g_pmt = globalGridlockQueue[pmt.txRef];
/* to be changed */
/* vote on your outflows */
if (pmt.sender == currentStash && g_pmt.state == GridlockState.Active) {
g_pmt.state = GridlockState.Inactive;
inactivatedPmtRefs.push(pmt.txRef);
sf.updatePosition(pmt.receiver, pmt.sender, pmt.amount);
// Stash(stashRegistry[pmt.sender]).inc_position(pmt.amount);
// Stash(stashRegistry[pmt.receiver]).dec_position(pmt.amount);
done[pmt.receiver] = false;
}
}
done[currentStash] = true;
/* emit sync info */
doneStashes.length = 0;
notDoneStashes.length = 0;
for (uint k = 0; k < resolveSequence.length; k++) {
bytes32 stashName = bank.getStash(resolveSequence[k]);
if (done[stashName]) doneStashes.push(stashName);
else notDoneStashes.push(stashName);
}
Sync(inactivatedPmtRefs, doneStashes, notDoneStashes);
committed = true;
return true;
}
function allDone() internal returns (bool) {
bool alldone = true;
for (uint i = 0; i < resolveSequence.length; i++) {
if (!done[bank.getStash(resolveSequence[i])]) {
alldone = false;
break;
}
}
return alldone;
}
function receiverInactivate(bytes32 _txRef) private returns (bool _isReceiver) {
for (uint i = 0; i < gridlockQueue.length; i++) {
Pmt pmt = payments[gridlockQueue[i]];
if (pmt.txRef == _txRef) {
if (!checkOwnedStash(pmt.receiver)) return false;
sf.updatePosition(pmt.receiver, pmt.sender, pmt.amount);
return true;
}
}
}
event AllDone(bool allDone, uint current);
/* @pseudo-public */
function syncPseudoPublicStates(bytes32[] _inactivatedPmtRefs,
bytes32[] _doneStashes,
bytes32[] _notDoneStashes)
atState(AgentState.Resolving)
isYourTurn
hasCommitted(_inactivatedPmtRefs, _doneStashes, _notDoneStashes)
{
/* syncing global queue */
globalGridlockQueueDepth += _inactivatedPmtRefs.length;
for (uint i = 0; i < _inactivatedPmtRefs.length; i++) {
globalGridlockQueue[_inactivatedPmtRefs[i]].state = GridlockState.Inactive;
receiverInactivate(_inactivatedPmtRefs[i]);
}
/* syncing done mapping */
for (uint j = 0; j < _doneStashes.length; j++) {
done[_doneStashes[j]] = true;
}
for (uint k = 0; k < _notDoneStashes.length; k++) {
done[_notDoneStashes[k]] = false;
}
/* if everyone is done, enter netting phase, else pass on to the next participant */
bool alldone = allDone();
current++;
if (current == resolveSequence.length) current = 0;
AllDone(alldone, current);
if (alldone == true) nextState();
}
/* @pseudo-public */
//update private balance , update zcontract first then local balance, used at the end of the
// LSM process only.
event Deadlock();
function settle() atState(AgentState.Settling) {
/* netting by doing net balance movement */
sf.netting(msg.sender);
/* 1. confirm and dequeue active gridlocked payments
2. reactivate inactive gridlocked payments and update position accordingly */
uint beforeSettleGridlockCount = gridlockQueue.length;
uint numGridlockedPmts = 0;
for (uint j = 0; j < gridlockQueue.length; j++) {
/* require(pmtProved(gridlockQueue[j])); */
Pmt pmt = payments[gridlockQueue[j]];
GridlockedPmt g_pmt = globalGridlockQueue[pmt.txRef];
/* to be changed */
if (g_pmt.state == GridlockState.Active) {
g_pmt.state = GridlockState.Released;
// Changed
pmt.state = PmtState.Confirmed;
} else if (g_pmt.state == GridlockState.Inactive) {// reactivate inactive pmts
g_pmt.state = GridlockState.Active;
sf.updatePosition(pmt.sender, pmt.receiver, pmt.amount);
gridlockQueue[numGridlockedPmts] = pmt.txRef;
numGridlockedPmts++;
} else if (g_pmt.state == GridlockState.Onhold) {
gridlockQueue[numGridlockedPmts] = pmt.txRef;
numGridlockedPmts++;
}
}
if (beforeSettleGridlockCount == numGridlockedPmts) {
Deadlock();
/* maxQueueDepth += 5; // prevent recursive gridlock */
} else if (isNettingParticipant()) {
bank.updateCurrentSalt2NettingSalt();
}
gridlockQueue.length = numGridlockedPmts;
nextState();
}
// current resolve round leader can stop the LSM if timeout
function moveOn() atState(AgentState.Settling) isYourTurn {
require(now >= resolveEndTime + proofTimeout);
nextState();
}
function pmtProved(bytes32 _txRef) external view returns (bool) {
return sgdz.proofCompleted(_txRef);
}
/* @private for: [sender, receiver, (MAS)] */
function confirmPmt(bytes32 _txRef) atState(AgentState.Normal) onlyReceiver(_txRef) {
//comment out to get it to work
/* require(pmtProved(_txRef)); */
sf.transfer(payments[_txRef].sender,
payments[_txRef].receiver,
payments[_txRef].amount,
msg.sender);
payments[_txRef].state = PmtState.Confirmed;
bank.updateCurrentSalt(payments[_txRef].salt);
}
// UBIN-61 ///////////////////////////////////////////////////
// @pseudo-public == privateFor: [everyone]
// ----------------------------------------------------------
// UBIN-61 [Quorum] Cancel unsettled outgoing payment instruction - Laks
// ----------------------------------------------------------
function cancelPmtFromGlobalQueue(bytes32 _txRef)
atState(AgentState.Normal)
//onlySender(_txRef)
{
require(globalGridlockQueue[_txRef].state != GridlockState.Cancelled);
if (globalGridlockQueue[_txRef].state != GridlockState.Onhold) {
globalGridlockQueueDepth--;
delete globalGridlockQueue[_txRef];
}
globalGridlockQueue[_txRef].state = GridlockState.Cancelled;
}
//anything other than agent state Normal will get rejected
// @privateFor: [receiver, (optional MAS)]
// call this after cancelPmtFromGlobalQueue
function cancelPmt(bytes32 _txRef)
atState(AgentState.Normal)
onlySender(_txRef)
{
if (bank.isSuspended(payments[_txRef].sender)) {
bank.emitStatusCode(600);
return;
}
require((payments[_txRef].state == PmtState.Pending) ||
(payments[_txRef].state == PmtState.Onhold));
require(globalGridlockQueue[_txRef].state != GridlockState.Cancelled);
bool changePosition = false;
if (payments[_txRef].state == PmtState.Pending) changePosition = true;
if (payments[_txRef].state == PmtState.Onhold) removeByValue('onholdPmts', _txRef);
payments[_txRef].state = PmtState.Cancelled;
//if high priority, decrement express count
if (payments[_txRef].express == 1) {
expressCount--;
}
//remove item from gridlock array
removeByValue('gridlockQueue', _txRef);
// instead of doing this, we have compress the cancelled item in settle()
if (changePosition) updatePosition(_txRef, true);
// if (success) Status(_txRef,true);
//inactivationTracker++;
Status(_txRef, true);
}
// ---------------------------------------------------------------------------
// UBIN-62 - Put unsettled outgoing payment instruction on hold - Laks
// @pseudo-public
// ---------------------------------------------------------------------------
function holdPmtFromGlobalQueue(bytes32 _txRef)
atState(AgentState.Normal)
//onlySender(_txRef)
{
require((globalGridlockQueue[_txRef].state != GridlockState.Onhold) && (globalGridlockQueue[_txRef].state != GridlockState.Cancelled));
GridlockedPmt g_pmt = globalGridlockQueue[_txRef];
g_pmt.state = GridlockState.Onhold;
globalGridlockQueueDepth--;
}
// ---------------------------------------------------------------------------
// UBIN-62 - Put unsettled outgoing payment instruction on hold - Laks
// @privateFor: [receiver, (optional MAS)]
// ---------------------------------------------------------------------------
event Status(bytes32 txRef, bool holdStatus);
function holdPmt(bytes32 _txRef)
atState(AgentState.Normal)
onlySender(_txRef)
{
if (bank.isSuspended(payments[_txRef].sender)) {
bank.emitStatusCode(700);
return;
}
require(payments[_txRef].state == PmtState.Pending);
require(globalGridlockQueue[_txRef].state != GridlockState.Onhold);
payments[_txRef].state = PmtState.Onhold;
onholdPmts.push(_txRef);
updatePosition(_txRef, true);
removeByValue('gridlockQueue', _txRef);
if (payments[_txRef].state == PmtState.Onhold) {
//inactivationTracker++;
Status(_txRef, true);
}
else Status(_txRef, false);
// Debug message - bank.getStash(msg.sender) is empty leading to onlySender to fail - Laks
}
// ---------------------------------------------------------------------------
// UBIN-63 - Reactivate unsettled payment instruction that is on hold - Laks
// @privateFor: [receiver, (optional MAS)]
// ---------------------------------------------------------------------------
function unholdPmt(bytes32 _txRef)
atState(AgentState.Normal)
onlySender(_txRef)
{
if (bank.isSuspended(payments[_txRef].sender)) {
bank.emitStatusCode(800);
return;
}
require(payments[_txRef].state == PmtState.Onhold);
require(globalGridlockQueue[_txRef].state == GridlockState.Onhold);
payments[_txRef].state = PmtState.Pending;
removeByValue('onholdPmts', _txRef);
enqueue(_txRef, payments[_txRef].express);
updatePosition(_txRef, false);
if (payments[_txRef].state == PmtState.Pending) {
//inactivationTracker--;
Status(_txRef, false);
}
else Status(_txRef, true);
}
// ---------------------------------------------------------------------------
// UBIN-63 - Reactivate unsettled payment instruction that is on hold - Laks
// @pseudo-public
// called after unholdPmt
// ---------------------------------------------------------------------------
function unholdPmtFromGlobalQueue(bytes32 _txRef)
atState(AgentState.Normal)
//onlySender(_txRef)
{
//remove item from globalGridlockQueue
require(globalGridlockQueue[_txRef].state == GridlockState.Onhold);
GridlockedPmt g_pmt = globalGridlockQueue[_txRef];
g_pmt.state = GridlockState.Active;
globalGridlockQueueDepth++;
}
function updatePosition(bytes32 _txRef, bool reverse) internal {
if (reverse) {
sf.updatePosition(payments[_txRef].receiver, payments[_txRef].sender, payments[_txRef].amount);
} else {
sf.updatePosition(payments[_txRef].sender, payments[_txRef].receiver, payments[_txRef].amount);
}
}
function getLineLength() view returns (uint) {
return resolveSequence.length;
}
function getIsPaymentActive(bytes32 _txRef) external view returns (bool) {
GridlockedPmt g_pmt = globalGridlockQueue[_txRef];
/* to be changed */
if (g_pmt.state == GridlockState.Active) {
return true;
} else {
return false;
}
}
// ----------------------------------------------------------
// ----------------------------------------------------------
function IndexOf(bytes32[] values, bytes32 value) returns (uint) {
uint i;
bool found = true;
for (i = 0; i < values.length; i++) {
if (values[i] == value) {
found = true;
break;
}
}
if (found)
return i;
else
return 99999999;
}
// ------------------------------
// Implementation of UBIN-60 - Laks
// ------------------------------
function updatePriority(bytes32 _txRef, int _express) {
var (i,found) = ArrayIndexOf(pmtIdx, _txRef);
if (!found) {
bank.emitStatusCode(300);
return;
}
if (bank.isSuspended(payments[_txRef].sender)) {
bank.emitStatusCode(400);
return;
}
require(payments[_txRef].express != _express);
// no update when the priority level is the same
if (payments[_txRef].express == 0) {
expressCount++;
} else if (payments[_txRef].express == 1) {
expressCount--;
}
payments[_txRef].express = _express;
updateGridlockQueue(_txRef);
}
// -----------------------------------------------------
// TO DO - To be refactored into a common untils - Laks
// -----------------------------------------------------
function ArrayIndexOf(bytes32[] values, bytes32 value) view internal returns (uint, bool) {
bool found = false;
uint i;
for (i = 0; i < values.length; i++) {
if (values[i] == value) {
found = true;
break;
}
}
if (found)
return (i, found);
else
return (0, found);
}
// ------------------------------------
// Keep the gridlock queue sorted by 1. priority level 2. timestamp
// Might need a more generic quick sort function in future
// Assumes that the gridlockqueue is already sorted before the current txn
// ------------------------------------
function updateGridlockQueue(bytes32 _txRef){
uint tstamp = payments[_txRef].timestamp;
uint i;
bytes32 curTxRef;
uint curTstamp;
int curExpress;
var (index, found) = ArrayIndexOf(gridlockQueue, _txRef);
uint j = index;
if (payments[_txRef].express == 1) {
// shift the txn to the left
if (index == 0) return;
for (i = index - 1; int(i) >= 0; i--) {// rather painful discovery that uint i>=0 doesn't work :( - Jay
curTxRef = gridlockQueue[i];
curTstamp = payments[curTxRef].timestamp;
curExpress = payments[curTxRef].express;
if (curExpress == 0 || tstamp < curTstamp) {
gridlockQueue[i] = _txRef;
gridlockQueue[j] = curTxRef;
j--;
}
}
} else {
// shift the txn to the right
if (index == gridlockQueue.length - 1) return;
for (i = index + 1; i <= gridlockQueue.length - 1; i++) {
curTxRef = gridlockQueue[i];
curTstamp = payments[curTxRef].timestamp;
curExpress = payments[curTxRef].express;
if (curExpress == 1 || tstamp > curTstamp) {
gridlockQueue[i] = _txRef;
gridlockQueue[j] = curTxRef;
j++;
}
}
}
}
// ------------------------------------
// ------------------------------------
// Removes the given value in an array
// Refactored to use ArrayIndexOf - Laks
// ------------------------------------
function removeByValue(bytes32 arrayName, bytes32 value) internal returns (bool) {
bytes32[] array;
//TODO use a mapping?
if (arrayName == 'onholdPmts') {
array = onholdPmts;
} else if (arrayName == 'gridlockQueue') {
array = gridlockQueue;
if (payments[value].express == 1) expressCount--;
} else {
return false;
}
var (index, found) = ArrayIndexOf(array, value);
if (found) {
for (uint i = index; i < array.length - 1; i++) {
array[i] = array[i + 1];
}
delete array[array.length - 1];
array.length--;
return true;
}
return false;
}
}
| --------------------------------------------------------------------------- UBIN-63 - Reactivate unsettled payment instruction that is on hold - Laks @privateFor: [receiver, (optional MAS)] --------------------------------------------------------------------------- | {
}
function unholdPmt(bytes32 _txRef)
atState(AgentState.Normal)
onlySender(_txRef)
if (bank.isSuspended(payments[_txRef].sender)) {
bank.emitStatusCode(800);
return;
}
require(payments[_txRef].state == PmtState.Onhold);
require(globalGridlockQueue[_txRef].state == GridlockState.Onhold);
payments[_txRef].state = PmtState.Pending;
removeByValue('onholdPmts', _txRef);
enqueue(_txRef, payments[_txRef].express);
updatePosition(_txRef, false);
if (payments[_txRef].state == PmtState.Pending) {
Status(_txRef, false);
}
else Status(_txRef, true);
}
| 12,707,855 |
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see `ERC20Detailed`.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through `transferFrom`. This is
* zero by default.
*
* This value changes when `approve` or `transferFrom` are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* > Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an `Approval` event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a `Transfer` event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to `approve`. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: openzeppelin-solidity/contracts/math/SafeMath.sol
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, "SafeMath: division by zero");
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, "SafeMath: modulo by zero");
return a % b;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol
pragma solidity ^0.5.0;
/**
* @dev Implementation of the `IERC20` interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using `_mint`.
* For a generic mechanism see `ERC20Mintable`.
*
* *For a detailed writeup see our guide [How to implement supply
* mechanisms](https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226).*
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an `Approval` event is emitted on calls to `transferFrom`.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard `decreaseAllowance` and `increaseAllowance`
* functions have been added to mitigate the well-known issues around setting
* allowances. See `IERC20.approve`.
*/
contract ERC20 is IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
/**
* @dev See `IERC20.totalSupply`.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev See `IERC20.balanceOf`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev See `IERC20.transfer`.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public returns (bool) {
_transfer(msg.sender, recipient, amount);
return true;
}
/**
* @dev See `IERC20.allowance`.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See `IERC20.approve`.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 value) public returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev See `IERC20.transferFrom`.
*
* Emits an `Approval` event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of `ERC20`;
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `value`.
* - the caller must have allowance for `sender`'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(amount));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to `approve` that can be used as a mitigation for
* problems described in `IERC20.approve`.
*
* Emits an `Approval` event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to `transfer`, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a `Transfer` event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a `Transfer` event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destoys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a `Transfer` event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 value) internal {
require(account != address(0), "ERC20: burn from the zero address");
_totalSupply = _totalSupply.sub(value);
_balances[account] = _balances[account].sub(value);
emit Transfer(account, address(0), value);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an `Approval` event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 value) internal {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Destoys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See `_burn` and `_approve`.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount));
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Detailed.sol
pragma solidity ^0.5.0;
/**
* @dev Optional functions from the ERC20 standard.
*/
contract ERC20Detailed is IERC20 {
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for `name`, `symbol`, and `decimals`. All three of
* these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol, uint8 decimals) public {
_name = name;
_symbol = symbol;
_decimals = decimals;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei.
*
* > Note that this information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* `IERC20.balanceOf` and `IERC20.transfer`.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
}
// File: openzeppelin-solidity/contracts/access/Roles.sol
pragma solidity ^0.5.0;
/**
* @title Roles
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
// File: openzeppelin-solidity/contracts/access/roles/PauserRole.sol
pragma solidity ^0.5.0;
contract PauserRole {
using Roles for Roles.Role;
event PauserAdded(address indexed account);
event PauserRemoved(address indexed account);
Roles.Role private _pausers;
constructor () internal {
_addPauser(msg.sender);
}
modifier onlyPauser() {
require(isPauser(msg.sender), "PauserRole: caller does not have the Pauser role");
_;
}
function isPauser(address account) public view returns (bool) {
return _pausers.has(account);
}
function addPauser(address account) public onlyPauser {
_addPauser(account);
}
function renouncePauser() public {
_removePauser(msg.sender);
}
function _addPauser(address account) internal {
_pausers.add(account);
emit PauserAdded(account);
}
function _removePauser(address account) internal {
_pausers.remove(account);
emit PauserRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/lifecycle/Pausable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is PauserRole {
/**
* @dev Emitted when the pause is triggered by a pauser (`account`).
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by a pauser (`account`).
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state. Assigns the Pauser role
* to the deployer.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Called by a pauser to pause, triggers stopped state.
*/
function pause() public onlyPauser whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev Called by a pauser to unpause, returns to normal state.
*/
function unpause() public onlyPauser whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Pausable.sol
pragma solidity ^0.5.0;
/**
* @title Pausable token
* @dev ERC20 modified with pausable transfers.
*/
contract ERC20Pausable is ERC20, Pausable {
function transfer(address to, uint256 value) public whenNotPaused returns (bool) {
return super.transfer(to, value);
}
function transferFrom(address from, address to, uint256 value) public whenNotPaused returns (bool) {
return super.transferFrom(from, to, value);
}
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
return super.approve(spender, value);
}
function increaseAllowance(address spender, uint addedValue) public whenNotPaused returns (bool) {
return super.increaseAllowance(spender, addedValue);
}
function decreaseAllowance(address spender, uint subtractedValue) public whenNotPaused returns (bool) {
return super.decreaseAllowance(spender, subtractedValue);
}
}
// File: openzeppelin-solidity/contracts/access/roles/MinterRole.sol
pragma solidity ^0.5.0;
contract MinterRole {
using Roles for Roles.Role;
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
Roles.Role private _minters;
constructor () internal {
_addMinter(msg.sender);
}
modifier onlyMinter() {
require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role");
_;
}
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
function addMinter(address account) public onlyMinter {
_addMinter(account);
}
function renounceMinter() public {
_removeMinter(msg.sender);
}
function _addMinter(address account) internal {
_minters.add(account);
emit MinterAdded(account);
}
function _removeMinter(address account) internal {
_minters.remove(account);
emit MinterRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Mintable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of `ERC20` that adds a set of accounts with the `MinterRole`,
* which have permission to mint (create) new tokens as they see fit.
*
* At construction, the deployer of the contract is the only minter.
*/
contract ERC20Mintable is ERC20, MinterRole {
/**
* @dev See `ERC20._mint`.
*
* Requirements:
*
* - the caller must have the `MinterRole`.
*/
function mint(address account, uint256 amount) public onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
}
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Burnable.sol
pragma solidity ^0.5.0;
/**
* @dev Extension of `ERC20` that allows token holders to destroy both their own
* tokens and those that they have an allowance for, in a way that can be
* recognized off-chain (via event analysis).
*/
contract ERC20Burnable is ERC20 {
/**
* @dev Destoys `amount` tokens from the caller.
*
* See `ERC20._burn`.
*/
function burn(uint256 amount) public {
_burn(msg.sender, amount);
}
/**
* @dev See `ERC20._burnFrom`.
*/
function burnFrom(address account, uint256 amount) public {
_burnFrom(account, amount);
}
}
// File: openzeppelin-solidity/contracts/ownership/Ownable.sol
pragma solidity ^0.5.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be aplied to your functions to restrict their use to
* the owner.
*/
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* > Note: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: openzeppelin-solidity/contracts/access/roles/SignerRole.sol
pragma solidity ^0.5.0;
contract SignerRole {
using Roles for Roles.Role;
event SignerAdded(address indexed account);
event SignerRemoved(address indexed account);
Roles.Role private _signers;
constructor () internal {
_addSigner(msg.sender);
}
modifier onlySigner() {
require(isSigner(msg.sender), "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(msg.sender);
}
function _addSigner(address account) internal {
_signers.add(account);
emit SignerAdded(account);
}
function _removeSigner(address account) internal {
_signers.remove(account);
emit SignerRemoved(account);
}
}
// File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol
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.
*
* (.warning) `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
* [`eth_sign`](https://github.com/ethereum/wiki/wiki/JSON-RPC#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));
}
}
// File: openzeppelin-solidity/contracts/drafts/SignatureBouncer.sol
pragma solidity ^0.5.0;
/**
* @title SignatureBouncer
* @author PhABC, Shrugs and aflesher
* @dev SignatureBouncer allows users to submit a signature as a permission to
* do an action.
* If the signature is from one of the authorized signer addresses, the
* signature is valid.
* Note that SignatureBouncer offers no protection against replay attacks, users
* must add this themselves!
*
* Signer addresses can be individual servers signing grants or different
* users within a decentralized club that have permission to invite other
* members. This technique is useful for whitelists and airdrops; instead of
* putting all valid addresses on-chain, simply sign a grant of the form
* keccak256(abi.encodePacked(`:contractAddress` + `:granteeAddress`)) using a
* valid signer address.
* Then restrict access to your crowdsale/whitelist/airdrop using the
* `onlyValidSignature` modifier (or implement your own using _isValidSignature).
* In addition to `onlyValidSignature`, `onlyValidSignatureAndMethod` and
* `onlyValidSignatureAndData` can be used to restrict access to only a given
* method or a given method with given parameters respectively.
* See the tests in SignatureBouncer.test.js for specific usage examples.
*
* @notice A method that uses the `onlyValidSignatureAndData` modifier must make
* the _signature parameter the "last" parameter. You cannot sign a message that
* has its own signature in it so the last 128 bytes of msg.data (which
* represents the length of the _signature data and the _signature data itself)
* is ignored when validating. Also non fixed sized parameters make constructing
* the data in the signature much more complex.
* See https://ethereum.stackexchange.com/a/50616 for more details.
*/
contract SignatureBouncer is SignerRole {
using ECDSA for bytes32;
// Function selectors are 4 bytes long, as documented in
// https://solidity.readthedocs.io/en/v0.4.24/abi-spec.html#function-selector
uint256 private constant _METHOD_ID_SIZE = 4;
// Signature size is 65 bytes (tightly packed v + r + s), but gets padded to 96 bytes
uint256 private constant _SIGNATURE_SIZE = 96;
constructor () internal {
// solhint-disable-previous-line no-empty-blocks
}
/**
* @dev Requires that a valid signature of a signer was provided.
*/
modifier onlyValidSignature(bytes memory signature) {
require(_isValidSignature(msg.sender, signature), "SignatureBouncer: invalid signature for caller");
_;
}
/**
* @dev Requires that a valid signature with a specified method of a signer was provided.
*/
modifier onlyValidSignatureAndMethod(bytes memory signature) {
// solhint-disable-next-line max-line-length
require(_isValidSignatureAndMethod(msg.sender, signature), "SignatureBouncer: invalid signature for caller and method");
_;
}
/**
* @dev Requires that a valid signature with a specified method and params of a signer was provided.
*/
modifier onlyValidSignatureAndData(bytes memory signature) {
// solhint-disable-next-line max-line-length
require(_isValidSignatureAndData(msg.sender, signature), "SignatureBouncer: invalid signature for caller and data");
_;
}
/**
* @dev is the signature of `this + account` from a signer?
* @return bool
*/
function _isValidSignature(address account, bytes memory signature) internal view returns (bool) {
return _isValidDataHash(keccak256(abi.encodePacked(address(this), account)), signature);
}
/**
* @dev is the signature of `this + account + methodId` from a signer?
* @return bool
*/
function _isValidSignatureAndMethod(address account, bytes memory signature) internal view returns (bool) {
bytes memory data = new bytes(_METHOD_ID_SIZE);
for (uint i = 0; i < data.length; i++) {
data[i] = msg.data[i];
}
return _isValidDataHash(keccak256(abi.encodePacked(address(this), account, data)), signature);
}
/**
* @dev is the signature of `this + account + methodId + params(s)` from a signer?
* @notice the signature parameter of the method being validated must be the "last" parameter
* @return bool
*/
function _isValidSignatureAndData(address account, bytes memory signature) internal view returns (bool) {
require(msg.data.length > _SIGNATURE_SIZE, "SignatureBouncer: data is too short");
bytes memory data = new bytes(msg.data.length - _SIGNATURE_SIZE);
for (uint i = 0; i < data.length; i++) {
data[i] = msg.data[i];
}
return _isValidDataHash(keccak256(abi.encodePacked(address(this), account, data)), signature);
}
/**
* @dev Internal function to convert a hash to an eth signed message
* and then recover the signature and check it against the signer role.
* @return bool
*/
function _isValidDataHash(bytes32 hash, bytes memory signature) internal view returns (bool) {
address signer = hash.toEthSignedMessageHash().recover(signature);
return signer != address(0) && isSigner(signer);
}
}
// File: openzeppelin-solidity/contracts/introspection/ERC165Checker.sol
pragma solidity ^0.5.0;
/**
* @dev Library used to query support of an interface declared via `IERC165`.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Returns true if `account` supports the `IERC165` interface,
*/
function _supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return _supportsERC165Interface(account, _INTERFACE_ID_ERC165) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for `IERC165` itself is queried automatically.
*
* See `IERC165.supportsInterface`.
*/
function _supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return _supportsERC165(account) &&
_supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for `IERC165` itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* `IERC165` support.
*
* See `IERC165.supportsInterface`.
*/
function _supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!_supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with the `supportsERC165` method in this library.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
// success determines whether the staticcall succeeded and result determines
// whether the contract at account indicates support of _interfaceId
(bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);
return (success && result);
}
/**
* @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return success true if the STATICCALL succeeded, false otherwise
* @return result true if the STATICCALL succeeded and the contract at account
* indicates support of the interface with identifier interfaceId, false otherwise
*/
function _callERC165SupportsInterface(address account, bytes4 interfaceId)
private
view
returns (bool success, bool result)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
// solhint-disable-next-line no-inline-assembly
assembly {
let encodedParams_data := add(0x20, encodedParams)
let encodedParams_size := mload(encodedParams)
let output := mload(0x40) // Find empty storage location using "free memory pointer"
mstore(output, 0x0)
success := staticcall(
30000, // 30k gas
account, // To addr
encodedParams_data,
encodedParams_size,
output,
0x20 // Outputs are 32 bytes long
)
result := mload(output) // Load the result
}
}
}
// File: contracts/THCToken.sol
pragma solidity ^0.5.2;
contract THCToken is ERC20Detailed, ERC20Mintable, ERC20Burnable, ERC20Pausable, SignatureBouncer {
using SafeMath for uint256;
mapping (address => mapping (uint256 => bool)) public _usedNonce;
constructor(
string memory name,
string memory symbol,
uint8 decimals,
uint256 initialSupply,
address initialHolder,
address minter,
address signer,
address pauser
)
ERC20Detailed(name, symbol, decimals)
SignatureBouncer()
ERC20Mintable()
ERC20Pausable()
public
{
_mint(initialHolder, initialSupply);
_addMinter(minter);
_addPauser(pauser);
_addSigner(signer);
}
modifier isNotUsedNonce(address from, uint256 nonce) {
require(!_usedNonce[from][nonce]);
_;
}
function transferDelegatedWithSign(
address from,
address to,
uint256 amount,
uint256 fee,
uint256 nonce,
string memory message,
bytes memory signature
) public
whenNotPaused
isNotUsedNonce(msg.sender, nonce)
onlyValidSignatureAndData(signature)
returns (bool success)
{
require(from != address(0));
require(to != address(0));
require(from != to);
require(msg.sender != to);
require(msg.sender != from);
require(balanceOf(from) >= amount.add(fee), "not enough balance");
if(fee > 0) {
_transfer(from, msg.sender, fee);
}
_transfer(from, to, amount);
_usedNonce[msg.sender][nonce] = true;
return true;
}
} | is the signature of `this + account + methodId + params(s)` from a signer? the signature parameter of the method being validated must be the "last" parameter return bool/ | function _isValidSignatureAndData(address account, bytes memory signature) internal view returns (bool) {
require(msg.data.length > _SIGNATURE_SIZE, "SignatureBouncer: data is too short");
bytes memory data = new bytes(msg.data.length - _SIGNATURE_SIZE);
for (uint i = 0; i < data.length; i++) {
data[i] = msg.data[i];
}
return _isValidDataHash(keccak256(abi.encodePacked(address(this), account, data)), signature);
}
| 912,627 |
// SPDX-License-Identifier: CC-BY-4.0
pragma solidity >=0.4.22 <0.9.0;
// Import the library 'Roles'
import "./Roles.sol";
// Define a contract 'SupplierRole' to manage this role - add, remove, check
contract SupplierRole {
using Roles for Roles.Role;
// Define 2 events, one for Adding, and other for Removing
event SupplierAdded(address indexed account);
event SupplierRemoved(address indexed account);
// Define a struct 'suppliers' by inheriting from 'Roles' library, struct Role
Roles.Role private suppliers;
// In the constructor make the address that deploys this contract the 1st consumer
constructor() {
_addSupplier(msg.sender);
}
// Define a modifier that checks to see if msg.sender has the appropriate role
modifier onlySupplier() {
require(isSupplier(msg.sender), "You need to have the consumer role to perform this");
_;
}
// Define a function 'isSupplier' to check this role
function isSupplier(address account) public view returns (bool) {
return suppliers.has(account);
}
// Define a function 'addSupplier' that adds this role
function addSupplier(address account) public onlySupplier {
_addSupplier(account);
}
// Define a function 'renounceSupplier' to renounce this role
function renounceSupplier() public {
_removeSupplier(msg.sender);
}
// Define an internal function '_addSupplier' to add this role, called by 'addSupplier'
function _addSupplier(address account) internal {
suppliers.add(account);
emit SupplierAdded(account);
}
// Define an internal function '_removeSupplier' to remove this role, called by 'removeSupplier'
function _removeSupplier(address account) internal {
suppliers.remove(account);
emit SupplierRemoved(account);
}
} | Define a function 'renounceSupplier' to renounce this role | function renounceSupplier() public {
_removeSupplier(msg.sender);
}
| 5,377,124 |
./partial_match/1/0xCFc81Bc2507467084f038E88EB6576b4e66f6adD/sources/ERC20.sol | applies taxes, checks for limits, locks generates autoLP and stakingETH, and autostakesIf seller sold less than sellLockTime(2h 50m) ago, sell is declined, can be disabled by TeamSets the time sellers get locked(2 hours 50 mins by default)If buyer bought less than buyLockTime(2h 50m) ago, buy is declined, can be disabled by TeamSets the time buyers get locked(2 hours 50 mins by default) | function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{
uint256 recipientBalance = _balances[recipient];
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "Transfer exceeds balance");
uint8 tax;
if(isSell){
if(!_excludedFromSellLock.contains(sender)){
require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Seller in sellLock");
_sellLock[sender]=block.timestamp+sellLockTime;
}
require(_isBlacklisted.contains(sender) == false, "Address blacklisted!");
if (block.timestamp <= tradingEnabledAt + autoBanTime && enableAutoBlacklist == 1) {
_isBlacklisted.add(sender);
emit antiBotBan(sender);
}
tax=_sellTax;
if(!_excludedFromBuyLock.contains(recipient)){
require(_buyLock[recipient]<=block.timestamp||buyLockDisabled,"Buyer in buyLock");
_buyLock[recipient]=block.timestamp+buyLockTime;
}
require(amount <= MaxBuy,"Tx amount exceeding max buy amount");
require(_isBlacklisted.contains(recipient) == false, "Address blacklisted!");
if (block.timestamp <= tradingEnabledAt + autoBanTime && enableAutoBlacklist == 1) {
_isBlacklisted.add(recipient);
emit antiBotBan(recipient);
}
tax=_buyTax;
require(_sellLock[sender]<=block.timestamp||sellLockDisabled,"Sender in Lock");
require(_isBlacklisted.contains(sender) == false, "Sender address blacklisted!");
require(_isBlacklisted.contains(recipient) == false, "Recipient address blacklisted!");
if (block.timestamp <= tradingEnabledAt + autoBanTime && enableAutoBlacklist == 1) {
_isBlacklisted.add(sender);
emit antiBotBan(sender);
}
tax=_transferTax;
}
_swapContractToken();
emit Transfer(sender,recipient,taxedAmount);
}
| 9,233,532 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import './ERC721Enum.sol';
import '@openzeppelin/contracts/security/ReentrancyGuard.sol';
import './PaymentSplitter.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/access/Ownable.sol';
import '@openzeppelin/contracts/utils/Counters.sol';
import '../interfaces/ILBRLedger.sol';
/**
* @title LBR Ledger minting contract
* @author Maxwell J. Rux
*/
contract LBRLedger is
ERC721Enum,
Ownable,
ReentrancyGuard,
PaymentSplitter,
ILBRLedger
{
using Counters for Counters.Counter;
using Strings for uint256;
string private _uri;
string private _contractURI;
uint256 private _price = 0.08 ether;
uint256 private constant MAX_SUPPLY = 5000;
uint256 private constant MAX_MULTIMINT = 25;
uint256 private constant MAX_RESERVED_SUPPLY = 250;
// number of NFTs in reserve that have already been minted
Counters.Counter private _reserved;
bool _status = false;
constructor(
string memory __uri,
address[] memory payees,
uint256[] memory shares,
string memory _name,
string memory _symbol
) ERC721M(_name, _symbol) PaymentSplitter(payees, shares) {
_uri = __uri;
}
/**
* @dev Mint an LBR Ledger NFT
* @param numMints Number of mints
*/
function mint(uint256 numMints) external payable override nonReentrant {
require(_status, 'LBRLedger: Sale is paused');
require(
msg.value >= price() * numMints,
'LBRLedger: Not enough ether sent'
);
require(
totalSupply() + numMints <= MAX_SUPPLY,
'LBRLedger: New mint exceeds maximum supply'
);
require(
totalSupply() + numMints <=
MAX_SUPPLY - MAX_RESERVED_SUPPLY + _reserved.current(),
'LBRLedger: New mint exceeds maximum available supply'
);
require(
numMints <= MAX_MULTIMINT,
'LBRLedger: Exceeds max mints per transaction'
);
uint256 tokenIndex = totalSupply();
for (uint256 i = 0; i < numMints; ++i) {
_safeMint(msg.sender, tokenIndex + i);
}
delete tokenIndex;
}
/**
* @dev Mints reserved NFTs to an address other than the sender. Sender must be owner
* @param numMints Number of mints
* @param recipient Recipient of new mints
*/
function mintReservedToAddress(uint256 numMints, address recipient)
external
onlyOwner
{
require(
totalSupply() + numMints <= MAX_SUPPLY,
'LBRLedger: New mint exceeds maximum supply'
);
require(
_reserved.current() + numMints <= MAX_RESERVED_SUPPLY,
'LBRLedger: New mint exceeds reserve supply'
);
uint256 tokenIndex = totalSupply();
for (uint256 i = 0; i < numMints; ++i) {
_reserved.increment();
_safeMint(recipient, tokenIndex + i);
}
delete tokenIndex;
}
/**
* @dev Mints reserved NFTs to the sender. Sender must be owner
* @param numMints Number of mints
*/
function mintReserved(uint256 numMints) external onlyOwner {
require(
totalSupply() + numMints <= MAX_SUPPLY,
'LBRLedger: New mint exceeds maximum supply'
);
require(
_reserved.current() + numMints <= MAX_RESERVED_SUPPLY,
'LBRLedger: New mint exceeds reserve supply'
);
uint256 tokenIndex = totalSupply();
for (uint256 i = 0; i < numMints; ++i) {
_reserved.increment();
_safeMint(msg.sender, tokenIndex + i);
}
delete tokenIndex;
}
/**
* @dev Sets base uri used for tokenURI. Sender must be owner
* @param __uri The new uri to set base uri to
*/
function setBaseURI(string memory __uri) external onlyOwner {
_uri = __uri;
}
/**
* @dev Sets price per mint. Sender must be owner
* @param __price New price
*/
function setPrice(uint256 __price) external onlyOwner {
_price = __price;
}
/**
* @dev Changes sale state to opposite of what it was previously. Sender must be owner
*/
function flipSaleState() external onlyOwner {
_status = !_status;
}
function setContractURI(string memory __contractURI) external onlyOwner {
_contractURI = __contractURI;
}
function contractURI() public view override returns (string memory) {
return _contractURI;
}
function price() public view override returns (uint256) {
return _price;
}
function reserved() public view override returns (uint256) {
return _reserved.current();
}
function baseURI() public view override returns (string memory) {
return _uri;
}
function _baseURI() internal view virtual override returns (string memory) {
return _uri;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol)
pragma solidity ^0.8.0;
import './ERC721M.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/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 ERC721Enum is ERC721M, IERC721Enumerable {
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(IERC165, ERC721M)
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 < ERC721M.balanceOf(owner),
'ERC721Enum: owner index out of bounds'
);
uint256 counter = 0;
for (uint256 i = 0; i < _owners.length; ++i) {
if (owner == _owners[i]) {
if (counter == index) {
return i;
} else {
++counter;
}
}
}
require(false, 'ERC721Enum: owner index out of bounds');
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _owners.length;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
require(_exists(index), 'ERC721Enumerable: global index out of bounds');
return index;
}
function tokensOfOwner(address owner) public view returns (uint256[] memory) {
require(
ERC721M.balanceOf(owner) > 0,
'ERC721Enum: owner index out of bounds'
);
uint256 b = balanceOf(owner);
uint256[] memory ids = new uint256[](b);
for (uint256 i = 0; i < b; ++i) {
ids[i] = tokenOfOwnerByIndex(owner, i);
}
return ids;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and making it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/Context.sol';
import '@openzeppelin/contracts/utils/math/SafeMath.sol';
/**
* @title PaymentSplitter
* @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware
* that the Ether will be split in this way, since it is handled transparently by the contract.
*
* The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each
* account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim
* an amount proportional to the percentage of total shares they were assigned.
*
* `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the
* accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release}
* function.
*/
contract PaymentSplitter is Context {
event PayeeAdded(address account, uint256 shares);
event PaymentReleased(address to, uint256 amount);
event PaymentReceived(address from, uint256 amount);
uint256 private _totalShares;
uint256 private _totalReleased;
mapping(address => uint256) private _shares;
mapping(address => uint256) private _released;
address[] private _payees;
/**
* @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at
* the matching position in the `shares` array.
*
* All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no
* duplicates in `payees`.
*/
constructor(address[] memory payees, uint256[] memory shares_) payable {
require(
payees.length == shares_.length,
'PaymentSplitter: payees and shares length mismatch'
);
require(payees.length > 0, 'PaymentSplitter: no payees');
for (uint256 i = 0; i < payees.length; i++) {
_addPayee(payees[i], shares_[i]);
}
}
/**
* @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully
* reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the
* reliability of the events, and not the actual splitting of Ether.
*
* To learn more about this see the Solidity documentation for
* https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback
* functions].
*/
receive() external payable virtual {
emit PaymentReceived(_msgSender(), msg.value);
}
/**
* @dev Getter for the total shares held by payees.
*/
function totalShares() public view returns (uint256) {
return _totalShares;
}
/**
* @dev Getter for the total amount of Ether already released.
*/
function totalReleased() public view returns (uint256) {
return _totalReleased;
}
/**
* @dev Getter for the amount of shares held by an account.
*/
function shares(address account) public view returns (uint256) {
return _shares[account];
}
/**
* @dev Getter for the amount of Ether already released to a payee.
*/
function released(address account) public view returns (uint256) {
return _released[account];
}
/**
* @dev Getter for the address of the payee number `index`.
*/
function payee(uint256 index) public view returns (address) {
return _payees[index];
}
/**
* @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the
* total shares and their previous withdrawals.
*/
function release(address payable account) public virtual {
require(_shares[account] > 0, 'PaymentSplitter: account has no shares');
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[account]) /
_totalShares -
_released[account];
require(payment != 0, 'PaymentSplitter: account is not due payment');
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
/**
* @dev Add a new payee to the contract.
* @param account The address of the payee to add.
* @param shares_ The number of shares owned by the payee.
*/
function _addPayee(address account, uint256 shares_) private {
require(
account != address(0),
'PaymentSplitter: account is the zero address'
);
require(shares_ > 0, 'PaymentSplitter: shares are 0');
require(
_shares[account] == 0,
'PaymentSplitter: account already has shares'
);
_payees.push(account);
_shares[account] = shares_;
_totalShares = _totalShares + shares_;
emit PayeeAdded(account, shares_);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
import "../utils/Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Counters.sol)
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
library Counters {
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
unchecked {
counter._value += 1;
}
}
function decrement(Counter storage counter) internal {
uint256 value = counter._value;
require(value > 0, "Counter: decrement overflow");
unchecked {
counter._value = value - 1;
}
}
function reset(Counter storage counter) internal {
counter._value = 0;
}
}
// SPDX-License-Identifier: MIT
// Author: LBR Ledger
// Developed by Max J. Rux
// Dev GitHub: @TheBigMort
pragma solidity ^0.8.9;
interface ILBRLedger {
function mint(uint256 numMints) external payable;
function contractURI() external view returns (string memory);
function price() external view returns (uint256);
function reserved() external view returns (uint256);
function baseURI() external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol)
pragma solidity ^0.8.0;
import '@openzeppelin/contracts/token/ERC721/IERC721.sol';
import '@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol';
import '@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol';
import '@openzeppelin/contracts/utils/Address.sol';
import '@openzeppelin/contracts/utils/Context.sol';
import '@openzeppelin/contracts/utils/Strings.sol';
import '@openzeppelin/contracts/utils/introspection/ERC165.sol';
/**
* @dev Modified version of the ERC721 token standard that uses arrays and iteration
* instead of mappings for owners.
*/
contract ERC721M is Context, ERC165, IERC721, IERC721Metadata {
using Address for address;
using Strings for uint256;
string private _name;
string private _symbol;
address[] internal _owners;
mapping(uint256 => address) private _tokenApprovals;
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
super.supportsInterface(interfaceId);
}
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(owner != address(0), 'ERC721: balance query for the zero address');
uint256 counter = 0;
for (uint256 i = 0; i < _owners.length; ++i) {
if (_owners[i] == owner) {
++counter;
}
}
return counter;
}
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(_exists(tokenId), 'ERC721: owner query for nonexistent token');
return _owners[tokenId];
}
function name() public view virtual override returns (string memory) {
return _name;
}
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
'ERC721Metadata: URI query for nonexistent token'
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: '';
}
function _baseURI() internal view virtual returns (string memory) {
return '';
}
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721M.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);
}
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(_exists(tokenId), 'ERC721: approved query for nonexistent token');
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
_setApprovalForAll(_msgSender(), operator, approved);
}
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721: transfer caller is not owner nor approved'
);
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, '');
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
'ERC721: transfer caller is not owner nor approved'
);
_safeTransfer(from, to, tokenId, _data);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
'ERC721: transfer to non ERC721Receiver implementer'
);
}
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return tokenId >= 0 && tokenId < _owners.length;
}
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(_exists(tokenId), 'ERC721: operator query for nonexistent token');
address owner = ERC721M.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner, spender));
}
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, '');
}
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
'ERC721: transfer to non ERC721Receiver implementer'
);
}
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), 'ERC721: mint to the zero address');
require(!_exists(tokenId), 'ERC721: token already minted');
_beforeTokenTransfer(address(0), to, tokenId);
_owners.push(to);
emit Transfer(address(0), to, tokenId);
_afterTokenTransfer(address(0), to, tokenId);
}
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721M.ownerOf(tokenId);
_beforeTokenTransfer(owner, address(0), tokenId);
_approve(address(0), tokenId);
delete _owners[tokenId];
emit Transfer(owner, address(0), tokenId);
_afterTokenTransfer(owner, address(0), tokenId);
}
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721M.ownerOf(tokenId) == from,
'ERC721: transfer from incorrect owner'
);
require(to != address(0), 'ERC721: transfer to the zero address');
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_owners[tokenId] = to;
emit Transfer(from, to, tokenId);
_afterTokenTransfer(from, to, tokenId);
}
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721M.ownerOf(tokenId), to, tokenId);
}
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);
}
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;
}
}
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
function _afterTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol)
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);
/**
* @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/IERC721.sol)
pragma solidity ^0.8.0;
import "../../utils/introspection/IERC165.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface IERC721Receiver {
/**
* @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom}
* by `operator` from `from`, this function is called.
*
* It must return its Solidity selector to confirm the token transfer.
* If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted.
*
* The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
import "../IERC721.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity ^0.8.0;
// CAUTION
// This version of SafeMath should only be used with Solidity 0.8 or later,
// because it relies on the compiler's built in overflow checks.
/**
* @dev Wrappers over Solidity's arithmetic operations.
*
* NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler
* now has built in overflow checking.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b > a) return (false, 0);
return (true, a - b);
}
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a / b);
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
unchecked {
if (b == 0) return (false, 0);
return (true, a % b);
}
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
return a + b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
return a * b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator.
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b <= a, errorMessage);
return a - b;
}
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a / b;
}
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
unchecked {
require(b > 0, errorMessage);
return a % b;
}
}
} | Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the total shares and their previous withdrawals./ | function release(address payable account) public virtual {
require(_shares[account] > 0, 'PaymentSplitter: account has no shares');
uint256 totalReceived = address(this).balance + _totalReleased;
uint256 payment = (totalReceived * _shares[account]) /
_totalShares -
_released[account];
require(payment != 0, 'PaymentSplitter: account is not due payment');
_released[account] = _released[account] + payment;
_totalReleased = _totalReleased + payment;
Address.sendValue(account, payment);
emit PaymentReleased(account, payment);
}
| 14,373,066 |
./full_match/1/0x81F36c0B78D166103CfFF5D18Eec904Ff533A295/sources/contracts/Connector.sol | Sets the counterpart _counterpart The new bridge connector address/ | function setCounterpart(address _counterpart) external {
require(counterpart == address(0), "CNR: Connector address has already been set");
counterpart = _counterpart;
}
| 16,540,796 |
./partial_match/56/0x5F4F36Bc84572747C0b5D7BdF8315FD99316f672/sources/GambitKing.sol | _moveDelegates(_delegates[_from], address(0), _amount); | function burn(address _from ,uint256 _amount) public onlyOwner {
_burn(_from, _amount);
}
constructor(
GambitToken _cake
| 11,136,014 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.6.8;
pragma experimental ABIEncoderV2;
interface iERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint);
function totalSupply() external view returns (uint);
function balanceOf(address account) external view returns (uint);
function transfer(address, uint) external returns (bool);
function allowance(address owner, address spender) external view returns (uint);
function approve(address, uint) external returns (bool);
function transferFrom(address, address, uint) external returns (bool);
event Transfer(address indexed from, address indexed to, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
}
interface iBASE {
function secondsPerEra() external view returns (uint);
// function DAO() external view returns (iDAO);
}
interface iUTILS {
function calcPart(uint bp, uint total) external pure returns (uint part);
function calcShare(uint part, uint total, uint amount) external pure returns (uint share);
function calcSwapOutput(uint x, uint X, uint Y) external pure returns (uint output);
function calcSwapFee(uint x, uint X, uint Y) external pure returns (uint output);
function calcStakeUnits(uint b, uint B, uint t, uint T, uint P) external pure returns (uint units);
// function calcAsymmetricShare(uint s, uint T, uint A) external pure returns (uint share);
// function getPoolAge(address token) external view returns(uint age);
function getPoolShare(address token, uint units) external view returns(uint baseAmt, uint tokenAmt);
function getPoolShareAssym(address token, uint units, bool toBase) external view returns(uint baseAmt, uint tokenAmt, uint outputAmt);
function calcValueInBase(address token, uint amount) external view returns (uint value);
function calcValueInToken(address token, uint amount) external view returns (uint value);
function calcValueInBaseWithPool(address payable pool, uint amount) external view returns (uint value);
}
interface iDAO {
function ROUTER() external view returns(address);
function UTILS() external view returns(iUTILS);
function FUNDS_CAP() external view returns(uint);
}
// SafeMath
library SafeMath {
function add(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c >= a);
return c;
}
function mul(uint a, uint b) internal pure returns (uint) {
if (a == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, "SafeMath");
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath");
}
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath");
}
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
}
contract Pool_Vether is iERC20 {
using SafeMath for uint;
address public BASE;
address public TOKEN;
iDAO public DAO;
uint public one = 10**18;
// ERC-20 Parameters
string _name; string _symbol;
uint public override decimals; uint public override totalSupply;
// ERC-20 Mappings
mapping(address => uint) private _balances;
mapping(address => mapping(address => uint)) private _allowances;
uint public genesis;
uint public baseAmt;
uint public tokenAmt;
uint public baseAmtStaked;
uint public tokenAmtStaked;
uint public fees;
uint public volume;
uint public txCount;
// Only Router can execute
modifier onlyRouter() {
_isRouter();
_;
}
function _isRouter() internal view {
require(msg.sender == _DAO().ROUTER(), "RouterErr");
}
function _DAO() internal view returns(iDAO) {
return DAO;
}
constructor (address _base, address _token, iDAO _dao) public payable {
BASE = _base;
TOKEN = _token;
DAO = _dao;
string memory poolName = "VetherPoolV1-";
string memory poolSymbol = "VPT1-";
if(_token == address(0)){
_name = string(abi.encodePacked(poolName, "Ethereum"));
_symbol = string(abi.encodePacked(poolSymbol, "ETH"));
} else {
_name = string(abi.encodePacked(poolName, iERC20(_token).name()));
_symbol = string(abi.encodePacked(poolSymbol, iERC20(_token).symbol()));
}
decimals = 18;
genesis = now;
}
function _checkApprovals() external onlyRouter{
if(iERC20(BASE).allowance(address(this), _DAO().ROUTER()) == 0){
if(TOKEN != address(0)){
iERC20(TOKEN).approve(_DAO().ROUTER(), (2**256)-1);
}
iERC20(BASE).approve(_DAO().ROUTER(), (2**256)-1);
}
}
receive() external payable {}
//========================================iERC20=========================================//
function name() public view override returns (string memory) {
return _name;
}
function symbol() public view override returns (string memory) {
return _symbol;
}
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
// iERC20 Transfer function
function transfer(address to, uint value) public override returns (bool success) {
__transfer(msg.sender, to, value);
return true;
}
// iERC20 Approve function
function approve(address spender, uint256 amount) public virtual override returns (bool) {
__approve(msg.sender, spender, amount);
return true;
}
function __approve(address owner, address spender, uint256 amount) internal virtual {
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// iERC20 TransferFrom function
function transferFrom(address from, address to, uint value) public override returns (bool success) {
require(value <= _allowances[from][msg.sender], 'AllowanceErr');
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
__transfer(from, to, value);
return true;
}
// Internal transfer function
function __transfer(address _from, address _to, uint _value) private {
require(_balances[_from] >= _value, 'BalanceErr');
require(_balances[_to] + _value >= _balances[_to], 'BalanceErr');
_balances[_from] =_balances[_from].sub(_value);
_balances[_to] += _value;
emit Transfer(_from, _to, _value);
}
// Router can mint
function _mint(address account, uint256 amount) external onlyRouter {
totalSupply = totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
_allowances[account][DAO.ROUTER()] += amount;
emit Transfer(address(0), account, amount);
}
// Burn supply
function burn(uint256 amount) public virtual {
__burn(msg.sender, amount);
}
function burnFrom(address from, uint256 value) public virtual {
require(value <= _allowances[from][msg.sender], 'AllowanceErr');
_allowances[from][msg.sender] = _allowances[from][msg.sender].sub(value);
__burn(from, value);
}
function __burn(address account, uint256 amount) internal virtual {
_balances[account] = _balances[account].sub(amount, "BalanceErr");
totalSupply = totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
//==================================================================================//
// Extended Asset Functions
// TransferTo function
function transferTo(address recipient, uint256 amount) public returns (bool) {
__transfer(tx.origin, recipient, amount);
return true;
}
// ETH Transfer function
function transferETH(address payable to, uint value) public payable onlyRouter returns (bool success) {
to.call{value:value}("");
return true;
}
function sync() public {
if (TOKEN == address(0)) {
tokenAmt = address(this).balance;
} else {
tokenAmt = iERC20(TOKEN).balanceOf(address(this));
}
}
function add(address token, uint amount) public payable returns (bool success) {
if(token == BASE){
iERC20(BASE).transferFrom(msg.sender, address(this), amount);
baseAmt = baseAmt.add(amount);
return true;
} else if (token == TOKEN){
iERC20(TOKEN).transferFrom(msg.sender, address(this), amount);
tokenAmt = tokenAmt.add(amount);
return true;
} else if (token == address(0)){
require((amount == msg.value), "InputErr");
tokenAmt = tokenAmt.add(amount);
} else {
return false;
}
}
//==================================================================================//
// Data Model
function _incrementPoolBalances(uint _baseAmt, uint _tokenAmt) external onlyRouter {
baseAmt += _baseAmt;
tokenAmt += _tokenAmt;
baseAmtStaked += _baseAmt;
tokenAmtStaked += _tokenAmt;
}
function _setPoolBalances(uint _baseAmt, uint _tokenAmt, uint _baseAmtStaked, uint _tokenAmtStaked) external onlyRouter {
baseAmtStaked = _baseAmtStaked;
tokenAmtStaked = _tokenAmtStaked;
__setPool(_baseAmt, _tokenAmt);
}
function _setPoolAmounts(uint _baseAmt, uint _tokenAmt) external onlyRouter {
__setPool(_baseAmt, _tokenAmt);
}
function __setPool(uint _baseAmt, uint _tokenAmt) internal {
baseAmt = _baseAmt;
tokenAmt = _tokenAmt;
}
function _decrementPoolBalances(uint _baseAmt, uint _tokenAmt) external onlyRouter {
uint _unstakedBase = _DAO().UTILS().calcShare(_baseAmt, baseAmt, baseAmtStaked);
uint _unstakedToken = _DAO().UTILS().calcShare(_tokenAmt, tokenAmt, tokenAmtStaked);
baseAmtStaked = baseAmtStaked.sub(_unstakedBase);
tokenAmtStaked = tokenAmtStaked.sub(_unstakedToken);
__decrementPool(_baseAmt, _tokenAmt);
}
function __decrementPool(uint _baseAmt, uint _tokenAmt) internal {
baseAmt = baseAmt.sub(_baseAmt);
tokenAmt = tokenAmt.sub(_tokenAmt);
}
function _addPoolMetrics(uint _volume, uint _fee) external onlyRouter {
txCount += 1;
volume += _volume;
fees += _fee;
}
}
contract Router_Vether {
using SafeMath for uint;
address public BASE;
address public DEPLOYER;
iDAO public DAO;
// uint256 public currentEra;
// uint256 public nextEraTime;
// uint256 public reserve;
uint public totalStaked;
uint public totalVolume;
uint public totalFees;
uint public unstakeTx;
uint public stakeTx;
uint public swapTx;
address[] public arrayTokens;
mapping(address=>address payable) private mapToken_Pool;
mapping(address=>bool) public isPool;
event NewPool(address token, address pool, uint genesis);
event Staked(address member, uint inputBase, uint inputToken, uint unitsIssued);
event Unstaked(address member, uint outputBase, uint outputToken, uint unitsClaimed);
event Swapped(address tokenFrom, address tokenTo, uint inputAmount, uint transferAmount, uint outputAmount, uint fee, address recipient);
// event NewEra(uint256 currentEra, uint256 nextEraTime, uint256 reserve);
// Only Deployer can execute
modifier onlyDeployer() {
require(msg.sender == DEPLOYER, "DeployerErr");
_;
}
constructor () public payable {
BASE = 0x4Ba6dDd7b89ed838FEd25d208D4f644106E34279;
DEPLOYER = msg.sender;
}
receive() external payable {
buyTo(msg.value, address(0), msg.sender);
}
function setGenesisDao(address dao) public onlyDeployer {
DAO = iDAO(dao);
}
function _DAO() internal view returns(iDAO) {
return DAO;
}
function migrateRouterData(address payable oldRouter) public onlyDeployer {
totalStaked = Router_Vether(oldRouter).totalStaked();
totalVolume = Router_Vether(oldRouter).totalVolume();
totalFees = Router_Vether(oldRouter).totalFees();
unstakeTx = Router_Vether(oldRouter).unstakeTx();
stakeTx = Router_Vether(oldRouter).stakeTx();
swapTx = Router_Vether(oldRouter).swapTx();
}
function migrateTokenData(address payable oldRouter) public onlyDeployer {
uint tokenCount = Router_Vether(oldRouter).tokenCount();
for(uint i = 0; i<tokenCount; i++){
address token = Router_Vether(oldRouter).getToken(i);
address payable pool = Router_Vether(oldRouter).getPool(token);
isPool[pool] = true;
arrayTokens.push(token);
mapToken_Pool[token] = pool;
}
}
function purgeDeployer() public onlyDeployer {
DEPLOYER = address(0);
}
function createPool(uint inputBase, uint inputToken, address token) public payable returns(address payable pool){
require(getPool(token) == address(0), "CreateErr");
require(token != BASE, "Must not be Base");
require((inputToken > 0 && inputBase > 0), "Must get tokens for both");
Pool_Vether newPool = new Pool_Vether(BASE, token, DAO);
pool = payable(address(newPool));
uint _actualInputToken = _handleTransferIn(token, inputToken, pool);
uint _actualInputBase = _handleTransferIn(BASE, inputBase, pool);
mapToken_Pool[token] = pool;
arrayTokens.push(token);
isPool[pool] = true;
totalStaked += _actualInputBase;
stakeTx += 1;
uint units = _handleStake(pool, _actualInputBase, _actualInputToken, msg.sender);
emit NewPool(token, pool, now);
emit Staked(msg.sender, _actualInputBase, _actualInputToken, units);
return pool;
}
//==================================================================================//
// Staking functions
function stake(uint inputBase, uint inputToken, address token) public payable returns (uint units) {
units = stakeForMember(inputBase, inputToken, token, msg.sender);
return units;
}
function stakeForMember(uint inputBase, uint inputToken, address token, address member) public payable returns (uint units) {
address payable pool = getPool(token);
uint _actualInputToken = _handleTransferIn(token, inputToken, pool);
uint _actualInputBase = _handleTransferIn(BASE, inputBase, pool);
totalStaked += _actualInputBase;
stakeTx += 1;
require(totalStaked <= DAO.FUNDS_CAP(), "Must be less than Funds Cap");
units = _handleStake(pool, _actualInputBase, _actualInputToken, member);
emit Staked(member, _actualInputBase, _actualInputToken, units);
return units;
}
function _handleStake(address payable pool, uint _baseAmt, uint _tokenAmt, address _member) internal returns (uint _units) {
Pool_Vether(pool)._checkApprovals();
uint _B = Pool_Vether(pool).baseAmt();
uint _T = Pool_Vether(pool).tokenAmt();
uint _P = Pool_Vether(pool).totalSupply();
Pool_Vether(pool)._incrementPoolBalances(_baseAmt, _tokenAmt);
_units = _DAO().UTILS().calcStakeUnits(_baseAmt, _B, _tokenAmt, _T, _P);
Pool_Vether(pool)._mint(_member, _units);
return _units;
}
//==================================================================================//
// Unstaking functions
// Unstake % for self
function unstake(uint basisPoints, address token) public returns (bool success) {
require((basisPoints > 0 && basisPoints <= 10000), "InputErr");
uint _units = _DAO().UTILS().calcPart(basisPoints, iERC20(getPool(token)).balanceOf(msg.sender));
unstakeExact(_units, token);
return true;
}
// Unstake an exact qty of units
function unstakeExact(uint units, address token) public returns (bool success) {
address payable pool = getPool(token);
address payable member = msg.sender;
(uint _outputBase, uint _outputToken) = _DAO().UTILS().getPoolShare(token, units);
totalStaked = totalStaked.sub(_outputBase);
unstakeTx += 1;
_handleUnstake(pool, units, _outputBase, _outputToken, member);
emit Unstaked(member, _outputBase, _outputToken, units);
_handleTransferOut(token, _outputToken, pool, member);
_handleTransferOut(BASE, _outputBase, pool, member);
return true;
}
// // Unstake % Asymmetrically
function unstakeAsymmetric(uint basisPoints, bool toBase, address token) public returns (uint outputAmount){
uint _units = _DAO().UTILS().calcPart(basisPoints, iERC20(getPool(token)).balanceOf(msg.sender));
outputAmount = unstakeExactAsymmetric(_units, toBase, token);
return outputAmount;
}
// Unstake Exact Asymmetrically
function unstakeExactAsymmetric(uint units, bool toBase, address token) public returns (uint outputAmount){
address payable pool = getPool(token);
require(units < iERC20(pool).totalSupply(), "InputErr");
(uint _outputBase, uint _outputToken, uint _outputAmount) = _DAO().UTILS().getPoolShareAssym(token, units, toBase);
totalStaked = totalStaked.sub(_outputBase);
unstakeTx += 1;
_handleUnstake(pool, units, _outputBase, _outputToken, msg.sender);
emit Unstaked(msg.sender, _outputBase, _outputToken, units);
_handleTransferOut(token, _outputToken, pool, msg.sender);
_handleTransferOut(BASE, _outputBase, pool, msg.sender);
return _outputAmount;
}
function _handleUnstake(address payable pool, uint _units, uint _outputBase, uint _outputToken, address _member) internal returns (bool success) {
Pool_Vether(pool)._checkApprovals();
Pool_Vether(pool)._decrementPoolBalances(_outputBase, _outputToken);
Pool_Vether(pool).burnFrom(_member, _units);
return true;
}
//==================================================================================//
// Universal Swapping Functions
function buy(uint amount, address token) public payable returns (uint outputAmount, uint fee){
(outputAmount, fee) = buyTo(amount, token, msg.sender);
return (outputAmount, fee);
}
function buyTo(uint amount, address token, address payable member) public payable returns (uint outputAmount, uint fee) {
address payable pool = getPool(token);
Pool_Vether(pool)._checkApprovals();
uint _actualAmount = _handleTransferIn(BASE, amount, pool);
// uint _minusFee = _getFeeBase(_actualAmount, token);
(outputAmount, fee) = _swapBaseToToken(pool, _actualAmount);
// processFee(BASE);
totalStaked += _actualAmount;
totalVolume += _actualAmount;
totalFees += _DAO().UTILS().calcValueInBase(token, fee);
swapTx += 1;
_handleTransferOut(token, outputAmount, pool, member);
emit Swapped(BASE, token, _actualAmount, 0, outputAmount, fee, member);
return (outputAmount, fee);
}
// function _getFeeBase(uint _x, address payable _pool) private view returns(uint){
// uint _X = Pool_Vether(_pool).baseAmt();
// uint _feeShare = Dao_Vether.feeShare();
// uint _fee = UTILS.calcSwapInputFee(_x, _X).div(_feeShare);
// return _X.sub(_fee);
// }
function sell(uint amount, address token) public payable returns (uint outputAmount, uint fee){
(outputAmount, fee) = sellTo(amount, token, msg.sender);
return (outputAmount, fee);
}
function sellTo(uint amount, address token, address payable member) public payable returns (uint outputAmount, uint fee) {
address payable pool = getPool(token);
Pool_Vether(pool)._checkApprovals();
uint _actualAmount = _handleTransferIn(token, amount, pool);
(outputAmount, fee) = _swapTokenToBase(pool, _actualAmount);
// addDividend(pool, outputAmount, fee);
totalStaked = totalStaked.sub(outputAmount);
totalVolume += outputAmount;
totalFees += fee;
swapTx += 1;
_handleTransferOut(BASE, outputAmount, pool, member);
emit Swapped(token, BASE, _actualAmount, 0, outputAmount, fee, member);
return (outputAmount, fee);
}
function swap(uint inputAmount, address fromToken, address toToken) public payable returns (uint outputAmount, uint fee) {
require(fromToken != toToken, "InputErr");
address payable poolFrom = getPool(fromToken); address payable poolTo = getPool(toToken);
Pool_Vether(poolFrom)._checkApprovals();
Pool_Vether(poolTo)._checkApprovals();
uint _actualAmount = _handleTransferIn(fromToken, inputAmount, poolFrom);
uint _transferAmount = 0;
if(fromToken == BASE){
(outputAmount, fee) = _swapBaseToToken(poolFrom, _actualAmount); // Buy to token
totalStaked += _actualAmount;
totalVolume += _actualAmount;
// addDividend(poolFrom, outputAmount, fee);
} else if(toToken == BASE) {
(outputAmount, fee) = _swapTokenToBase(poolFrom,_actualAmount); // Sell to token
totalStaked = totalStaked.sub(outputAmount);
totalVolume += outputAmount;
// addDividend(poolFrom, outputAmount, fee);
} else {
(uint _yy, uint _feey) = _swapTokenToBase(poolFrom, _actualAmount); // Sell to BASE
uint _actualYY = _handleTransferOver(BASE, poolFrom, poolTo, _yy);
totalStaked = totalStaked.add(_actualYY).sub(_actualAmount);
totalVolume += _yy; totalFees += _feey;
// addDividend(poolFrom, _yy, _feey);
(uint _zz, uint _feez) = _swapBaseToToken(poolTo, _actualYY); // Buy to token
totalFees += _DAO().UTILS().calcValueInBase(toToken, _feez);
// addDividend(poolTo, _zz, _feez);
_transferAmount = _actualYY; outputAmount = _zz;
fee = _feez + _DAO().UTILS().calcValueInToken(toToken, _feey);
}
swapTx += 1;
_handleTransferOut(toToken, outputAmount, poolTo, msg.sender);
emit Swapped(fromToken, toToken, _actualAmount, _transferAmount, outputAmount, fee, msg.sender);
return (outputAmount, fee);
}
function _swapBaseToToken(address payable pool, uint _x) internal returns (uint _y, uint _fee){
uint _X = Pool_Vether(pool).baseAmt();
uint _Y = Pool_Vether(pool).tokenAmt();
_y = _DAO().UTILS().calcSwapOutput(_x, _X, _Y);
_fee = _DAO().UTILS().calcSwapFee(_x, _X, _Y);
Pool_Vether(pool)._setPoolAmounts(_X.add(_x), _Y.sub(_y));
_updatePoolMetrics(pool, _y+_fee, _fee, false);
// _checkEmission();
return (_y, _fee);
}
function _swapTokenToBase(address payable pool, uint _x) internal returns (uint _y, uint _fee){
uint _X = Pool_Vether(pool).tokenAmt();
uint _Y = Pool_Vether(pool).baseAmt();
_y = _DAO().UTILS().calcSwapOutput(_x, _X, _Y);
_fee = _DAO().UTILS().calcSwapFee(_x, _X, _Y);
Pool_Vether(pool)._setPoolAmounts(_Y.sub(_y), _X.add(_x));
_updatePoolMetrics(pool, _y+_fee, _fee, true);
// _checkEmission();
return (_y, _fee);
}
function _updatePoolMetrics(address payable pool, uint _txSize, uint _fee, bool _toBase) internal {
if(_toBase){
Pool_Vether(pool)._addPoolMetrics(_txSize, _fee);
} else {
uint _txBase = _DAO().UTILS().calcValueInBaseWithPool(pool, _txSize);
uint _feeBase = _DAO().UTILS().calcValueInBaseWithPool(pool, _fee);
Pool_Vether(pool)._addPoolMetrics(_txBase, _feeBase);
}
}
//==================================================================================//
// Revenue Functions
// Every swap, calculate fee, add to reserve
// Every era, send reserve to DAO
// function _checkEmission(address token) private {
// if (now >= nextEraTime) { // If new Era and allowed to emit
// currentEra += 1; // Increment Era
// nextEraTime = now + iBASE(token).secondsPerEra() + 100; // Set next Era time
// uint reserve = iERC20(token).balanceOf(address(this));
// iERC20(token).transfer(address(_DAO()), reserve);
// emit NewEra(currentEra, nextEraTime, reserve); // Emit Event
// }
// }
// function processFee(address token) public {
// uint balance = iERC20(token).balanceOf(address(this));
// if(token == BASE){
// iERC20(token).transfer(address(_DAO()), balance);
// } else {
// }
// }
//==================================================================================//
// Token Transfer Functions
function _handleTransferIn(address _token, uint _amount, address _pool) internal returns(uint actual){
if(_amount > 0) {
if(_token == address(0)){
require((_amount == msg.value), "InputErr");
payable(_pool).call{value:_amount}("");
actual = _amount;
} else {
uint startBal = iERC20(_token).balanceOf(_pool);
iERC20(_token).transferFrom(msg.sender, _pool, _amount);
actual = iERC20(_token).balanceOf(_pool).sub(startBal);
}
}
}
function _handleTransferOut(address _token, uint _amount, address _pool, address payable _recipient) internal {
if(_amount > 0) {
if (_token == address(0)) {
Pool_Vether(payable(_pool)).transferETH(_recipient, _amount);
} else {
iERC20(_token).transferFrom(_pool, _recipient, _amount);
}
}
}
function _handleTransferOver(address _token, address _from, address _to, uint _amount) internal returns(uint actual){
if(_amount > 0) {
uint startBal = iERC20(_token).balanceOf(_to);
iERC20(_token).transferFrom(_from, _to, _amount);
actual = iERC20(_token).balanceOf(_to).sub(startBal);
}
}
//======================================HELPERS========================================//
// Helper Functions
function getPool(address token) public view returns(address payable pool){
return mapToken_Pool[token];
}
function tokenCount() public view returns(uint){
return arrayTokens.length;
}
function getToken(uint i) public view returns(address){
return arrayTokens[i];
}
} | iERC20 Approve function | function approve(address spender, uint256 amount) public virtual override returns (bool) {
__approve(msg.sender, spender, amount);
return true;
}
| 51,532 |
pragma solidity ^0.5.12;
library SafeMath {
function MUL98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0)
return 0;
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV107(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0);
uint256 c = a / b;
return c;
}
function SUB705(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD235(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD157(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
contract ERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowed;
event TRANSFER731(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL787(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
uint256 internal _totalSupply;
function TOTALSUPPLY882() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF767(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE10(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER204(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER522(msg.sender, to, value);
return true;
}
function APPROVE277(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_allowed[msg.sender][spender] = value;
emit APPROVAL787(msg.sender, spender, value);
return true;
}
function TRANSFERFROM832(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER522(from, to, value);
_allowed[msg.sender][to] = _allowed[msg.sender][to].SUB705(value);
return true;
}
function _TRANSFER522(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB705(value);
_balances[to] = _balances[to].ADD235(value);
emit TRANSFER731(from, to, value);
}
}
contract ERC20Mintable is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function _MINT321(address to, uint256 amount) internal { //inject NONSTANDARD NAMING
_balances[to] = _balances[to].ADD235(amount);
_totalSupply = _totalSupply.ADD235(amount);
emit TRANSFER731(address(0), to, amount);
}
function _BURN441(address from, uint256 amount) internal { //inject NONSTANDARD NAMING
_balances[from] = _balances[from].SUB705(amount);
_totalSupply = _totalSupply.SUB705(amount);
emit TRANSFER731(from, address(0), amount);
}
}
// ----------- Aave ----------------
contract ILendingPoolAddressesProvider {
function GETLENDINGPOOL38() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLIMPL881(address _pool) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLCORE21() public view returns (address payable); //inject NONSTANDARD NAMING
function SETLENDINGPOOLCOREIMPL156(address _lendingPoolCore) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLCONFIGURATOR254() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLCONFIGURATORIMPL555(address _configurator) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLDATAPROVIDER61() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLDATAPROVIDERIMPL193(address _provider) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLPARAMETERSPROVIDER362() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLPARAMETERSPROVIDERIMPL978(address _parametersProvider) public; //inject NONSTANDARD NAMING
function GETTOKENDISTRIBUTOR827() public view returns (address); //inject NONSTANDARD NAMING
function SETTOKENDISTRIBUTOR348(address _tokenDistributor) public; //inject NONSTANDARD NAMING
function GETFEEPROVIDER168() public view returns (address); //inject NONSTANDARD NAMING
function SETFEEPROVIDERIMPL718(address _feeProvider) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLLIQUIDATIONMANAGER82() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLLIQUIDATIONMANAGER708(address _manager) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLMANAGER762() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLMANAGER882(address _lendingPoolManager) public; //inject NONSTANDARD NAMING
function GETPRICEORACLE485() public view returns (address); //inject NONSTANDARD NAMING
function SETPRICEORACLE428(address _priceOracle) public; //inject NONSTANDARD NAMING
function GETLENDINGRATEORACLE592() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGRATEORACLE655(address _lendingRateOracle) public; //inject NONSTANDARD NAMING
}
interface ILendingPool {
function ADDRESSESPROVIDER344() external view returns(address); //inject NONSTANDARD NAMING
function DEPOSIT818(address _reserve, uint256 _amount, uint16 _referralCode) external payable; //inject NONSTANDARD NAMING
function REDEEMUNDERLYING805(address _reserve, address _user, uint256 _amount) external; //inject NONSTANDARD NAMING
function BORROW264(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external; //inject NONSTANDARD NAMING
function REPAY662(address _reserve, uint256 _amount, address _onBehalfOf) external payable; //inject NONSTANDARD NAMING
function SWAPBORROWRATEMODE766(address _reserve) external; //inject NONSTANDARD NAMING
function REBALANCEFIXEDBORROWRATE627(address _reserve, address _user) external; //inject NONSTANDARD NAMING
function SETUSERUSERESERVEASCOLLATERAL986(address _reserve, bool _useAsCollateral) external; //inject NONSTANDARD NAMING
function LIQUIDATIONCALL807(address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken) external payable; //inject NONSTANDARD NAMING
function FLASHLOAN206(address _receiver, address _reserve, uint256 _amount, bytes calldata _params) external; //inject NONSTANDARD NAMING
function GETRESERVECONFIGURATIONDATA59(address _reserve) external view returns(uint256 ltv, uint256 liquidationThreshold, uint256 liquidationDiscount, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool fixedBorrowRateEnabled, bool isActive); //inject NONSTANDARD NAMING
function GETRESERVEDATA692(address _reserve) external view returns(uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsFixed, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 fixedBorrowRate, uint256 averageFixedBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp); //inject NONSTANDARD NAMING
function GETUSERACCOUNTDATA811(address _user) external view returns(uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor); //inject NONSTANDARD NAMING
function GETUSERRESERVEDATA732(address _reserve, address _user) external view returns(uint256 currentATokenBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled); //inject NONSTANDARD NAMING
function GETRESERVES689() external view; //inject NONSTANDARD NAMING
}
interface ILendingPoolCore {
function GETRESERVEATOKENADDRESS314(address _reserve) external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVECURRENTVARIABLEBORROWRATE762(address _token) external view returns (uint256); //inject NONSTANDARD NAMING
function GETRESERVECURRENTLIQUIDITYRATE636(address _token) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface IAavePriceOracleGetter {
function GETASSETPRICE734(address _asset) external view returns (uint256); //inject NONSTANDARD NAMING
function GETASSETSPRICES996(address[] calldata _assets) external view returns(uint256[] memory); //inject NONSTANDARD NAMING
function GETSOURCEOFASSET324(address _asset) external view returns(address); //inject NONSTANDARD NAMING
function GETFALLBACKORACLE535() external view returns(address); //inject NONSTANDARD NAMING
}
interface IAToken {
function REDIRECTINTERESTSTREAM242(address _to) external; //inject NONSTANDARD NAMING
function REDIRECTINTERESTSTREAMOF292(address _from, address _to) external; //inject NONSTANDARD NAMING
function ALLOWINTERESTREDIRECTIONTO292(address _to) external; //inject NONSTANDARD NAMING
function REDEEM632(uint256 _amount) external; //inject NONSTANDARD NAMING
function PRINCIPALBALANCEOF100(address _user) external view returns(uint256); //inject NONSTANDARD NAMING
function ISTRANSFERALLOWED396(address _user, uint256 _amount) external view returns (bool); //inject NONSTANDARD NAMING
function GETUSERINDEX768(address _user) external view returns(uint256); //inject NONSTANDARD NAMING
function GETINTERESTREDIRECTIONADDRESS228(address _user) external view returns(address); //inject NONSTANDARD NAMING
function GETREDIRECTEDBALANCE288(address _user) external view returns(uint256); //inject NONSTANDARD NAMING
function TOTALSUPPLY882() external view returns (uint256 supply); //inject NONSTANDARD NAMING
function BALANCEOF767(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING
function TRANSFER204(address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function TRANSFERFROM832(address _from, address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function APPROVE277(address _spender, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function ALLOWANCE10(address _owner, address _spender) external view returns (uint256 remaining); //inject NONSTANDARD NAMING
function NAME858() external view returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL894() external view returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS454() external view returns (uint8); //inject NONSTANDARD NAMING
}
interface PriceOracle {
function GETUNDERLYINGPRICE929(address) external view returns (uint256); //inject NONSTANDARD NAMING
}
// ---------- Compound ----------
interface CErc20 {
function BORROW264(uint256) external returns (uint256); //inject NONSTANDARD NAMING
function BORROWRATEPERBLOCK388() external view returns (uint256); //inject NONSTANDARD NAMING
function BORROWBALANCECURRENT444(address) external returns (uint256); //inject NONSTANDARD NAMING
function REPAYBORROW515(uint256) external returns (uint256); //inject NONSTANDARD NAMING
}
interface CEth {
function MINT397() external payable; //inject NONSTANDARD NAMING
function REDEEMUNDERLYING805(uint redeemAmount) external returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFUNDERLYING788(address owner) external returns (uint256); //inject NONSTANDARD NAMING
function SUPPLYRATEPERBLOCK15() external view returns (uint256); //inject NONSTANDARD NAMING
}
interface Comptroller {
function MARKETS249(address) external returns (bool, uint256); //inject NONSTANDARD NAMING
function ENTERMARKETS82(address[] calldata) //inject NONSTANDARD NAMING
external
returns (uint256[] memory);
function GETACCOUNTLIQUIDITY384(address) //inject NONSTANDARD NAMING
external
view
returns (uint256, uint256, uint256);
function ORACLE168() external view returns(address); //inject NONSTANDARD NAMING
}
// ---------- kyber ----------
interface Exchange {
function TRADE301( //inject NONSTANDARD NAMING
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId )external payable returns(uint);
}
// -----tCDP-----
contract tCDPConstants {
uint256 constant dust264 = 1e6; // minimum mint amount //inject NONSTANDARD NAMING
ERC20 constant dai445 = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI(debt) token address //inject NONSTANDARD NAMING
//Compound
Comptroller constant comptroller75 = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); //inject NONSTANDARD NAMING
CEth constant ceth501 = CEth(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); //inject NONSTANDARD NAMING
CErc20 constant cdai61 = CErc20(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); //inject NONSTANDARD NAMING
//AAVE
ILendingPoolAddressesProvider constant addressesprovider654 = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); //inject NONSTANDARD NAMING
uint16 constant referral215 = 47; // TODO: apply new referral code //inject NONSTANDARD NAMING
//Kyber
Exchange constant kybernetwork927 = Exchange(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); //inject NONSTANDARD NAMING
address constant etheraddr36 = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //inject NONSTANDARD NAMING
address constant ref472 = 0xD0533664013a82c31584B7FFDB215139f38Ad77A; //inject NONSTANDARD NAMING
//rebalance target/boundary/size
uint256 constant targetratio559 = 0.4e18; //40% //inject NONSTANDARD NAMING
uint256 constant upperbound23 = 444444444444444444; // 1/225% //inject NONSTANDARD NAMING
uint256 constant lowerbound414 = 363636363636363636; // 1/275% //inject NONSTANDARD NAMING
uint256 constant bite558 = 0.025 * 1e18; //2.5% //inject NONSTANDARD NAMING
}
contract tCDP is ERC20Mintable, tCDPConstants{
using SafeMath for *;
bool public isCompound;
event MIGRATION431(uint8); // 0x01 = to Compound, 0x02 = to Aave //inject NONSTANDARD NAMING
constructor() public {
symbol = "tETH-DAI";
name = "tokenized CDP ETH-DAI v1";
decimals = 18;
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
dai445.APPROVE277(lendingPoolCoreAddress, uint256(-1));
dai445.APPROVE277(address(cdai61), uint256(-1));
address[] memory cTokens = new address[](1);
cTokens[0] = address(ceth501);
uint256[] memory errors = comptroller75.ENTERMARKETS82(cTokens);
require(errors[0] == 0, "Comptroller.enterMarkets failed.");
dai445.APPROVE277(address(kybernetwork927), uint256(-1));
isCompound = FINDBESTRATE616();
}
function INITIATE270(uint256 amount) external payable { //inject NONSTANDARD NAMING
require(_totalSupply < dust264, "initiated");
require(msg.value > dust264, "value too small");
if(isCompound) {
ceth501.MINT397.value(msg.value)();
_MINT321(msg.sender, msg.value);
require(cdai61.BORROW264(amount) == 0, "borrow failed");
dai445.TRANSFER204(msg.sender, amount);
}
else {
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.DEPOSIT818.value(msg.value)(etheraddr36, msg.value, referral215);
_MINT321(msg.sender, msg.value);
lendingPool.BORROW264(address(dai445), amount, 2, referral215);
dai445.TRANSFER204(msg.sender, amount);
}
}
function COLLATERAL797() public returns(uint256) { //inject NONSTANDARD NAMING
if(isCompound) {
return ceth501.BALANCEOFUNDERLYING788(address(this));
}
else {
address lendingPoolCore = addressesprovider654.GETLENDINGPOOLCORE21();
address aETH = ILendingPoolCore(lendingPoolCore).GETRESERVEATOKENADDRESS314(etheraddr36);
return IAToken(aETH).BALANCEOF767(address(this));
}
}
function DEBT567() public returns(uint256) { //inject NONSTANDARD NAMING
if(isCompound) {
return cdai61.BORROWBALANCECURRENT444(address(this));
}
else {
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
(, uint256 borrowBalance,,,,,,,,) = lendingPool.GETUSERRESERVEDATA732(address(dai445), address(this));
return borrowBalance;
}
}
function MINT397() external payable returns(uint256) { //inject NONSTANDARD NAMING
require(_totalSupply >= dust264, "not initiated");
uint256 amount = msg.value;
uint256 tokenToMint = _totalSupply.MUL98(amount).DIV107(COLLATERAL797());
uint256 tokenToBorrow = DEBT567().MUL98(amount).DIV107(COLLATERAL797());
_MINT321(msg.sender, tokenToMint);
if(isCompound) {
ceth501.MINT397.value(amount)();
require(cdai61.BORROW264(tokenToBorrow) == 0, "borrow failed");
dai445.TRANSFER204(msg.sender, tokenToBorrow);
}
else{
// deposit
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.DEPOSIT818.value(amount)(etheraddr36, amount, referral215);
// borrow
lendingPool.BORROW264(address(dai445), tokenToBorrow, 2, referral215);
// transfer
dai445.TRANSFER204(msg.sender, tokenToBorrow);
}
return tokenToMint;
}
function BURN250(uint256 amount) external { //inject NONSTANDARD NAMING
uint256 tokenToRepay = amount.MUL98(DEBT567()).DIV107(_totalSupply);
uint256 tokenToDraw = amount.MUL98(COLLATERAL797()).DIV107(_totalSupply);
_BURN441(msg.sender, amount);
dai445.TRANSFERFROM832(msg.sender, address(this), tokenToRepay);
if(isCompound) {
require(cdai61.REPAYBORROW515(tokenToRepay) == 0, "repay failed");
require(ceth501.REDEEMUNDERLYING805(tokenToDraw) == 0, "redeem failed");
}
else {
// repay
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
// Dai.approve(lendingPoolCoreAddress, tokenToRepay);
lendingPool.REPAY662(address(dai445), tokenToRepay, address(this));
// redeem
IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36));
aETH.REDEEM632(tokenToDraw);
}
(bool success, ) = msg.sender.call.value(tokenToDraw)("");
require(success, "Failed to transfer ether to msg.sender");
}
function() external payable{}
//true if (cEth APR - cDai APR) >= (aEth APR - aDai APR), otherwise, false
function FINDBESTRATE616() public view returns (bool) { //inject NONSTANDARD NAMING
return AAVEDAIAPR797().MUL98(targetratio559).DIV107(1e18).ADD235(COMPOUNDETHAPR912()) > COMPOUNDDAIAPR961().MUL98(targetratio559).DIV107(1e18).ADD235(AAVEETHAPR160());
}
function COMPOUNDDAIAPR961() public view returns (uint256) { //inject NONSTANDARD NAMING
return cdai61.BORROWRATEPERBLOCK388().MUL98(2102400);
}
function COMPOUNDETHAPR912() public view returns (uint256) { //inject NONSTANDARD NAMING
return ceth501.SUPPLYRATEPERBLOCK15().MUL98(2102400);
}
function AAVEDAIAPR797() public view returns (uint256) { //inject NONSTANDARD NAMING
ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21());
return core.GETRESERVECURRENTVARIABLEBORROWRATE762(address(dai445)).DIV107(1e9);
}
function AAVEETHAPR160() public view returns (uint256) { //inject NONSTANDARD NAMING
ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21());
return core.GETRESERVECURRENTLIQUIDITYRATE636(etheraddr36).DIV107(1e9);
}
function GETUNDERLYINGPRICE929() public view returns(uint256) { //inject NONSTANDARD NAMING
uint256 price;
if(isCompound) {
address oracle = comptroller75.ORACLE168();
PriceOracle priceOracle = PriceOracle(oracle);
price = priceOracle.GETUNDERLYINGPRICE929(address(cdai61));
}
else {
address oracleAddress = addressesprovider654.GETPRICEORACLE485();
IAavePriceOracleGetter priceOracle = IAavePriceOracleGetter(oracleAddress);
price = priceOracle.GETASSETPRICE734(address(dai445));
}
return price;
}
function DEBTRATIO670() public returns (uint256) { //inject NONSTANDARD NAMING
uint256 price = GETUNDERLYINGPRICE929();
uint256 ratio = DEBT567().MUL98(price).DIV107(COLLATERAL797());
return ratio;
}
function DELEVERAGE904() external { //inject NONSTANDARD NAMING
require(_totalSupply >= dust264, "not initiated");
require(DEBTRATIO670() > upperbound23, "debt ratio is good");
uint256 amount = COLLATERAL797().MUL98(bite558).DIV107(1e18);
if(isCompound) {
require(ceth501.REDEEMUNDERLYING805(amount) == 0, "redeem failed");
uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472);
require(cdai61.REPAYBORROW515(income) == 0, "repay failed");
}
else {
// redeem
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36));
aETH.REDEEM632(amount);
uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472);
// repay
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
// Dai.approve(lendingPoolCoreAddress, income);
lendingPool.REPAY662(address(dai445), income, address(this));
}
}
function LEVERAGE920() external { //inject NONSTANDARD NAMING
require(_totalSupply >= dust264, "not initiated");
require(DEBTRATIO670() < lowerbound414, "debt ratio is good");
uint256 amount = DEBT567().MUL98(bite558).DIV107(1e18);
if(isCompound) {
require(cdai61.BORROW264(amount) == 0, "borrow failed");
uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472);
ceth501.MINT397.value(income)();
}
else {
// borrow
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.BORROW264(address(dai445), amount, 2, referral215);
uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472);
// deposit
lendingPool.DEPOSIT818.value(income)(etheraddr36, income, referral215);
}
}
function MIGRATE814() external { //inject NONSTANDARD NAMING
if(FINDBESTRATE616() != isCompound) {
uint256 _debt = DEBT567();
uint256 _collateral = COLLATERAL797();
dai445.TRANSFERFROM832(msg.sender, address(this), _debt);
uint256 newBorrow = _debt.ADD235(2);
if(isCompound) {
require(cdai61.REPAYBORROW515(_debt) == 0, "borrow failed");
require(ceth501.REDEEMUNDERLYING805(_collateral) == 0, "redeem failed");
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.DEPOSIT818.value(_collateral)(etheraddr36, _collateral, referral215);
lendingPool.BORROW264(address(dai445), newBorrow, 2, referral215);
isCompound = false;
emit MIGRATION431(0x02);
}
else {
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
lendingPool.REPAY662(address(dai445), _debt, address(this));
IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36));
aETH.REDEEM632(_collateral);
ceth501.MINT397.value(_collateral)();
require(cdai61.BORROW264(newBorrow) == 0, "borrow failed");
isCompound = true;
emit MIGRATION431(0x01);
}
dai445.TRANSFER204(msg.sender, newBorrow);
}
}
} | inject NONSTANDARD NAMING | function MINT397() external payable; | 5,544,617 |
// File @animoca/ethereum-contracts-erc20_base/contracts/token/ERC20/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
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.
*/
// SPDX-License-Identifier: MIT
pragma solidity 0.6.8;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @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 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);
}
// File @animoca/ethereum-contracts-core_library/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumMap for EnumMap.Map;
*
* // Declare a set state variable
* EnumMap.Map private myMap;
* }
* ```
*/
library EnumMap {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// This means that we can only create new EnumMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 key;
bytes32 value;
}
struct Map {
// Storage of map keys and values
MapEntry[] entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping (bytes32 => uint256) indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(Map storage map, bytes32 key, bytes32 value) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map.indexes[key];
if (keyIndex == 0) { // Equivalent to !contains(map, key)
map.entries.push(MapEntry({ key: key, value: value }));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map.indexes[key] = map.entries.length;
return true;
} else {
map.entries[keyIndex - 1].value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(Map storage map, bytes32 key) internal returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map.indexes[key];
if (keyIndex != 0) { // Equivalent to contains(map, key)
// To delete a key-value pair from the entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map.entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map.entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map.entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map.indexes[lastEntry.key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map.entries.pop();
// Delete the index for the deleted slot
delete map.indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(Map storage map, bytes32 key) internal view returns (bool) {
return map.indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function length(Map storage map) internal view returns (uint256) {
return map.entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Map storage map, uint256 index) internal view returns (bytes32, bytes32) {
require(map.entries.length > index, "EnumMap: index out of bounds");
MapEntry storage entry = map.entries[index];
return (entry.key, entry.value);
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(Map storage map, bytes32 key) internal view returns (bytes32) {
uint256 keyIndex = map.indexes[key];
require(keyIndex != 0, "EnumMap: nonexistent key"); // Equivalent to contains(map, key)
return map.entries[keyIndex - 1].value; // All indexes are 1-based
}
}
// File @animoca/ethereum-contracts-core_library/contracts/algo/[email protected]
/*
https://github.com/OpenZeppelin/openzeppelin-contracts
The MIT License (MIT)
Copyright (c) 2016-2019 zOS Global Limited
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
pragma solidity 0.6.8;
/**
* @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 EnumSet for EnumSet.Set;
*
* // Declare a set state variable
* EnumSet.Set private mySet;
* }
* ```
*/
library EnumSet {
// 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.
// 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) internal 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) internal 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) internal view returns (bool) {
return set.indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(Set storage set) internal 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) internal view returns (bytes32) {
require(set.values.length > index, "EnumSet: index out of bounds");
return set.values[index];
}
}
// File @openzeppelin/contracts/GSN/[email protected]
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/[email protected]
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 @animoca/ethereum-contracts-core_library/contracts/payment/[email protected]
pragma solidity 0.6.8;
/**
@title PayoutWallet
@dev adds support for a payout wallet
Note: .
*/
contract PayoutWallet is Ownable
{
event PayoutWalletSet(address payoutWallet_);
address payable public payoutWallet;
constructor(address payoutWallet_) internal {
setPayoutWallet(payoutWallet_);
}
function setPayoutWallet(address payoutWallet_) public onlyOwner {
require(payoutWallet_ != address(0), "The payout wallet must not be the zero address");
require(payoutWallet_ != address(this), "The payout wallet must not be the contract itself");
require(payoutWallet_ != payoutWallet, "The payout wallet must be different");
payoutWallet = payable(payoutWallet_);
emit PayoutWalletSet(payoutWallet);
}
}
// File @animoca/ethereum-contracts-core_library/contracts/utils/[email protected]
pragma solidity 0.6.8;
/**
* Contract module which allows derived contracts to implement a mechanism for
* activating, or 'starting', a contract.
*
* This module is used through inheritance. It will make available the modifiers
* `whenNotStarted` and `whenStarted`, which can be applied to the functions of
* your contract. Those functions will only be 'startable' once the modifiers
* are put in place.
*/
contract Startable is Context {
event Started(address account);
uint256 private _startedAt;
/**
* Modifier to make a function callable only when the contract has not started.
*/
modifier whenNotStarted() {
require(_startedAt == 0, "Startable: started");
_;
}
/**
* Modifier to make a function callable only when the contract has started.
*/
modifier whenStarted() {
require(_startedAt != 0, "Startable: not started");
_;
}
/**
* Constructor.
*/
constructor () internal {}
/**
* Returns the timestamp when the contract entered the started state.
* @return The timestamp when the contract entered the started state.
*/
function startedAt() public view returns (uint256) {
return _startedAt;
}
/**
* Triggers the started state.
* @dev Emits the Started event when the function is successfully called.
*/
function _start() internal virtual whenNotStarted {
_startedAt = now;
emit Started(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.6.0;
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
contract Pausable is Context {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
constructor () internal {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!_paused, "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(_paused, "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
}
// File @openzeppelin/contracts/utils/[email protected]
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/math/[email protected]
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 @animoca/ethereum-contracts-sale_base/contracts/sale/interfaces/[email protected]
pragma solidity 0.6.8;
/**
* @title ISale
*
* An interface for a contract which allows merchants to display products and customers to purchase them.
*
* Products, designated as SKUs, are represented by bytes32 identifiers so that an identifier can carry an
* explicit name under the form of a fixed-length string. Each SKU can be priced via up to several payment
* tokens which can be ETH and/or ERC20(s). ETH token is represented by the magic value TOKEN_ETH, which means
* this value can be used as the 'token' argument of the purchase-related functions to indicate ETH payment.
*
* The total available supply for a SKU is fixed at its creation. The magic value SUPPLY_UNLIMITED is used
* to represent a SKU with an infinite, never-decreasing supply. An optional purchase notifications receiver
* contract address can be set for a SKU at its creation: if the value is different from the zero address,
* the function `onPurchaseNotificationReceived` will be called on this address upon every purchase of the SKU.
*
* This interface is designed to be consistent while managing a variety of implementation scenarios. It is
* also intended to be developer-friendly: all vital information is consistently deductible from the events
* (backend-oriented), as well as retrievable through calls to public functions (frontend-oriented).
*/
interface ISale {
/**
* Event emitted to notify about the magic values necessary for interfacing with this contract.
* @param names An array of names for the magic values used by the contract.
* @param values An array of values for the magic values used by the contract.
*/
event MagicValues(bytes32[] names, bytes32[] values);
/**
* Event emitted to notify about the creation of a SKU.
* @param sku The identifier of the created SKU.
* @param totalSupply The initial total supply for sale.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver If not the zero address, the address of a contract on which `onPurchaseNotificationReceived` will be called after each purchase,
* If this is the zero address, the call is not enabled.
*/
event SkuCreation(bytes32 sku, uint256 totalSupply, uint256 maxQuantityPerPurchase, address notificationsReceiver);
/**
* Event emitted to notify about a change in the pricing of a SKU.
* @dev `tokens` and `prices` arrays MUST have the same length.
* @param sku The identifier of the updated SKU.
* @param tokens An array of updated payment tokens. If empty, interpret as all payment tokens being disabled.
* @param prices An array of updated prices for each of the payment tokens.
* Zero price values are used for payment tokens being disabled.
*/
event SkuPricingUpdate(bytes32 indexed sku, address[] tokens, uint256[] prices);
/**
* Event emitted to notify about a purchase.
* @param purchaser The initiater and buyer of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token used as the currency for the payment.
* @param sku The identifier of the purchased SKU.
* @param quantity The purchased quantity.
* @param userData Optional extra user input data.
* @param totalPrice The amount of `token` paid.
* @param pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* @param paymentData Implementation-specific extra payment data, such as conversion rates.
* @param deliveryData Implementation-specific extra delivery data, such as purchase receipts.
*/
event Purchase(
address indexed purchaser,
address recipient,
address indexed token,
bytes32 indexed sku,
uint256 quantity,
bytes userData,
uint256 totalPrice,
bytes32[] pricingData,
bytes32[] paymentData,
bytes32[] deliveryData
);
/**
* Returns the magic value used to represent the ETH payment token.
* @dev MUST NOT be the zero address.
* @return the magic value used to represent the ETH payment token.
*/
function TOKEN_ETH() external pure returns (address);
/**
* Returns the magic value used to represent an infinite, never-decreasing SKU's supply.
* @dev MUST NOT be zero.
* @return the magic value used to represent an infinite, never-decreasing SKU's supply.
*/
function SUPPLY_UNLIMITED() external pure returns (uint256);
/**
* Performs a purchase.
* @dev Reverts if `token` is the address zero.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external payable;
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price to pay.
* @return pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* If not empty, the implementer MUST document how to interepret the values.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external view returns (uint256 totalPrice, bytes32[] memory pricingData);
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @dev Reverts if `sku` does not exist.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
view
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
);
/**
* Returns the list of created SKU identifiers.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of SKUs is bounded, so that this function does not run out of gas.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external view returns (bytes32[] memory skus);
}
// File @animoca/ethereum-contracts-sale_base/contracts/sale/interfaces/[email protected]
pragma solidity 0.6.8;
/**
* @title IPurchaseNotificationsReceiver
* Interface for any contract that wants to support purchase notifications from a Sale contract.
*/
interface IPurchaseNotificationsReceiver {
/**
* Handles the receipt of a purchase notification.
* @dev This function MUST return the function selector, otherwise the caller will revert the transaction.
* The selector to be returned can be obtained as `this.onPurchaseNotificationReceived.selector`
* @dev This function MAY throw.
* @param purchaser The purchaser of the purchase.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
* @param totalPrice The total price paid.
* @param pricingData Implementation-specific extra pricing data, such as details about discounts applied.
* @param paymentData Implementation-specific extra payment data, such as conversion rates.
* @param deliveryData Implementation-specific extra delivery data, such as purchase receipts.
* @return `bytes4(keccak256("onPurchaseNotificationReceived(address,address,address,bytes32,uint256,bytes,uint256,bytes32[],bytes32[],bytes32[])"))`
*/
function onPurchaseNotificationReceived(
address purchaser,
address recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData,
uint256 totalPrice,
bytes32[] calldata pricingData,
bytes32[] calldata paymentData,
bytes32[] calldata deliveryData
) external pure returns (bytes4);
}
// File @animoca/ethereum-contracts-sale_base/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title PurchaseLifeCycles
* An abstract contract which define the life cycles for a purchase implementer.
*/
abstract contract PurchaseLifeCycles {
/**
* Wrapper for the purchase data passed as argument to the life cycle functions and down to their step functions.
*/
struct PurchaseData {
address payable purchaser;
address payable recipient;
address token;
bytes32 sku;
uint256 quantity;
bytes userData;
uint256 totalPrice;
bytes32[] pricingData;
bytes32[] paymentData;
bytes32[] deliveryData;
}
/* Internal Life Cycle Functions */
/**
* `estimatePurchase` lifecycle.
* @param purchase The purchase conditions.
*/
function _estimatePurchase(PurchaseData memory purchase)
internal
virtual
view
returns (uint256 totalPrice, bytes32[] memory pricingData)
{
_validation(purchase);
_pricing(purchase);
totalPrice = purchase.totalPrice;
pricingData = purchase.pricingData;
}
/**
* `purchaseFor` lifecycle.
* @param purchase The purchase conditions.
*/
function _purchaseFor(PurchaseData memory purchase) internal virtual {
_validation(purchase);
_pricing(purchase);
_payment(purchase);
_delivery(purchase);
_notification(purchase);
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal virtual view;
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal virtual view;
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual;
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual;
}
// File @animoca/ethereum-contracts-sale_base/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title AbstractSale
* An abstract base sale contract with a minimal implementation of ISale and administration functions.
* A minimal implementation of the `_validation`, `_delivery` and `notification` life cycle step functions
* are provided, but the inheriting contract must implement `_pricing` and `_payment`.
*/
abstract contract AbstractSale is PurchaseLifeCycles, ISale, PayoutWallet, Startable, Pausable {
using Address for address;
using SafeMath for uint256;
using EnumSet for EnumSet.Set;
using EnumMap for EnumMap.Map;
struct SkuInfo {
uint256 totalSupply;
uint256 remainingSupply;
uint256 maxQuantityPerPurchase;
address notificationsReceiver;
EnumMap.Map prices;
}
address public constant override TOKEN_ETH = address(0x00eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee);
uint256 public constant override SUPPLY_UNLIMITED = type(uint256).max;
EnumSet.Set internal _skus;
mapping(bytes32 => SkuInfo) internal _skuInfos;
uint256 internal immutable _skusCapacity;
uint256 internal immutable _tokensPerSkuCapacity;
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal PayoutWallet(payoutWallet_) {
_skusCapacity = skusCapacity;
_tokensPerSkuCapacity = tokensPerSkuCapacity;
bytes32[] memory names = new bytes32[](2);
bytes32[] memory values = new bytes32[](2);
(names[0], values[0]) = ("TOKEN_ETH", bytes32(uint256(TOKEN_ETH)));
(names[1], values[1]) = ("SUPPLY_UNLIMITED", bytes32(uint256(SUPPLY_UNLIMITED)));
emit MagicValues(names, values);
_pause();
}
/* Public Admin Functions */
/**
* Actvates, or 'starts', the contract.
* @dev Emits the `Started` event.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has already been started.
* @dev Reverts if the contract is not paused.
*/
function start() public virtual onlyOwner {
_start();
_unpause();
}
/**
* Pauses the contract.
* @dev Emits the `Paused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is already paused.
*/
function pause() public virtual onlyOwner whenStarted {
_pause();
}
/**
* Resumes the contract.
* @dev Emits the `Unpaused` event.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if the contract has not been started yet.
* @dev Reverts if the contract is not paused.
*/
function unpause() public virtual onlyOwner whenStarted {
_unpause();
}
/**
* Creates an SKU.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `totalSupply` is zero.
* @dev Reverts if `sku` already exists.
* @dev Reverts if `notificationsReceiver` is not the zero address and is not a contract address.
* @dev Reverts if the update results in too many SKUs.
* @dev Emits the `SkuCreation` event.
* @param sku the SKU identifier.
* @param totalSupply the initial total supply.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param notificationsReceiver The purchase notifications receiver contract address.
* If set to the zero address, the notification is not enabled.
*/
function createSku(
bytes32 sku,
uint256 totalSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver
) public virtual onlyOwner {
require(totalSupply != 0, "Sale: zero supply");
require(_skus.length() < _skusCapacity, "Sale: too many skus");
require(_skus.add(sku), "Sale: sku already created");
if (notificationsReceiver != address(0)) {
require(notificationsReceiver.isContract(), "Sale: receiver is not a contract");
}
SkuInfo storage skuInfo = _skuInfos[sku];
skuInfo.totalSupply = totalSupply;
skuInfo.remainingSupply = totalSupply;
skuInfo.maxQuantityPerPurchase = maxQuantityPerPurchase;
skuInfo.notificationsReceiver = notificationsReceiver;
emit SkuCreation(sku, totalSupply, maxQuantityPerPurchase, notificationsReceiver);
}
/**
* Sets the token prices for the specified product SKU.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `tokens` and `prices` have different lengths.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if one of the `tokens` is the zero address.
* @dev Reverts if the update results in too many tokens for the SKU.
* @dev Emits the `SkuPricingUpdate` event.
* @param sku The identifier of the SKU.
* @param tokens The list of payment tokens to update.
* If empty, disable all the existing payment tokens.
* @param prices The list of prices to apply for each payment token.
* Zero price values are used to disable a payment token.
*/
function updateSkuPricing(
bytes32 sku,
address[] memory tokens,
uint256[] memory prices
) public virtual onlyOwner {
uint256 length = tokens.length;
require(length == prices.length, "Sale: tokens/prices lengths mismatch");
SkuInfo storage skuInfo = _skuInfos[sku];
require(skuInfo.totalSupply != 0, "Sale: non-existent sku");
EnumMap.Map storage tokenPrices = skuInfo.prices;
if (length == 0) {
uint256 currentLength = tokenPrices.length();
for (uint256 i = 0; i < currentLength; ++i) {
// TODO add a clear function in EnumMap and EnumSet and use it
(bytes32 token, ) = tokenPrices.at(0);
tokenPrices.remove(token);
}
} else {
_setTokenPrices(tokenPrices, tokens, prices);
}
emit SkuPricingUpdate(sku, tokens, prices);
}
/* ISale Public Functions */
/**
* Performs a purchase.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `token` is the address zero.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @dev Emits the Purchase event.
* @param recipient The recipient of the purchase.
* @param token The token to use as the payment currency.
* @param sku The identifier of the SKU to purchase.
* @param quantity The quantity to purchase.
* @param userData Optional extra user input data.
*/
function purchaseFor(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external virtual override payable whenStarted whenNotPaused {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
_purchaseFor(purchase);
}
/**
* Estimates the computed final total amount to pay for a purchase, including any potential discount.
* @dev This function MUST compute the same price as `purchaseFor` would in identical conditions (same arguments, same point in time).
* @dev If an implementer contract uses the `priceInfo` field, it SHOULD document how to interpret the info.
* @dev Reverts if the sale has not started.
* @dev Reverts if the sale is paused.
* @dev Reverts if `token` is the zero address.
* @dev Reverts if `quantity` is zero.
* @dev Reverts if `quantity` is greater than the maximum purchase quantity.
* @dev Reverts if `quantity` is greater than the remaining supply.
* @dev Reverts if `sku` does not exist.
* @dev Reverts if `sku` exists but does not have a price set for `token`.
* @param recipient The recipient of the purchase used to calculate the total price amount.
* @param token The payment token used to calculate the total price amount.
* @param sku The identifier of the SKU used to calculate the total price amount.
* @param quantity The quantity used to calculate the total price amount.
* @param userData Optional extra user input data.
* @return totalPrice The computed total price.
* @return priceInfo Implementation-specific extra price information, such as details about potential discounts applied.
*/
function estimatePurchase(
address payable recipient,
address token,
bytes32 sku,
uint256 quantity,
bytes calldata userData
) external virtual override view whenStarted whenNotPaused returns (uint256 totalPrice, bytes32[] memory priceInfo) {
PurchaseData memory purchase;
purchase.purchaser = _msgSender();
purchase.recipient = recipient;
purchase.token = token;
purchase.sku = sku;
purchase.quantity = quantity;
purchase.userData = userData;
return _estimatePurchase(purchase);
}
/**
* Returns the information relative to a SKU.
* @dev WARNING: it is the responsibility of the implementer to ensure that the
* number of payment tokens is bounded, so that this function does not run out of gas.
* @dev Reverts if `sku` does not exist.
* @param sku The SKU identifier.
* @return totalSupply The initial total supply for sale.
* @return remainingSupply The remaining supply for sale.
* @return maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @return notificationsReceiver The address of a contract on which to call the `onPurchaseNotificationReceived` function.
* @return tokens The list of supported payment tokens.
* @return prices The list of associated prices for each of the `tokens`.
*/
function getSkuInfo(bytes32 sku)
external
override
view
returns (
uint256 totalSupply,
uint256 remainingSupply,
uint256 maxQuantityPerPurchase,
address notificationsReceiver,
address[] memory tokens,
uint256[] memory prices
)
{
SkuInfo storage skuInfo = _skuInfos[sku];
uint256 length = skuInfo.prices.length();
totalSupply = skuInfo.totalSupply;
remainingSupply = skuInfo.remainingSupply;
maxQuantityPerPurchase = skuInfo.maxQuantityPerPurchase;
notificationsReceiver = skuInfo.notificationsReceiver;
tokens = new address[](length);
prices = new uint256[](length);
for (uint256 i = 0; i < length; ++i) {
(bytes32 token, bytes32 price) = skuInfo.prices.at(i);
tokens[i] = address(uint256(token));
prices[i] = uint256(price);
}
}
/**
* Returns the list of created SKU identifiers.
* @return skus the list of created SKU identifiers.
*/
function getSkus() external override view returns (bytes32[] memory skus) {
skus = _skus.values;
}
/* Internal Utility Functions */
function _setTokenPrices(
EnumMap.Map storage tokenPrices,
address[] memory tokens,
uint256[] memory prices
) internal virtual {
for (uint256 i = 0; i < tokens.length; ++i) {
address token = tokens[i];
require(token != address(0), "Sale: zero address token");
uint256 price = prices[i];
if (price == 0) {
tokenPrices.remove(bytes32(uint256(token)));
} else {
tokenPrices.set(bytes32(uint256(token)), bytes32(price));
}
}
require(tokenPrices.length() <= _tokensPerSkuCapacity, "Sale: too many tokens");
}
/* Internal Life Cycle Step Functions */
/**
* Lifecycle step which validates the purchase pre-conditions.
* @dev Responsibilities:
* - Ensure that the purchase pre-conditions are met and revert if not.
* @dev Reverts if `purchase.recipient` is the zero address.
* @dev Reverts if `purchase.quantity` is zero.
* @dev Reverts if `purchase.quantity` is greater than the SKU's `maxQuantityPerPurchase`.
* @dev Reverts if `purchase.quantity` is greater than the available supply.
* @dev If this function is overriden, the implementer SHOULD super call this before.
* @param purchase The purchase conditions.
*/
function _validation(PurchaseData memory purchase) internal virtual override view {
require(purchase.recipient != address(0), "Sale: zero address recipient");
require(purchase.quantity != 0, "Sale: zero quantity purchase");
SkuInfo memory skuInfo = _skuInfos[purchase.sku];
require(purchase.quantity <= skuInfo.maxQuantityPerPurchase, "Sale: above max quantity");
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
require(skuInfo.remainingSupply >= purchase.quantity, "Sale: insufficient supply");
}
}
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @dev Reverts if there is not enough available supply.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _delivery(PurchaseData memory purchase) internal virtual override {
SkuInfo memory skuInfo = _skuInfos[purchase.sku];
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
_skuInfos[purchase.sku].remainingSupply = skuInfo.remainingSupply.sub(purchase.quantity);
}
}
/**
* Lifecycle step which notifies of the purchase.
* @dev Responsibilities:
* - Manage after-purchase event(s) emission.
* - Handle calls to the notifications receiver contract's `onPurchaseNotificationReceived` function, if applicable.
* @dev Reverts if `onPurchaseNotificationReceived` throws or returns an incorrect value.
* @dev Emits the `Purchase` event. The values of `purchaseData` are the concatenated values of `priceData`, `paymentData`
* and `deliveryData`. If not empty, the implementer MUST document how to interpret these values.
* @dev If this function is overriden, the implementer SHOULD super call it.
* @param purchase The purchase conditions.
*/
function _notification(PurchaseData memory purchase) internal virtual override {
emit Purchase(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
purchase.pricingData,
purchase.paymentData,
purchase.deliveryData
);
address notificationsReceiver = _skuInfos[purchase.sku].notificationsReceiver;
if (notificationsReceiver != address(0)) {
require(
IPurchaseNotificationsReceiver(notificationsReceiver).onPurchaseNotificationReceived(
purchase.purchaser,
purchase.recipient,
purchase.token,
purchase.sku,
purchase.quantity,
purchase.userData,
purchase.totalPrice,
purchase.pricingData,
purchase.paymentData,
purchase.deliveryData
) == IPurchaseNotificationsReceiver(address(0)).onPurchaseNotificationReceived.selector, // TODO precompute return value
"Sale: wrong receiver return value"
);
}
}
}
// File @animoca/ethereum-contracts-sale_base/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title FixedPricesSale
* An AbstractSale which implements a fixed prices strategy.
* The final implementer is responsible for implementing any additional pricing and/or delivery logic.
*/
contract FixedPricesSale is AbstractSale {
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @param payoutWallet_ the payout wallet.
* @param skusCapacity the cap for the number of managed SKUs.
* @param tokensPerSkuCapacity the cap for the number of tokens managed per SKU.
*/
constructor(
address payoutWallet_,
uint256 skusCapacity,
uint256 tokensPerSkuCapacity
) internal AbstractSale(payoutWallet_, skusCapacity, tokensPerSkuCapacity) {}
/* Internal Life Cycle Functions */
/**
* Lifecycle step which computes the purchase price.
* @dev Responsibilities:
* - Computes the pricing formula, including any discount logic and price conversion;
* - Set the value of `purchase.totalPrice`;
* - Add any relevant extra data related to pricing in `purchase.pricingData` and document how to interpret it.
* @dev Reverts if `purchase.sku` does not exist.
* @dev Reverts if `purchase.token` is not supported by the SKU.
* @dev Reverts in case of price overflow.
* @param purchase The purchase conditions.
*/
function _pricing(PurchaseData memory purchase) internal virtual override view {
SkuInfo storage skuInfo = _skuInfos[purchase.sku];
require(skuInfo.totalSupply != 0, "Sale: unsupported SKU");
EnumMap.Map storage prices = skuInfo.prices;
uint256 unitPrice = _unitPrice(purchase, prices);
purchase.totalPrice = unitPrice.mul(purchase.quantity);
}
/**
* Lifecycle step which manages the transfer of funds from the purchaser.
* @dev Responsibilities:
* - Ensure the payment reaches destination in the expected output token;
* - Handle any token swap logic;
* - Add any relevant extra data related to payment in `purchase.paymentData` and document how to interpret it.
* @dev Reverts in case of payment failure.
* @param purchase The purchase conditions.
*/
function _payment(PurchaseData memory purchase) internal virtual override {
if (purchase.token == TOKEN_ETH) {
require(msg.value >= purchase.totalPrice, "Sale: insufficient ETH provided");
payoutWallet.transfer(purchase.totalPrice);
uint256 change = msg.value.sub(purchase.totalPrice);
if (change != 0) {
purchase.purchaser.transfer(change);
}
} else {
require(
IERC20(purchase.token).transferFrom(_msgSender(), payoutWallet, purchase.totalPrice),
"Sale: ERC20 payment failed"
);
}
}
/* Internal Utility Functions */
function _unitPrice(PurchaseData memory purchase, EnumMap.Map storage prices)
internal
virtual
view
returns (uint256 unitPrice)
{
unitPrice = uint256(prices.get(bytes32(uint256(purchase.token))));
require(unitPrice != 0, "Sale: unsupported payment token");
}
}
// File @animoca/f1dt-ethereum-contracts/contracts/sale/[email protected]
pragma solidity 0.6.8;
/**
* @title CrateKeyFullSale
* A FixedPricesSale contract implementation that handles the full-price (non-discounted) purchase of ERC20 F1DTCrateKey tokens.
*/
contract CrateKeyFullSale is FixedPricesSale {
/* sku => crate key */
mapping (bytes32 => IF1DTCrateKeyFull) public crateKeys;
/**
* Constructor.
* @dev Emits the `MagicValues` event.
* @dev Emits the `Paused` event.
* @dev Emits the `PayoutWalletSet` event.
* @param payoutWallet_ the payout wallet.
*/
constructor (
address payoutWallet_
)
public
FixedPricesSale(
payoutWallet_,
4, // SKUs capacity (each type of crate key only)
4 // tokens per-SKU capacity
)
{
}
/**
* Creates an SKU.
* @dev Deprecated. Please use `createCrateKeySku(bytes32, uint256, uint256, IF1DTCrateKeyFull)` for creating
* inventory SKUs.
* @dev Reverts if called.
* @param *sku* the SKU identifier.
* @param *totalSupply* the initial total supply.
* @param *maxQuantityPerPurchase* The maximum allowed quantity for a single purchase.
* @param *notificationsReceiver* The purchase notifications receiver contract address.
* If set to the zero address, the notification is not enabled.
*/
function createSku(
bytes32 /*sku*/,
uint256 /*totalSupply*/,
uint256 /*maxQuantityPerPurchase*/,
address /*notificationsReceiver*/
) public override onlyOwner {
revert("Deprecated. Please use `createCrateKeySku(bytes32, uint256, uint256, IF1DTCrateKeyFull)`");
}
/**
* Creates an SKU and associates the specified ERC20 F1DTCrateKey token contract with it.
* @dev Reverts if called by any other than the contract owner.
* @dev Reverts if `totalSupply` is zero.
* @dev Reverts if `sku` already exists.
* @dev Reverts if the update results in too many SKUs.
* @dev Reverts if the `totalSupply` is SUPPLY_UNLIMITED.
* @dev Reverts if the `crateKey` is the zero address.
* @dev Emits the `SkuCreation` event.
* @param sku The SKU identifier.
* @param totalSupply The initial total supply.
* @param maxQuantityPerPurchase The maximum allowed quantity for a single purchase.
* @param crateKey The ERC20 F1DTCrateKey token contract to bind with the SKU.
*/
function createCrateKeySku(
bytes32 sku,
uint256 totalSupply,
uint256 maxQuantityPerPurchase,
IF1DTCrateKeyFull crateKey
) external onlyOwner {
require(
totalSupply != SUPPLY_UNLIMITED,
"CrateKeyFullSale: invalid total supply");
require(
crateKey != IF1DTCrateKeyFull(0),
"CrateKeyFullSale: zero address");
super.createSku(
sku,
totalSupply,
maxQuantityPerPurchase,
address(0)); // notifications receiver
crateKeys[sku] = crateKey;
}
/**
* Lifecycle step which delivers the purchased SKUs to the recipient.
* @dev Responsibilities:
* - Ensure the product is delivered to the recipient, if that is the contract's responsibility.
* - Handle any internal logic related to the delivery, including the remaining supply update;
* - Add any relevant extra data related to delivery in `purchase.deliveryData` and document how to interpret it.
* @dev Transfers tokens from the ERC20 F1DTCrateKey token contract associated with the SKU being purchased, of the
* specified purchase quantity.
* @dev Reverts if the holder has an insufficient ERC20 F1DTCrateKey token balance for the transfer.
* @dev Reverts if the sale contract has an insufficient ERC20 F1DTCrateKey allowance for the transfer.
* @param purchase The purchase conditions.
*/
function _delivery(
PurchaseData memory purchase
) internal override {
super._delivery(purchase);
IF1DTCrateKeyFull crateKey = crateKeys[purchase.sku];
crateKey.transferFrom(
crateKey.holder(),
purchase.recipient,
purchase.quantity);
}
}
/**
* @dev Interface of the ERC20 F1DTCrateKey token contract.
*/
interface IF1DTCrateKeyFull {
/**
* Returns the amount of tokens owned by `account`.
* @param account The account whose token balance will be retrieved.
* @return The amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* Returns the remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` through
* {transferFrom}.
* @dev This value is zero by default.
* @dev This value changes when {approve} or {transferFrom} are called.
* @param owner The account who has granted a spending allowance to the spender.
* @param spender The account who has been granted a spending allowance by the owner.
* @return The remaining number of tokens that `spender` will be allowed to spend on behalf of `owner` through
* {transferFrom}.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* Moves `amount` tokens from `sender` to `recipient` using the allowance mechanism.
* @dev `amount` is deducted from the caller's allowance.
* @dev Emits a {Transfer} event.
* @param sender The account where the tokens will be transferred from.
* @param recipient The account where the tokens will be transferred to.
* @param amount The amount of tokens being transferred.
* @return Boolean indicating whether the operation succeeded.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* Returns the account holding the initial token supply.
* @return The account holding the initial token supply.
*/
function holder() external view returns (address);
} | Lifecycle step which validates the purchase pre-conditions. Responsibilities: - Ensure that the purchase pre-conditions are met and revert if not. Reverts if `purchase.recipient` is the zero address. Reverts if `purchase.quantity` is zero. Reverts if `purchase.quantity` is greater than the SKU's `maxQuantityPerPurchase`. Reverts if `purchase.quantity` is greater than the available supply. If this function is overriden, the implementer SHOULD super call this before. purchase The purchase conditions./ | function _validation(PurchaseData memory purchase) internal virtual override view {
require(purchase.recipient != address(0), "Sale: zero address recipient");
require(purchase.quantity != 0, "Sale: zero quantity purchase");
SkuInfo memory skuInfo = _skuInfos[purchase.sku];
require(purchase.quantity <= skuInfo.maxQuantityPerPurchase, "Sale: above max quantity");
if (skuInfo.totalSupply != SUPPLY_UNLIMITED) {
require(skuInfo.remainingSupply >= purchase.quantity, "Sale: insufficient supply");
}
}
| 228,615 |
./full_match/3/0x03b0258e8A3d9C0a7574bD55b06815998345ec1B/sources/contracts/DiamondHoldTestETH.sol | Adds liquidity to the PancakeSwap V2 LP/ Approve token transfer to cover all possible scenarios Adds the liquidity and gives the LP tokens to the owner of this contract The LP tokens need to be manually locked | function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(pancakeswapV2Router), tokenAmount);
address(this),
tokenAmount,
owner(),
block.timestamp
);
pancakeswapV2Router.addLiquidityETH{value: ethAmount}(
}
| 8,267,754 |
pragma solidity 0.5.10;
contract Context {
constructor () internal { }
function _MSGSENDER793() internal view returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA330() internal view returns (bytes memory) { //inject NONSTANDARD NAMING
this;
return msg.data;
}
}
interface IERC20 {
function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF227(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER744(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE643(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE357(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM570(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER432(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL431(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD803(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB97(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB97(a, b, "SafeMath: subtraction overflow");
}
function SUB97(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 MUL111(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV358(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV358(a, b, "SafeMath: division by zero");
}
function DIV358(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0, errorMessage);
uint256 c = a / b;
return c;
}
function MOD464(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD464(a, b, "SafeMath: modulo by zero");
}
function MOD464(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
function TOTALSUPPLY908() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF227(address account) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[account];
}
function TRANSFER744(address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER927(_MSGSENDER793(), recipient, amount);
return true;
}
function ALLOWANCE643(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowances[owner][spender];
}
function APPROVE357(address spender, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE171(_MSGSENDER793(), spender, amount);
return true;
}
function TRANSFERFROM570(address sender, address recipient, uint256 amount) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER927(sender, recipient, amount);
_APPROVE171(sender, _MSGSENDER793(), _allowances[sender][_MSGSENDER793()].SUB97(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
function INCREASEALLOWANCE99(address spender, uint256 addedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].ADD803(addedValue));
return true;
}
function DECREASEALLOWANCE633(address spender, uint256 subtractedValue) public returns (bool) { //inject NONSTANDARD NAMING
_APPROVE171(_MSGSENDER793(), spender, _allowances[_MSGSENDER793()][spender].SUB97(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
function _TRANSFER927(address sender, address recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_balances[sender] = _balances[sender].SUB97(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].ADD803(amount);
emit TRANSFER432(sender, recipient, amount);
}
function _MINT736(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: mint to the zero address");
_totalSupply = _totalSupply.ADD803(amount);
_balances[account] = _balances[account].ADD803(amount);
emit TRANSFER432(address(0), account, amount);
}
function _BURN826(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
require(account != address(0), "ERC20: burn from the zero address");
_balances[account] = _balances[account].SUB97(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.SUB97(amount);
emit TRANSFER432(account, address(0), amount);
}
function _APPROVE171(address owner, address spender, uint256 amount) internal { //inject NONSTANDARD NAMING
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit APPROVAL431(owner, spender, amount);
}
function _BURNFROM936(address account, uint256 amount) internal { //inject NONSTANDARD NAMING
_BURN826(account, amount);
_APPROVE171(account, _MSGSENDER793(), _allowances[account][_MSGSENDER793()].SUB97(amount, "ERC20: burn amount exceeds allowance"));
}
}
library BytesLib {
function CONCAT636(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
bytes memory tempBytes;
assembly {
tempBytes := mload(0x40)
let length := mload(_preBytes)
mstore(tempBytes, length)
let mc := add(tempBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
mc := end
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31)
))
}
return tempBytes;
}
function CONCATSTORAGE846(bytes storage _preBytes, bytes memory _postBytes) internal { //inject NONSTANDARD NAMING
assembly {
let fslot := sload(_preBytes_slot)
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
let newlength := add(slength, mlength)
switch add(lt(slength, 32), lt(newlength, 32))
case 2 {
sstore(
_preBytes_slot,
add(
fslot,
add(
mul(
div(
mload(add(_postBytes, 0x20)),
exp(0x100, sub(32, mlength))
),
exp(0x100, sub(32, newlength))
),
mul(mlength, 2)
)
)
)
}
case 1 {
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
let submod := sub(32, slength)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(
sc,
add(
and(
fslot,
0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff00
),
and(mload(mc), mask)
)
)
for {
mc := add(mc, 0x20)
sc := add(sc, 1)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
default {
mstore(0x0, _preBytes_slot)
let sc := add(keccak256(0x0, 0x20), div(slength, 32))
sstore(_preBytes_slot, add(mul(newlength, 2), 1))
let slengthmod := mod(slength, 32)
let mlengthmod := mod(mlength, 32)
let submod := sub(32, slengthmod)
let mc := add(_postBytes, submod)
let end := add(_postBytes, mlength)
let mask := sub(exp(0x100, submod), 1)
sstore(sc, add(sload(sc), and(mload(mc), mask)))
for {
sc := add(sc, 1)
mc := add(mc, 0x20)
} lt(mc, end) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
sstore(sc, mload(mc))
}
mask := exp(0x100, sub(mc, end))
sstore(sc, mul(div(mload(mc), mask), mask))
}
}
}
function SLICE479(bytes memory _bytes, uint _start, uint _length) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + _length), "Slice out of bounds");
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(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function TOADDRESS666(bytes memory _bytes, uint _start) internal pure returns (address) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 20), "Address conversion out of bounds.");
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function TOUINT411(bytes memory _bytes, uint _start) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(_bytes.length >= (_start + 32), "Uint conversion out of bounds.");
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function EQUAL334(bytes memory _preBytes, bytes memory _postBytes) internal pure returns (bool) { //inject NONSTANDARD NAMING
bool success = true;
assembly {
let length := mload(_preBytes)
switch eq(length, mload(_postBytes))
case 1 {
let cb := 1
let mc := add(_preBytes, 0x20)
let end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} eq(add(lt(mc, end), cb), 2) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
if iszero(eq(mload(mc), mload(cc))) {
success := 0
cb := 0
}
}
}
default {
success := 0
}
}
return success;
}
function EQUALSTORAGE265(bytes storage _preBytes, bytes memory _postBytes) internal view returns (bool) { //inject NONSTANDARD NAMING
bool success = true;
assembly {
let fslot := sload(_preBytes_slot)
let slength := div(and(fslot, sub(mul(0x100, iszero(and(fslot, 1))), 1)), 2)
let mlength := mload(_postBytes)
switch eq(slength, mlength)
case 1 {
if iszero(iszero(slength)) {
switch lt(slength, 32)
case 1 {
fslot := mul(div(fslot, 0x100), 0x100)
if iszero(eq(fslot, mload(add(_postBytes, 0x20)))) {
success := 0
}
}
default {
let cb := 1
mstore(0x0, _preBytes_slot)
let sc := keccak256(0x0, 0x20)
let mc := add(_postBytes, 0x20)
let end := add(mc, mlength)
for {} eq(add(lt(mc, end), cb), 2) {
sc := add(sc, 1)
mc := add(mc, 0x20)
} {
if iszero(eq(sload(sc), mload(mc))) {
success := 0
cb := 0
}
}
}
}
}
default {
success := 0
}
}
return success;
}
function TOBYTES32571(bytes memory _source) pure internal returns (bytes32 result) { //inject NONSTANDARD NAMING
bytes memory tempEmptyStringTest = bytes(_source);
if (tempEmptyStringTest.length == 0) {
return 0x0;
}
assembly {
result := mload(add(_source, 32))
}
}
}
library BTCUtils {
using BytesLib for bytes;
using SafeMath for uint256;
uint256 public constant diff1_target719 = 0xffff0000000000000000000000000000000000000000000000000000; //inject NONSTANDARD NAMING
uint256 public constant retarget_period820 = 2 * 7 * 24 * 60 * 60; //inject NONSTANDARD NAMING
uint256 public constant retarget_period_blocks665 = 2016; //inject NONSTANDARD NAMING
function DETERMINEVARINTDATALENGTH811(bytes memory _flag) internal pure returns (uint8) { //inject NONSTANDARD NAMING
if (uint8(_flag[0]) == 0xff) {
return 8;
}
if (uint8(_flag[0]) == 0xfe) {
return 4;
}
if (uint8(_flag[0]) == 0xfd) {
return 2;
}
return 0;
}
function REVERSEENDIANNESS18(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
bytes memory _newValue = new bytes(_b.length);
for (uint i = 0; i < _b.length; i++) {
_newValue[_b.length - i - 1] = _b[i];
}
return _newValue;
}
function BYTESTOUINT790(bytes memory _b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 _number;
for (uint i = 0; i < _b.length; i++) {
_number = _number + uint8(_b[i]) * (2 ** (8 * (_b.length - (i + 1))));
}
return _number;
}
function LASTBYTES156(bytes memory _b, uint256 _num) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint256 _start = _b.length.SUB97(_num);
return _b.SLICE479(_start, _num);
}
function HASH160454(bytes memory _b) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return abi.encodePacked(ripemd160(abi.encodePacked(sha256(_b))));
}
function HASH256986(bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return abi.encodePacked(sha256(abi.encodePacked(sha256(_b)))).TOBYTES32571();
}
function EXTRACTINPUTATINDEX738(bytes memory _vin, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint256 _len;
bytes memory _remaining;
uint256 _offset = 1;
for (uint8 _i = 0; _i < _index; _i ++) {
_remaining = _vin.SLICE479(_offset, _vin.length - _offset);
_len = DETERMINEINPUTLENGTH677(_remaining);
_offset = _offset + _len;
}
_remaining = _vin.SLICE479(_offset, _vin.length - _offset);
_len = DETERMINEINPUTLENGTH677(_remaining);
return _vin.SLICE479(_offset, _len);
}
function ISLEGACYINPUT163(bytes memory _input) internal pure returns (bool) { //inject NONSTANDARD NAMING
return keccak256(_input.SLICE479(36, 1)) != keccak256(hex"00");
}
function DETERMINEINPUTLENGTH677(bytes memory _input) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint8 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input);
return 36 + 1 + _varIntDataLen + _scriptSigLen + 4;
}
function EXTRACTSEQUENCELELEGACY251(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint8 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input);
return _input.SLICE479(36 + 1 + _varIntDataLen + _scriptSigLen, 4);
}
function EXTRACTSEQUENCELEGACY692(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING
bytes memory _leSeqence = EXTRACTSEQUENCELELEGACY251(_input);
bytes memory _beSequence = REVERSEENDIANNESS18(_leSeqence);
return uint32(BYTESTOUINT790(_beSequence));
}
function EXTRACTSCRIPTSIG435(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint8 _varIntDataLen;
uint256 _scriptSigLen;
(_varIntDataLen, _scriptSigLen) = EXTRACTSCRIPTSIGLEN905(_input);
return _input.SLICE479(36, 1 + _varIntDataLen + _scriptSigLen);
}
function EXTRACTSCRIPTSIGLEN905(bytes memory _input) internal pure returns (uint8, uint256) { //inject NONSTANDARD NAMING
bytes memory _varIntTag = _input.SLICE479(36, 1);
uint8 _varIntDataLen = DETERMINEVARINTDATALENGTH811(_varIntTag);
uint256 _len;
if (_varIntDataLen == 0) {
_len = uint8(_varIntTag[0]);
} else {
_len = BYTESTOUINT790(REVERSEENDIANNESS18(_input.SLICE479(36 + 1, _varIntDataLen)));
}
return (_varIntDataLen, _len);
}
function EXTRACTSEQUENCELEWITNESS46(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _input.SLICE479(37, 4);
}
function EXTRACTSEQUENCEWITNESS1000(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING
bytes memory _leSeqence = EXTRACTSEQUENCELEWITNESS46(_input);
bytes memory _inputeSequence = REVERSEENDIANNESS18(_leSeqence);
return uint32(BYTESTOUINT790(_inputeSequence));
}
function EXTRACTOUTPOINT770(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _input.SLICE479(0, 36);
}
function EXTRACTINPUTTXIDLE232(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return _input.SLICE479(0, 32).TOBYTES32571();
}
function EXTRACTINPUTTXID926(bytes memory _input) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
bytes memory _leId = abi.encodePacked(EXTRACTINPUTTXIDLE232(_input));
bytes memory _beId = REVERSEENDIANNESS18(_leId);
return _beId.TOBYTES32571();
}
function EXTRACTTXINDEXLE408(bytes memory _input) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _input.SLICE479(32, 4);
}
function EXTRACTTXINDEX998(bytes memory _input) internal pure returns (uint32) { //inject NONSTANDARD NAMING
bytes memory _leIndex = EXTRACTTXINDEXLE408(_input);
bytes memory _beIndex = REVERSEENDIANNESS18(_leIndex);
return uint32(BYTESTOUINT790(_beIndex));
}
function DETERMINEOUTPUTLENGTH588(bytes memory _output) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint8 _len = uint8(_output.SLICE479(8, 1)[0]);
require(_len < 0xfd, "Multi-byte VarInts not supported");
return _len + 8 + 1;
}
function EXTRACTOUTPUTATINDEX182(bytes memory _vout, uint8 _index) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
uint256 _len;
bytes memory _remaining;
uint256 _offset = 1;
for (uint8 _i = 0; _i < _index; _i ++) {
_remaining = _vout.SLICE479(_offset, _vout.length - _offset);
_len = DETERMINEOUTPUTLENGTH588(_remaining);
_offset = _offset + _len;
}
_remaining = _vout.SLICE479(_offset, _vout.length - _offset);
_len = DETERMINEOUTPUTLENGTH588(_remaining);
return _vout.SLICE479(_offset, _len);
}
function EXTRACTOUTPUTSCRIPTLEN88(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _output.SLICE479(8, 1);
}
function EXTRACTVALUELE862(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _output.SLICE479(0, 8);
}
function EXTRACTVALUE239(bytes memory _output) internal pure returns (uint64) { //inject NONSTANDARD NAMING
bytes memory _leValue = EXTRACTVALUELE862(_output);
bytes memory _beValue = REVERSEENDIANNESS18(_leValue);
return uint64(BYTESTOUINT790(_beValue));
}
function EXTRACTOPRETURNDATA540(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
if (keccak256(_output.SLICE479(9, 1)) != keccak256(hex"6a")) {
return hex"";
}
bytes memory _dataLen = _output.SLICE479(10, 1);
return _output.SLICE479(11, BYTESTOUINT790(_dataLen));
}
function EXTRACTHASH570(bytes memory _output) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
if (uint8(_output.SLICE479(9, 1)[0]) == 0) {
uint256 _len = uint8(EXTRACTOUTPUTSCRIPTLEN88(_output)[0]) - 2;
if (uint8(_output.SLICE479(10, 1)[0]) != uint8(_len)) {
return hex"";
}
return _output.SLICE479(11, _len);
} else {
bytes32 _tag = keccak256(_output.SLICE479(8, 3));
if (_tag == keccak256(hex"1976a9")) {
if (uint8(_output.SLICE479(11, 1)[0]) != 0x14 ||
keccak256(_output.SLICE479(_output.length - 2, 2)) != keccak256(hex"88ac")) {
return hex"";
}
return _output.SLICE479(12, 20);
} else if (_tag == keccak256(hex"17a914")) {
if (uint8(_output.SLICE479(_output.length - 1, 1)[0]) != 0x87) {
return hex"";
}
return _output.SLICE479(11, 20);
}
}
return hex"";
}
function VALIDATEVIN629(bytes memory _vin) internal pure returns (bool) { //inject NONSTANDARD NAMING
uint256 _offset = 1;
uint8 _nIns = uint8(_vin.SLICE479(0, 1)[0]);
if (_nIns >= 0xfd || _nIns == 0) {
return false;
}
for (uint8 i = 0; i < _nIns; i++) {
_offset += DETERMINEINPUTLENGTH677(_vin.SLICE479(_offset, _vin.length - _offset));
if (_offset > _vin.length) {
return false;
}
}
return _offset == _vin.length;
}
function VALIDATEVOUT976(bytes memory _vout) internal pure returns (bool) { //inject NONSTANDARD NAMING
uint256 _offset = 1;
uint8 _nOuts = uint8(_vout.SLICE479(0, 1)[0]);
if (_nOuts >= 0xfd || _nOuts == 0) {
return false;
}
for (uint8 i = 0; i < _nOuts; i++) {
_offset += DETERMINEOUTPUTLENGTH588(_vout.SLICE479(_offset, _vout.length - _offset));
if (_offset > _vout.length) {
return false;
}
}
return _offset == _vout.length;
}
function EXTRACTMERKLEROOTLE545(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _header.SLICE479(36, 32);
}
function EXTRACTMERKLEROOTBE364(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return REVERSEENDIANNESS18(EXTRACTMERKLEROOTLE545(_header));
}
function EXTRACTTARGET28(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING
bytes memory _m = _header.SLICE479(72, 3);
uint8 _e = uint8(_header[75]);
uint256 _mantissa = BYTESTOUINT790(REVERSEENDIANNESS18(_m));
uint _exponent = _e - 3;
return _mantissa * (256 ** _exponent);
}
function CALCULATEDIFFICULTY733(uint256 _target) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return diff1_target719.DIV358(_target);
}
function EXTRACTPREVBLOCKLE989(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _header.SLICE479(4, 32);
}
function EXTRACTPREVBLOCKBE985(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return REVERSEENDIANNESS18(EXTRACTPREVBLOCKLE989(_header));
}
function EXTRACTTIMESTAMPLE896(bytes memory _header) internal pure returns (bytes memory) { //inject NONSTANDARD NAMING
return _header.SLICE479(68, 4);
}
function EXTRACTTIMESTAMP636(bytes memory _header) internal pure returns (uint32) { //inject NONSTANDARD NAMING
return uint32(BYTESTOUINT790(REVERSEENDIANNESS18(EXTRACTTIMESTAMPLE896(_header))));
}
function EXTRACTDIFFICULTY209(bytes memory _header) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return CALCULATEDIFFICULTY733(EXTRACTTARGET28(_header));
}
function _HASH256MERKLESTEP183(bytes memory _a, bytes memory _b) internal pure returns (bytes32) { //inject NONSTANDARD NAMING
return HASH256986(abi.encodePacked(_a, _b));
}
function VERIFYHASH256MERKLE9(bytes memory _proof, uint _index) internal pure returns (bool) { //inject NONSTANDARD NAMING
if (_proof.length % 32 != 0) {
return false;
}
if (_proof.length == 32) {
return true;
}
if (_proof.length == 64) {
return false;
}
uint _idx = _index;
bytes32 _root = _proof.SLICE479(_proof.length - 32, 32).TOBYTES32571();
bytes32 _current = _proof.SLICE479(0, 32).TOBYTES32571();
for (uint i = 1; i < (_proof.length.DIV358(32)) - 1; i++) {
if (_idx % 2 == 1) {
_current = _HASH256MERKLESTEP183(_proof.SLICE479(i * 32, 32), abi.encodePacked(_current));
} else {
_current = _HASH256MERKLESTEP183(abi.encodePacked(_current), _proof.SLICE479(i * 32, 32));
}
_idx = _idx >> 1;
}
return _current == _root;
}
function RETARGETALGORITHM78( //inject NONSTANDARD NAMING
uint256 _previousTarget,
uint256 _firstTimestamp,
uint256 _secondTimestamp
) internal pure returns (uint256) {
uint256 _elapsedTime = _secondTimestamp.SUB97(_firstTimestamp);
if (_elapsedTime < retarget_period820.DIV358(4)) {
_elapsedTime = retarget_period820.DIV358(4);
}
if (_elapsedTime > retarget_period820.MUL111(4)) {
_elapsedTime = retarget_period820.MUL111(4);
}
uint256 _adjusted = _previousTarget.DIV358(65536).MUL111(_elapsedTime);
return _adjusted.DIV358(retarget_period820).MUL111(65536);
}
}
interface FundsInterface {
function LENDER92(bytes32) external view returns (address); //inject NONSTANDARD NAMING
function CUSTOM642(bytes32) external view returns (bool); //inject NONSTANDARD NAMING
function DEPOSIT909(bytes32, uint256) external; //inject NONSTANDARD NAMING
function DECREASETOTALBORROW522(uint256) external; //inject NONSTANDARD NAMING
function CALCGLOBALINTEREST773() external; //inject NONSTANDARD NAMING
}
interface SalesInterface {
function SALEINDEXBYLOAN897(bytes32, uint256) external returns(bytes32); //inject NONSTANDARD NAMING
function SETTLEMENTEXPIRATION526(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function ACCEPTED582(bytes32) external view returns (bool); //inject NONSTANDARD NAMING
function NEXT199(bytes32) external view returns (uint256); //inject NONSTANDARD NAMING
function CREATE943(bytes32, address, address, address, address, bytes32, bytes32, bytes32, bytes32, bytes20) external returns(bytes32); //inject NONSTANDARD NAMING
}
interface CollateralInterface {
function ONDEMANDSPV389() external view returns(address); //inject NONSTANDARD NAMING
function COLLATERAL382(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256); //inject NONSTANDARD NAMING
function SETCOLLATERAL164(bytes32 loan, uint256 refundableCollateral_, uint256 seizableCollateral_) external; //inject NONSTANDARD NAMING
function REQUESTSPV477(bytes32 loan) external; //inject NONSTANDARD NAMING
function CANCELSPV463(bytes32 loan) external; //inject NONSTANDARD NAMING
}
contract DSMath {
function ADD803(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require((z = x + y) >= x);
}
function SUB97(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require((z = x - y) <= x);
}
function MUL111(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
require(y == 0 || (z = x * y) / y == x);
}
function DIV358(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING
require(b > 0);
c = a / b;
}
function MIN456(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
return x <= y ? x : y;
}
function MAX638(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
return x >= y ? x : y;
}
function IMIN865(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING
return x <= y ? x : y;
}
function IMAX990(int x, int y) internal pure returns (int z) { //inject NONSTANDARD NAMING
return x >= y ? x : y;
}
uint constant col735 = 10 ** 8; //inject NONSTANDARD NAMING
uint constant wad510 = 10 ** 18; //inject NONSTANDARD NAMING
uint constant ray271 = 10 ** 27; //inject NONSTANDARD NAMING
function CMUL87(uint x, uint y) public pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, y), col735 / 2) / col735;
}
function WMUL533(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, y), wad510 / 2) / wad510;
}
function RMUL965(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, y), ray271 / 2) / ray271;
}
function CDIV416(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, col735), y / 2) / y;
}
function WDIV128(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, wad510), y / 2) / y;
}
function RDIV519(uint x, uint y) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = ADD803(MUL111(x, ray271), y / 2) / y;
}
function RPOW933(uint x, uint n) internal pure returns (uint z) { //inject NONSTANDARD NAMING
z = n % 2 != 0 ? x : ray271;
for (n /= 2; n != 0; n /= 2) {
x = RMUL965(x, x);
if (n % 2 != 0) {
z = RMUL965(z, x);
}
}
}
}
contract Medianizer {
function PEEK685() external view returns (bytes32, bool); //inject NONSTANDARD NAMING
function READ913() external returns (bytes32); //inject NONSTANDARD NAMING
function POKE561() external; //inject NONSTANDARD NAMING
function POKE561(bytes32) external; //inject NONSTANDARD NAMING
function FUND172 (uint256 amount, ERC20 token) external; //inject NONSTANDARD NAMING
}
contract Loans is DSMath {
FundsInterface funds;
Medianizer med;
SalesInterface sales;
CollateralInterface col;
uint256 public constant approve_exp_threshold840 = 2 hours; //inject NONSTANDARD NAMING
uint256 public constant accept_exp_threshold947 = 2 days; //inject NONSTANDARD NAMING
uint256 public constant liquidation_exp_threshold443 = 7 days; //inject NONSTANDARD NAMING
uint256 public constant seizure_exp_threshold699 = 2 days; //inject NONSTANDARD NAMING
uint256 public constant liquidation_discount317 = 930000000000000000; //inject NONSTANDARD NAMING
uint256 public constant max_num_liquidations552 = 3; //inject NONSTANDARD NAMING
uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING
mapping (bytes32 => Loan) public loans;
mapping (bytes32 => PubKeys) public pubKeys;
mapping (bytes32 => SecretHashes) public secretHashes;
mapping (bytes32 => Bools) public bools;
mapping (bytes32 => bytes32) public fundIndex;
mapping (bytes32 => uint256) public repayments;
mapping (address => bytes32[]) public borrowerLoans;
mapping (address => bytes32[]) public lenderLoans;
mapping (address => mapping(uint256 => bool)) public addressToTimestamp;
uint256 public loanIndex;
ERC20 public token;
uint256 public decimals;
address deployer;
struct Loan {
address borrower;
address lender;
address arbiter;
uint256 createdAt;
uint256 loanExpiration;
uint256 requestTimestamp;
uint256 closedTimestamp;
uint256 principal;
uint256 interest;
uint256 penalty;
uint256 fee;
uint256 liquidationRatio;
}
struct PubKeys {
bytes borrowerPubKey;
bytes lenderPubKey;
bytes arbiterPubKey;
}
struct SecretHashes {
bytes32 secretHashA1;
bytes32[3] secretHashAs;
bytes32 secretHashB1;
bytes32[3] secretHashBs;
bytes32 secretHashC1;
bytes32[3] secretHashCs;
bytes32 withdrawSecret;
bytes32 acceptSecret;
bool set;
}
struct Bools {
bool funded;
bool approved;
bool withdrawn;
bool sale;
bool paid;
bool off;
}
event CREATE22(bytes32 loan); //inject NONSTANDARD NAMING
event SETSECRETHASHES818(bytes32 loan); //inject NONSTANDARD NAMING
event FUNDLOAN50(bytes32 loan); //inject NONSTANDARD NAMING
event APPROVE490(bytes32 loan); //inject NONSTANDARD NAMING
event WITHDRAW160(bytes32 loan, bytes32 secretA1); //inject NONSTANDARD NAMING
event REPAY404(bytes32 loan, uint256 amount); //inject NONSTANDARD NAMING
event REFUND289(bytes32 loan); //inject NONSTANDARD NAMING
event CANCEL833(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING
event ACCEPT489(bytes32 loan, bytes32 secret); //inject NONSTANDARD NAMING
event LIQUIDATE130(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash); //inject NONSTANDARD NAMING
function BORROWER75(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING
return loans[loan].borrower;
}
function LENDER92(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING
return loans[loan].lender;
}
function ARBITER4(bytes32 loan) external view returns (address) { //inject NONSTANDARD NAMING
return loans[loan].arbiter;
}
function APPROVEEXPIRATION234(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(loans[loan].createdAt, approve_exp_threshold840);
}
function ACCEPTEXPIRATION879(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(loans[loan].loanExpiration, accept_exp_threshold947);
}
function LIQUIDATIONEXPIRATION442(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(loans[loan].loanExpiration, liquidation_exp_threshold443);
}
function SEIZUREEXPIRATION523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(LIQUIDATIONEXPIRATION442(loan), seizure_exp_threshold699);
}
function PRINCIPAL566(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].principal;
}
function INTEREST523(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].interest;
}
function FEE426(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].fee;
}
function PENALTY434(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].penalty;
}
function COLLATERAL382(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return col.COLLATERAL382(loan);
}
function REFUNDABLECOLLATERAL879(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return col.REFUNDABLECOLLATERAL879(loan);
}
function SEIZABLECOLLATERAL368(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return col.SEIZABLECOLLATERAL368(loan);
}
function TEMPORARYREFUNDABLECOLLATERAL760(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return col.TEMPORARYREFUNDABLECOLLATERAL760(loan);
}
function TEMPORARYSEIZABLECOLLATERAL228(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return col.TEMPORARYSEIZABLECOLLATERAL228(loan);
}
function REPAID307(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return repayments[loan];
}
function LIQUIDATIONRATIO684(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return loans[loan].liquidationRatio;
}
function OWEDTOLENDER7(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(PRINCIPAL566(loan), INTEREST523(loan));
}
function OWEDFORLOAN262(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(OWEDTOLENDER7(loan), FEE426(loan));
}
function OWEDFORLIQUIDATION588(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return ADD803(OWEDFORLOAN262(loan), PENALTY434(loan));
}
function OWING794(bytes32 loan) external view returns (uint256) { //inject NONSTANDARD NAMING
return SUB97(OWEDFORLOAN262(loan), REPAID307(loan));
}
function FUNDED74(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].funded;
}
function APPROVED714(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].approved;
}
function WITHDRAWN418(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].withdrawn;
}
function SALE305(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].sale;
}
function PAID214(bytes32 loan) external view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].paid;
}
function OFF578(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING
return bools[loan].off;
}
function DMUL562(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING
return MUL111(x, (10 ** SUB97(18, decimals)));
}
function DDIV45(uint x) public view returns (uint256) { //inject NONSTANDARD NAMING
return DIV358(x, (10 ** SUB97(18, decimals)));
}
function BORROWERLOANCOUNT920(address borrower_) external view returns (uint256) { //inject NONSTANDARD NAMING
return borrowerLoans[borrower_].length;
}
function LENDERLOANCOUNT648(address lender_) external view returns (uint256) { //inject NONSTANDARD NAMING
return lenderLoans[lender_].length;
}
function MINSEIZABLECOLLATERAL886(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
(bytes32 val, bool set) = med.PEEK685();
require(set, "Loans.minSeizableCollateral: Medianizer must be set");
uint256 price = uint(val);
return DIV358(WDIV128(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), price), DIV358(wad510, col735));
}
function COLLATERALVALUE260(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
(bytes32 val, bool set) = med.PEEK685();
require(set, "Loans.collateralValue: Medianizer must be set");
uint256 price = uint(val);
return CMUL87(price, COLLATERAL382(loan));
}
function MINCOLLATERALVALUE408(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return RMUL965(DMUL562(SUB97(OWEDFORLOAN262(loan), REPAID307(loan))), LIQUIDATIONRATIO684(loan));
}
function DISCOUNTCOLLATERALVALUE221(bytes32 loan) public view returns (uint256) { //inject NONSTANDARD NAMING
return WMUL533(COLLATERALVALUE260(loan), liquidation_discount317);
}
function SAFE528(bytes32 loan) public view returns (bool) { //inject NONSTANDARD NAMING
return COLLATERALVALUE260(loan) >= MINCOLLATERALVALUE408(loan);
}
constructor (FundsInterface funds_, Medianizer med_, ERC20 token_, uint256 decimals_) public {
require(address(funds_) != address(0), "Funds address must be non-zero");
require(address(med_) != address(0), "Medianizer address must be non-zero");
require(address(token_) != address(0), "Token address must be non-zero");
deployer = msg.sender;
funds = funds_;
med = med_;
token = token_;
decimals = decimals_;
require(token.APPROVE357(address(funds), max_uint_256251), "Token approve failed");
}
function SETSALES924(SalesInterface sales_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Loans.setSales: Only the deployer can perform this");
require(address(sales) == address(0), "Loans.setSales: The Sales address has already been set");
require(address(sales_) != address(0), "Loans.setSales: Sales address must be non-zero");
sales = sales_;
}
function SETCOLLATERAL164(CollateralInterface col_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Loans.setCollateral: Only the deployer can perform this");
require(address(col) == address(0), "Loans.setCollateral: The Collateral address has already been set");
require(address(col_) != address(0), "Loans.setCollateral: Collateral address must be non-zero");
col = col_;
}
function CREATE943( //inject NONSTANDARD NAMING
uint256 loanExpiration_,
address[3] calldata usrs_,
uint256[7] calldata vals_,
bytes32 fund
) external returns (bytes32 loan) {
if (fund != bytes32(0)) {
require(funds.LENDER92(fund) == usrs_[1], "Loans.create: Lender of Fund not in args");
}
require(!addressToTimestamp[usrs_[0]][vals_[6]], "Loans.create: Duplicate request timestamps are not allowed");
require(loanExpiration_ > now, "Loans.create: loanExpiration must be greater than `now`");
require(usrs_[0] != address(0) && usrs_[1] != address(0), "Loans.create: Borrower and Lender address must be non-zero");
require(vals_[0] != 0 && vals_[4] != 0, "Loans.create: Principal and Collateral must be non-zero");
require(vals_[5] != 0 && vals_[6] != 0, "Loans.create: Liquidation ratio and Request timestamp must be non-zero");
loanIndex = ADD803(loanIndex, 1);
loan = bytes32(loanIndex);
loans[loan].createdAt = now;
loans[loan].loanExpiration = loanExpiration_;
loans[loan].borrower = usrs_[0];
loans[loan].lender = usrs_[1];
loans[loan].arbiter = usrs_[2];
loans[loan].principal = vals_[0];
loans[loan].interest = vals_[1];
loans[loan].penalty = vals_[2];
loans[loan].fee = vals_[3];
uint256 minSeizableCol = MINSEIZABLECOLLATERAL886(loan);
col.SETCOLLATERAL164(loan, SUB97(vals_[4], minSeizableCol), minSeizableCol);
loans[loan].liquidationRatio = vals_[5];
loans[loan].requestTimestamp = vals_[6];
fundIndex[loan] = fund;
secretHashes[loan].set = false;
borrowerLoans[usrs_[0]].push(bytes32(loanIndex));
lenderLoans[usrs_[1]].push(bytes32(loanIndex));
addressToTimestamp[usrs_[0]][vals_[6]] = true;
emit CREATE22(loan);
}
function SETSECRETHASHES742( //inject NONSTANDARD NAMING
bytes32 loan,
bytes32[4] calldata borrowerSecretHashes,
bytes32[4] calldata lenderSecretHashes,
bytes32[4] calldata arbiterSecretHashes,
bytes calldata borrowerPubKey_,
bytes calldata lenderPubKey_,
bytes calldata arbiterPubKey_
) external {
require(!secretHashes[loan].set, "Loans.setSecretHashes: Secret hashes must not already be set");
require(
msg.sender == loans[loan].borrower || msg.sender == loans[loan].lender || msg.sender == address(funds),
"Loans.setSecretHashes: msg.sender must be Borrower, Lender or Funds Address"
);
secretHashes[loan].secretHashA1 = borrowerSecretHashes[0];
secretHashes[loan].secretHashAs = [ borrowerSecretHashes[1], borrowerSecretHashes[2], borrowerSecretHashes[3] ];
secretHashes[loan].secretHashB1 = lenderSecretHashes[0];
secretHashes[loan].secretHashBs = [ lenderSecretHashes[1], lenderSecretHashes[2], lenderSecretHashes[3] ];
secretHashes[loan].secretHashC1 = arbiterSecretHashes[0];
secretHashes[loan].secretHashCs = [ arbiterSecretHashes[1], arbiterSecretHashes[2], arbiterSecretHashes[3] ];
pubKeys[loan].borrowerPubKey = borrowerPubKey_;
pubKeys[loan].lenderPubKey = lenderPubKey_;
pubKeys[loan].arbiterPubKey = arbiterPubKey_;
secretHashes[loan].set = true;
}
function FUND172(bytes32 loan) external { //inject NONSTANDARD NAMING
require(secretHashes[loan].set, "Loans.fund: Secret hashes must be set");
require(bools[loan].funded == false, "Loans.fund: Loan is already funded");
bools[loan].funded = true;
require(token.TRANSFERFROM570(msg.sender, address(this), PRINCIPAL566(loan)), "Loans.fund: Failed to transfer tokens");
emit FUNDLOAN50(loan);
}
function APPROVE357(bytes32 loan) external { //inject NONSTANDARD NAMING
require(bools[loan].funded == true, "Loans.approve: Loan must be funded");
require(loans[loan].lender == msg.sender, "Loans.approve: Only the lender can approve the loan");
require(now <= APPROVEEXPIRATION234(loan), "Loans.approve: Loan is past the approve deadline");
bools[loan].approved = true;
emit APPROVE490(loan);
}
function WITHDRAW186(bytes32 loan, bytes32 secretA1) external { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.withdraw: Loan cannot be inactive");
require(bools[loan].funded == true, "Loans.withdraw: Loan must be funded");
require(bools[loan].approved == true, "Loans.withdraw: Loan must be approved");
require(bools[loan].withdrawn == false, "Loans.withdraw: Loan principal has already been withdrawn");
require(sha256(abi.encodePacked(secretA1)) == secretHashes[loan].secretHashA1, "Loans.withdraw: Secret does not match");
bools[loan].withdrawn = true;
require(token.TRANSFER744(loans[loan].borrower, PRINCIPAL566(loan)), "Loans.withdraw: Failed to transfer tokens");
secretHashes[loan].withdrawSecret = secretA1;
if (address(col.ONDEMANDSPV389()) != address(0)) {col.REQUESTSPV477(loan);}
emit WITHDRAW160(loan, secretA1);
}
function REPAY242(bytes32 loan, uint256 amount) external { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.repay: Loan cannot be inactive");
require(!SALE305(loan), "Loans.repay: Loan cannot be undergoing a liquidation");
require(bools[loan].withdrawn == true, "Loans.repay: Loan principal must be withdrawn");
require(now <= loans[loan].loanExpiration, "Loans.repay: Loan cannot have expired");
require(ADD803(amount, REPAID307(loan)) <= OWEDFORLOAN262(loan), "Loans.repay: Cannot repay more than the owed amount");
require(token.TRANSFERFROM570(msg.sender, address(this), amount), "Loans.repay: Failed to transfer tokens");
repayments[loan] = ADD803(amount, repayments[loan]);
if (REPAID307(loan) == OWEDFORLOAN262(loan)) {
bools[loan].paid = true;
if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);}
}
emit REPAY404(loan, amount);
}
function REFUND497(bytes32 loan) external { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.refund: Loan cannot be inactive");
require(!SALE305(loan), "Loans.refund: Loan cannot be undergoing a liquidation");
require(now > ACCEPTEXPIRATION879(loan), "Loans.refund: Cannot request refund until after acceptExpiration");
require(bools[loan].paid == true, "Loans.refund: The loan must be repaid");
require(msg.sender == loans[loan].borrower, "Loans.refund: Only the borrower can request a refund");
bools[loan].off = true;
loans[loan].closedTimestamp = now;
if (funds.CUSTOM642(fundIndex[loan]) == false) {
funds.DECREASETOTALBORROW522(loans[loan].principal);
funds.CALCGLOBALINTEREST773();
}
require(token.TRANSFER744(loans[loan].borrower, OWEDFORLOAN262(loan)), "Loans.refund: Failed to transfer tokens");
emit REFUND289(loan);
}
function CANCEL391(bytes32 loan, bytes32 secret) external { //inject NONSTANDARD NAMING
ACCEPT922(loan, secret);
emit CANCEL833(loan, secret);
}
function CANCEL391(bytes32 loan) external { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.cancel: Loan must not be inactive");
require(bools[loan].withdrawn == false, "Loans.cancel: Loan principal must not be withdrawn");
require(now >= SEIZUREEXPIRATION523(loan), "Loans.cancel: Seizure deadline has not been reached");
require(bools[loan].sale == false, "Loans.cancel: Loan must not be undergoing liquidation");
CLOSE691(loan);
emit CANCEL833(loan, bytes32(0));
}
function ACCEPT922(bytes32 loan, bytes32 secret) public { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.accept: Loan must not be inactive");
require(bools[loan].withdrawn == false || bools[loan].paid == true, "Loans.accept: Loan must be either not withdrawn or repaid");
require(msg.sender == loans[loan].lender || msg.sender == loans[loan].arbiter, "Loans.accept: msg.sender must be lender or arbiter");
require(now <= ACCEPTEXPIRATION879(loan), "Loans.accept: Acceptance deadline has past");
require(bools[loan].sale == false, "Loans.accept: Loan must not be going under liquidation");
require(
sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashB1 || sha256(abi.encodePacked(secret)) == secretHashes[loan].secretHashC1,
"Loans.accept: Invalid secret"
);
secretHashes[loan].acceptSecret = secret;
CLOSE691(loan);
emit ACCEPT489(loan, secret);
}
function CLOSE691(bytes32 loan) private { //inject NONSTANDARD NAMING
bools[loan].off = true;
loans[loan].closedTimestamp = now;
if (bools[loan].withdrawn == false) {
if (fundIndex[loan] == bytes32(0)) {
require(token.TRANSFER744(loans[loan].lender, loans[loan].principal), "Loans.close: Failed to transfer principal to Lender");
} else {
if (funds.CUSTOM642(fundIndex[loan]) == false) {
funds.DECREASETOTALBORROW522(loans[loan].principal);
}
funds.DEPOSIT909(fundIndex[loan], loans[loan].principal);
}
}
else {
if (fundIndex[loan] == bytes32(0)) {
require(token.TRANSFER744(loans[loan].lender, OWEDTOLENDER7(loan)), "Loans.close: Failed to transfer owedToLender to Lender");
} else {
if (funds.CUSTOM642(fundIndex[loan]) == false) {
funds.DECREASETOTALBORROW522(loans[loan].principal);
}
funds.DEPOSIT909(fundIndex[loan], OWEDTOLENDER7(loan));
}
require(token.TRANSFER744(loans[loan].arbiter, FEE426(loan)), "Loans.close: Failed to transfer fee to Arbiter");
}
}
function LIQUIDATE339(bytes32 loan, bytes32 secretHash, bytes20 pubKeyHash) external returns (bytes32 sale_) { //inject NONSTANDARD NAMING
require(!OFF578(loan), "Loans.liquidate: Loan must not be inactive");
require(bools[loan].withdrawn == true, "Loans.liquidate: Loan principal must be withdrawn");
require(msg.sender != loans[loan].borrower && msg.sender != loans[loan].lender, "Loans.liquidate: Liquidator must be a third-party");
require(secretHash != bytes32(0) && pubKeyHash != bytes20(0), "Loans.liquidate: secretHash and pubKeyHash must be non-zero");
if (sales.NEXT199(loan) == 0) {
if (now > loans[loan].loanExpiration) {
require(bools[loan].paid == false, "Loans.liquidate: loan must not have already been repaid");
} else {
require(!SAFE528(loan), "Loans.liquidate: collateralization must be below min-collateralization ratio");
}
if (funds.CUSTOM642(fundIndex[loan]) == false) {
funds.DECREASETOTALBORROW522(loans[loan].principal);
funds.CALCGLOBALINTEREST773();
}
} else {
require(sales.NEXT199(loan) < max_num_liquidations552, "Loans.liquidate: Max number of liquidations reached");
require(!sales.ACCEPTED582(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)), "Loans.liquidate: Previous liquidation already accepted");
require(
now > sales.SETTLEMENTEXPIRATION526(sales.SALEINDEXBYLOAN897(loan, sales.NEXT199(loan) - 1)),
"Loans.liquidate: Previous liquidation settlement expiration hasn't expired"
);
}
require(token.BALANCEOF227(msg.sender) >= DDIV45(DISCOUNTCOLLATERALVALUE221(loan)), "Loans.liquidate: insufficient balance to liquidate");
require(token.TRANSFERFROM570(msg.sender, address(sales), DDIV45(DISCOUNTCOLLATERALVALUE221(loan))), "Loans.liquidate: Token transfer failed");
SecretHashes storage h = secretHashes[loan];
uint256 i = sales.NEXT199(loan);
sale_ = sales.CREATE943(
loan, loans[loan].borrower, loans[loan].lender, loans[loan].arbiter, msg.sender,
h.secretHashAs[i], h.secretHashBs[i], h.secretHashCs[i], secretHash, pubKeyHash
);
if (bools[loan].sale == false) {
bools[loan].sale = true;
require(token.TRANSFER744(address(sales), REPAID307(loan)), "Loans.liquidate: Token transfer to Sales contract failed");
}
if (address(col.ONDEMANDSPV389()) != address(0)) {col.CANCELSPV463(loan);}
emit LIQUIDATE130(loan, secretHash, pubKeyHash);
}
}
interface CTokenInterface {
function REDEEM46(uint redeemTokens) external returns (uint); //inject NONSTANDARD NAMING
function REDEEMUNDERLYING614(uint redeemAmount) external returns (uint); //inject NONSTANDARD NAMING
function BORROW254(uint borrowAmount) external returns (uint); //inject NONSTANDARD NAMING
function LIQUIDATEBORROW888(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); //inject NONSTANDARD NAMING
function LIQUIDATEBORROW888(address borrower, address cTokenCollateral) external payable; //inject NONSTANDARD NAMING
function EXCHANGERATECURRENT666() external returns (uint); //inject NONSTANDARD NAMING
function GETCASH889() external view returns (uint); //inject NONSTANDARD NAMING
function TOTALBORROWSCURRENT914() external returns (uint); //inject NONSTANDARD NAMING
function BORROWRATEPERBLOCK907() external view returns (uint); //inject NONSTANDARD NAMING
function SUPPLYRATEPERBLOCK507() external view returns (uint); //inject NONSTANDARD NAMING
function TOTALRESERVES190() external view returns (uint); //inject NONSTANDARD NAMING
function RESERVEFACTORMANTISSA247() external view returns (uint); //inject NONSTANDARD NAMING
function TOTALSUPPLY908() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF227(address owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING
function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING
function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING
}
interface CERC20Interface {
function MINT386(uint mintAmount) external returns (uint); //inject NONSTANDARD NAMING
function REPAYBORROW556(uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING
function REPAYBORROWBEHALF985(address borrower, uint repayAmount) external returns (uint); //inject NONSTANDARD NAMING
function BORROWBALANCECURRENT604(address account) external returns (uint); //inject NONSTANDARD NAMING
}
interface ERC20Interface {
function ALLOWANCE643(address, address) external view returns (uint); //inject NONSTANDARD NAMING
function BALANCEOF227(address) external view returns (uint); //inject NONSTANDARD NAMING
function APPROVE357(address, uint) external; //inject NONSTANDARD NAMING
function TRANSFER744(address, uint) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM570(address, address, uint) external returns (bool); //inject NONSTANDARD NAMING
}
interface TrollerInterface {
function ENTERMARKETS395(address[] calldata cTokens) external returns (uint[] memory); //inject NONSTANDARD NAMING
function EXITMARKET275(address cTokenAddress) external returns (uint); //inject NONSTANDARD NAMING
function GETASSETSIN764(address account) external view returns (address[] memory); //inject NONSTANDARD NAMING
function GETACCOUNTLIQUIDITY185(address account) external view returns (uint, uint, uint); //inject NONSTANDARD NAMING
}
contract Helpers is DSMath {
address public comptroller;
function GETCOMPTROLLERADDRESS117() public view returns (address) { //inject NONSTANDARD NAMING
return comptroller;
}
function ENTERMARKET780(address cErc20) internal { //inject NONSTANDARD NAMING
TrollerInterface troller = TrollerInterface(GETCOMPTROLLERADDRESS117());
address[] memory markets = troller.GETASSETSIN764(address(this));
bool isEntered = false;
for (uint i = 0; i < markets.length; i++) {
if (markets[i] == cErc20) {
isEntered = true;
}
}
if (!isEntered) {
address[] memory toEnter = new address[](1);
toEnter[0] = cErc20;
troller.ENTERMARKETS395(toEnter);
}
}
function SETAPPROVAL391(address erc20, uint srcAmt, address to) internal { //inject NONSTANDARD NAMING
ERC20Interface erc20Contract = ERC20Interface(erc20);
uint tokenAllowance = erc20Contract.ALLOWANCE643(address(this), to);
if (srcAmt > tokenAllowance) {
erc20Contract.APPROVE357(to, 2**255);
}
}
}
contract ALCompound is Helpers {
function MINTCTOKEN703(address erc20, address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING
ENTERMARKET780(cErc20);
ERC20Interface token = ERC20Interface(erc20);
uint toDeposit = token.BALANCEOF227(address(this));
if (toDeposit > tokenAmt) {
toDeposit = tokenAmt;
}
CERC20Interface cToken = CERC20Interface(cErc20);
SETAPPROVAL391(erc20, toDeposit, cErc20);
assert(cToken.MINT386(toDeposit) == 0);
}
function REDEEMUNDERLYING614(address cErc20, uint tokenAmt) internal { //inject NONSTANDARD NAMING
CTokenInterface cToken = CTokenInterface(cErc20);
SETAPPROVAL391(cErc20, 10**50, cErc20);
uint toBurn = cToken.BALANCEOF227(address(this));
uint tokenToReturn = WMUL533(toBurn, cToken.EXCHANGERATECURRENT666());
if (tokenToReturn > tokenAmt) {
tokenToReturn = tokenAmt;
}
require(cToken.REDEEMUNDERLYING614(tokenToReturn) == 0, "something went wrong");
}
function REDEEMCTOKEN224(address cErc20, uint cTokenAmt) internal { //inject NONSTANDARD NAMING
CTokenInterface cToken = CTokenInterface(cErc20);
uint toBurn = cToken.BALANCEOF227(address(this));
if (toBurn > cTokenAmt) {
toBurn = cTokenAmt;
}
SETAPPROVAL391(cErc20, toBurn, cErc20);
require(cToken.REDEEM46(toBurn) == 0, "something went wrong");
}
}
contract Funds is DSMath, ALCompound {
Loans loans;
uint256 public constant default_liquidation_ratio475 = 1400000000000000000000000000; //inject NONSTANDARD NAMING
uint256 public constant default_liquidation_penalty756 = 1000000000937303470807876289; //inject NONSTANDARD NAMING
uint256 public constant default_min_loan_amt427 = 25 ether; //inject NONSTANDARD NAMING
uint256 public constant default_max_loan_amt507 = 2**256-1; //inject NONSTANDARD NAMING
uint256 public constant default_min_loan_dur981 = 6 hours; //inject NONSTANDARD NAMING
uint256 public constant num_seconds_in_year521 = 365 days; //inject NONSTANDARD NAMING
uint256 public constant max_loan_length66 = 10 * num_seconds_in_year521; //inject NONSTANDARD NAMING
uint256 public constant max_uint_256251 = 2**256-1; //inject NONSTANDARD NAMING
mapping (address => bytes32[]) public secretHashes;
mapping (address => uint256) public secretHashIndex;
mapping (address => bytes) public pubKeys;
mapping (bytes32 => Fund) public funds;
mapping (address => bytes32) public fundOwner;
mapping (bytes32 => Bools) public bools;
uint256 public fundIndex;
uint256 public lastGlobalInterestUpdated;
uint256 public tokenMarketLiquidity;
uint256 public cTokenMarketLiquidity;
uint256 public marketLiquidity;
uint256 public totalBorrow;
uint256 public globalInterestRateNumerator;
uint256 public lastUtilizationRatio;
uint256 public globalInterestRate;
uint256 public maxUtilizationDelta;
uint256 public utilizationInterestDivisor;
uint256 public maxInterestRateNumerator;
uint256 public minInterestRateNumerator;
uint256 public interestUpdateDelay;
uint256 public defaultArbiterFee;
ERC20 public token;
uint256 public decimals;
CTokenInterface public cToken;
bool compoundSet;
address deployer;
struct Fund {
address lender;
uint256 minLoanAmt;
uint256 maxLoanAmt;
uint256 minLoanDur;
uint256 maxLoanDur;
uint256 fundExpiry;
uint256 interest;
uint256 penalty;
uint256 fee;
uint256 liquidationRatio;
address arbiter;
uint256 balance;
uint256 cBalance;
}
struct Bools {
bool custom;
bool compoundEnabled;
}
event CREATE22(bytes32 fund); //inject NONSTANDARD NAMING
event DEPOSIT856(bytes32 fund, uint256 amount_); //inject NONSTANDARD NAMING
event UPDATE341(bytes32 fund, uint256 maxLoanDur_, uint256 fundExpiry_, address arbiter_); //inject NONSTANDARD NAMING
event REQUEST101(bytes32 fund, address borrower_, uint256 amount_, uint256 collateral_, uint256 loanDur_, uint256 requestTimestamp_); //inject NONSTANDARD NAMING
event WITHDRAW160(bytes32 fund, uint256 amount_, address recipient_); //inject NONSTANDARD NAMING
event ENABLECOMPOUND170(bytes32 fund); //inject NONSTANDARD NAMING
event DISABLECOMPOUND118(bytes32 fund); //inject NONSTANDARD NAMING
constructor(
ERC20 token_,
uint256 decimals_
) public {
require(address(token_) != address(0), "Funds.constructor: Token address must be non-zero");
require(decimals_ != 0, "Funds.constructor: Decimals must be non-zero");
deployer = msg.sender;
token = token_;
decimals = decimals_;
utilizationInterestDivisor = 10531702972595856680093239305;
maxUtilizationDelta = 95310179948351216961192521;
globalInterestRateNumerator = 95310179948351216961192521;
maxInterestRateNumerator = 182321557320989604265864303;
minInterestRateNumerator = 24692612600038629323181834;
interestUpdateDelay = 86400;
defaultArbiterFee = 1000000000236936036262880196;
globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521));
}
function SETLOANS600(Loans loans_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setLoans: Only the deployer can perform this");
require(address(loans) == address(0), "Funds.setLoans: Loans address has already been set");
require(address(loans_) != address(0), "Funds.setLoans: Loans address must be non-zero");
loans = loans_;
require(token.APPROVE357(address(loans_), max_uint_256251), "Funds.setLoans: Tokens cannot be approved");
}
function SETCOMPOUND395(CTokenInterface cToken_, address comptroller_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setCompound: Only the deployer can enable Compound lending");
require(!compoundSet, "Funds.setCompound: Compound address has already been set");
require(address(cToken_) != address(0), "Funds.setCompound: cToken address must be non-zero");
require(comptroller_ != address(0), "Funds.setCompound: comptroller address must be non-zero");
cToken = cToken_;
comptroller = comptroller_;
compoundSet = true;
}
function SETUTILIZATIONINTERESTDIVISOR326(uint256 utilizationInterestDivisor_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setUtilizationInterestDivisor: Only the deployer can perform this");
require(utilizationInterestDivisor_ != 0, "Funds.setUtilizationInterestDivisor: utilizationInterestDivisor is zero");
utilizationInterestDivisor = utilizationInterestDivisor_;
}
function SETMAXUTILIZATIONDELTA889(uint256 maxUtilizationDelta_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setMaxUtilizationDelta: Only the deployer can perform this");
require(maxUtilizationDelta_ != 0, "Funds.setMaxUtilizationDelta: maxUtilizationDelta is zero");
maxUtilizationDelta = maxUtilizationDelta_;
}
function SETGLOBALINTERESTRATENUMERATOR552(uint256 globalInterestRateNumerator_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setGlobalInterestRateNumerator: Only the deployer can perform this");
require(globalInterestRateNumerator_ != 0, "Funds.setGlobalInterestRateNumerator: globalInterestRateNumerator is zero");
globalInterestRateNumerator = globalInterestRateNumerator_;
}
function SETGLOBALINTERESTRATE215(uint256 globalInterestRate_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setGlobalInterestRate: Only the deployer can perform this");
require(globalInterestRate_ != 0, "Funds.setGlobalInterestRate: globalInterestRate is zero");
globalInterestRate = globalInterestRate_;
}
function SETMAXINTERESTRATENUMERATOR833(uint256 maxInterestRateNumerator_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setMaxInterestRateNumerator: Only the deployer can perform this");
require(maxInterestRateNumerator_ != 0, "Funds.setMaxInterestRateNumerator: maxInterestRateNumerator is zero");
maxInterestRateNumerator = maxInterestRateNumerator_;
}
function SETMININTERESTRATENUMERATOR870(uint256 minInterestRateNumerator_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setMinInterestRateNumerator: Only the deployer can perform this");
require(minInterestRateNumerator_ != 0, "Funds.setMinInterestRateNumerator: minInterestRateNumerator is zero");
minInterestRateNumerator = minInterestRateNumerator_;
}
function SETINTERESTUPDATEDELAY704(uint256 interestUpdateDelay_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setInterestUpdateDelay: Only the deployer can perform this");
require(interestUpdateDelay_ != 0, "Funds.setInterestUpdateDelay: interestUpdateDelay is zero");
interestUpdateDelay = interestUpdateDelay_;
}
function SETDEFAULTARBITERFEE996(uint256 defaultArbiterFee_) external { //inject NONSTANDARD NAMING
require(msg.sender == deployer, "Funds.setDefaultArbiterFee: Only the deployer can perform this");
require(defaultArbiterFee_ <= 1000000000315522921573372069, "Funds.setDefaultArbiterFee: defaultArbiterFee cannot be less than -1%");
defaultArbiterFee = defaultArbiterFee_;
}
function LENDER92(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING
return funds[fund].lender;
}
function MINLOANAMT516(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].minLoanAmt;}
else {return DIV358(default_min_loan_amt427, (10 ** SUB97(18, decimals)));}
}
function MAXLOANAMT810(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].maxLoanAmt;}
else {return default_max_loan_amt507;}
}
function MINLOANDUR238(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].minLoanDur;}
else {return default_min_loan_dur981;}
}
function MAXLOANDUR299(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
return funds[fund].maxLoanDur;
}
function FUNDEXPIRY174(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
return funds[fund].fundExpiry;
}
function INTEREST523(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].interest;}
else {return globalInterestRate;}
}
function PENALTY434(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].penalty;}
else {return default_liquidation_penalty756;}
}
function FEE426(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].fee;}
else {return defaultArbiterFee;}
}
function LIQUIDATIONRATIO684(bytes32 fund) public view returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].custom) {return funds[fund].liquidationRatio;}
else {return default_liquidation_ratio475;}
}
function ARBITER4(bytes32 fund) public view returns (address) { //inject NONSTANDARD NAMING
return funds[fund].arbiter;
}
function BALANCE334(bytes32 fund) public returns (uint256) { //inject NONSTANDARD NAMING
if (bools[fund].compoundEnabled) {
return WMUL533(funds[fund].cBalance, cToken.EXCHANGERATECURRENT666());
} else {
return funds[fund].balance;
}
}
function CTOKENEXCHANGERATE725() public returns (uint256) { //inject NONSTANDARD NAMING
if (compoundSet) {
return cToken.EXCHANGERATECURRENT666();
} else {
return 0;
}
}
function CUSTOM642(bytes32 fund) public view returns (bool) { //inject NONSTANDARD NAMING
return bools[fund].custom;
}
function SECRETHASHESCOUNT698(address addr_) public view returns (uint256) { //inject NONSTANDARD NAMING
return secretHashes[addr_].length;
}
function CREATE943( //inject NONSTANDARD NAMING
uint256 maxLoanDur_,
uint256 fundExpiry_,
address arbiter_,
bool compoundEnabled_,
uint256 amount_
) external returns (bytes32 fund) {
require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address");
require(
ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66,
"Funds.create: fundExpiry and maxLoanDur cannot exceed 10 years"
);
if (!compoundSet) {require(compoundEnabled_ == false, "Funds.create: Cannot enable Compound as it has not been configured");}
fundIndex = ADD803(fundIndex, 1);
fund = bytes32(fundIndex);
funds[fund].lender = msg.sender;
funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false);
funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true);
funds[fund].arbiter = arbiter_;
bools[fund].custom = false;
bools[fund].compoundEnabled = compoundEnabled_;
fundOwner[msg.sender] = bytes32(fundIndex);
if (amount_ > 0) {DEPOSIT909(fund, amount_);}
emit CREATE22(fund);
}
function CREATECUSTOM959( //inject NONSTANDARD NAMING
uint256 minLoanAmt_,
uint256 maxLoanAmt_,
uint256 minLoanDur_,
uint256 maxLoanDur_,
uint256 fundExpiry_,
uint256 liquidationRatio_,
uint256 interest_,
uint256 penalty_,
uint256 fee_,
address arbiter_,
bool compoundEnabled_,
uint256 amount_
) external returns (bytes32 fund) {
require(funds[fundOwner[msg.sender]].lender != msg.sender, "Funds.create: Only one loan fund allowed per address");
require(
ENSURENOTZERO255(maxLoanDur_, false) < max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) < now + max_loan_length66,
"Funds.createCustom: fundExpiry and maxLoanDur cannot exceed 10 years"
);
require(maxLoanAmt_ >= minLoanAmt_, "Funds.createCustom: maxLoanAmt must be greater than or equal to minLoanAmt");
require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.createCustom: maxLoanDur must be greater than or equal to minLoanDur");
if (!compoundSet) {require(compoundEnabled_ == false, "Funds.createCustom: Cannot enable Compound as it has not been configured");}
fundIndex = ADD803(fundIndex, 1);
fund = bytes32(fundIndex);
funds[fund].lender = msg.sender;
funds[fund].minLoanAmt = minLoanAmt_;
funds[fund].maxLoanAmt = maxLoanAmt_;
funds[fund].minLoanDur = minLoanDur_;
funds[fund].maxLoanDur = ENSURENOTZERO255(maxLoanDur_, false);
funds[fund].fundExpiry = ENSURENOTZERO255(fundExpiry_, true);
funds[fund].interest = interest_;
funds[fund].penalty = penalty_;
funds[fund].fee = fee_;
funds[fund].liquidationRatio = liquidationRatio_;
funds[fund].arbiter = arbiter_;
bools[fund].custom = true;
bools[fund].compoundEnabled = compoundEnabled_;
fundOwner[msg.sender] = bytes32(fundIndex);
if (amount_ > 0) {DEPOSIT909(fund, amount_);}
emit CREATE22(fund);
}
function DEPOSIT909(bytes32 fund, uint256 amount_) public { //inject NONSTANDARD NAMING
require(token.TRANSFERFROM570(msg.sender, address(this), amount_), "Funds.deposit: Failed to transfer tokens");
if (bools[fund].compoundEnabled) {
MINTCTOKEN703(address(token), address(cToken), amount_);
uint256 cTokenToAdd = DIV358(MUL111(amount_, wad510), cToken.EXCHANGERATECURRENT666());
funds[fund].cBalance = ADD803(funds[fund].cBalance, cTokenToAdd);
if (!CUSTOM642(fund)) {cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToAdd);}
} else {
funds[fund].balance = ADD803(funds[fund].balance, amount_);
if (!CUSTOM642(fund)) {tokenMarketLiquidity = ADD803(tokenMarketLiquidity, amount_);}
}
if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();}
emit DEPOSIT856(fund, amount_);
}
function UPDATE438( //inject NONSTANDARD NAMING
bytes32 fund,
uint256 maxLoanDur_,
uint256 fundExpiry_,
address arbiter_
) public {
require(msg.sender == LENDER92(fund), "Funds.update: Only the lender can update the fund");
require(
ENSURENOTZERO255(maxLoanDur_, false) <= max_loan_length66 && ENSURENOTZERO255(fundExpiry_, true) <= now + max_loan_length66,
"Funds.update: fundExpiry and maxLoanDur cannot exceed 10 years"
);
funds[fund].maxLoanDur = maxLoanDur_;
funds[fund].fundExpiry = fundExpiry_;
funds[fund].arbiter = arbiter_;
emit UPDATE341(fund, maxLoanDur_, fundExpiry_, arbiter_);
}
function UPDATECUSTOM705( //inject NONSTANDARD NAMING
bytes32 fund,
uint256 minLoanAmt_,
uint256 maxLoanAmt_,
uint256 minLoanDur_,
uint256 maxLoanDur_,
uint256 fundExpiry_,
uint256 interest_,
uint256 penalty_,
uint256 fee_,
uint256 liquidationRatio_,
address arbiter_
) external {
require(bools[fund].custom, "Funds.updateCustom: Fund must be a custom fund");
require(maxLoanAmt_ >= minLoanAmt_, "Funds.updateCustom: maxLoanAmt must be greater than or equal to minLoanAmt");
require(ENSURENOTZERO255(maxLoanDur_, false) >= minLoanDur_, "Funds.updateCustom: maxLoanDur must be greater than or equal to minLoanDur");
UPDATE438(fund, maxLoanDur_, fundExpiry_, arbiter_);
funds[fund].minLoanAmt = minLoanAmt_;
funds[fund].maxLoanAmt = maxLoanAmt_;
funds[fund].minLoanDur = minLoanDur_;
funds[fund].interest = interest_;
funds[fund].penalty = penalty_;
funds[fund].fee = fee_;
funds[fund].liquidationRatio = liquidationRatio_;
}
function REQUEST711( //inject NONSTANDARD NAMING
bytes32 fund,
address borrower_,
uint256 amount_,
uint256 collateral_,
uint256 loanDur_,
uint256 requestTimestamp_,
bytes32[8] calldata secretHashes_,
bytes calldata pubKeyA_,
bytes calldata pubKeyB_
) external returns (bytes32 loanIndex) {
require(msg.sender == LENDER92(fund), "Funds.request: Only the lender can fulfill a loan request");
require(amount_ <= BALANCE334(fund), "Funds.request: Insufficient balance");
require(amount_ >= MINLOANAMT516(fund), "Funds.request: Amount requested must be greater than minLoanAmt");
require(amount_ <= MAXLOANAMT810(fund), "Funds.request: Amount requested must be less than maxLoanAmt");
require(loanDur_ >= MINLOANDUR238(fund), "Funds.request: Loan duration must be greater than minLoanDur");
require(loanDur_ <= SUB97(FUNDEXPIRY174(fund), now) && loanDur_ <= MAXLOANDUR299(fund), "Funds.request: Loan duration must be less than maxLoanDur and expiry");
require(borrower_ != address(0), "Funds.request: Borrower address must be non-zero");
require(secretHashes_[0] != bytes32(0) && secretHashes_[1] != bytes32(0), "Funds.request: SecretHash1 & SecretHash2 should be non-zero");
require(secretHashes_[2] != bytes32(0) && secretHashes_[3] != bytes32(0), "Funds.request: SecretHash3 & SecretHash4 should be non-zero");
require(secretHashes_[4] != bytes32(0) && secretHashes_[5] != bytes32(0), "Funds.request: SecretHash5 & SecretHash6 should be non-zero");
require(secretHashes_[6] != bytes32(0) && secretHashes_[7] != bytes32(0), "Funds.request: SecretHash7 & SecretHash8 should be non-zero");
loanIndex = CREATELOAN338(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_);
LOANSETSECRETHASHES310(fund, loanIndex, secretHashes_, pubKeyA_, pubKeyB_);
LOANUPDATEMARKETLIQUIDITY912(fund, amount_);
loans.FUND172(loanIndex);
emit REQUEST101(fund, borrower_, amount_, collateral_, loanDur_, requestTimestamp_);
}
function WITHDRAW186(bytes32 fund, uint256 amount_) external { //inject NONSTANDARD NAMING
WITHDRAWTO298(fund, amount_, msg.sender);
}
function WITHDRAWTO298(bytes32 fund, uint256 amount_, address recipient_) public { //inject NONSTANDARD NAMING
require(msg.sender == LENDER92(fund), "Funds.withdrawTo: Only the lender can withdraw tokens");
require(BALANCE334(fund) >= amount_, "Funds.withdrawTo: Insufficient balance");
if (bools[fund].compoundEnabled) {
uint256 cBalanceBefore = cToken.BALANCEOF227(address(this));
REDEEMUNDERLYING614(address(cToken), amount_);
uint256 cBalanceAfter = cToken.BALANCEOF227(address(this));
uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter);
funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove);
require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed");
if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);}
} else {
funds[fund].balance = SUB97(funds[fund].balance, amount_);
require(token.TRANSFER744(recipient_, amount_), "Funds.withdrawTo: Token transfer failed");
if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);}
}
if (!CUSTOM642(fund)) {CALCGLOBALINTEREST773();}
emit WITHDRAW160(fund, amount_, recipient_);
}
function GENERATE494(bytes32[] calldata secretHashes_) external { //inject NONSTANDARD NAMING
for (uint i = 0; i < secretHashes_.length; i++) {
secretHashes[msg.sender].push(secretHashes_[i]);
}
}
function SETPUBKEY352(bytes calldata pubKey_) external { //inject NONSTANDARD NAMING
pubKeys[msg.sender] = pubKey_;
}
function ENABLECOMPOUND230(bytes32 fund) external { //inject NONSTANDARD NAMING
require(compoundSet, "Funds.enableCompound: Cannot enable Compound as it has not been configured");
require(bools[fund].compoundEnabled == false, "Funds.enableCompound: Compound is already enabled");
require(msg.sender == LENDER92(fund), "Funds.enableCompound: Only the lender can enable Compound");
uint256 cBalanceBefore = cToken.BALANCEOF227(address(this));
MINTCTOKEN703(address(token), address(cToken), funds[fund].balance);
uint256 cBalanceAfter = cToken.BALANCEOF227(address(this));
uint256 cTokenToReturn = SUB97(cBalanceAfter, cBalanceBefore);
tokenMarketLiquidity = SUB97(tokenMarketLiquidity, funds[fund].balance);
cTokenMarketLiquidity = ADD803(cTokenMarketLiquidity, cTokenToReturn);
bools[fund].compoundEnabled = true;
funds[fund].balance = 0;
funds[fund].cBalance = cTokenToReturn;
emit ENABLECOMPOUND170(fund);
}
function DISABLECOMPOUND481(bytes32 fund) external { //inject NONSTANDARD NAMING
require(bools[fund].compoundEnabled, "Funds.disableCompound: Compound is already disabled");
require(msg.sender == LENDER92(fund), "Funds.disableCompound: Only the lender can disable Compound");
uint256 balanceBefore = token.BALANCEOF227(address(this));
REDEEMCTOKEN224(address(cToken), funds[fund].cBalance);
uint256 balanceAfter = token.BALANCEOF227(address(this));
uint256 tokenToReturn = SUB97(balanceAfter, balanceBefore);
tokenMarketLiquidity = ADD803(tokenMarketLiquidity, tokenToReturn);
cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, funds[fund].cBalance);
bools[fund].compoundEnabled = false;
funds[fund].cBalance = 0;
funds[fund].balance = tokenToReturn;
emit DISABLECOMPOUND118(fund);
}
function DECREASETOTALBORROW522(uint256 amount_) external { //inject NONSTANDARD NAMING
require(msg.sender == address(loans), "Funds.decreaseTotalBorrow: Only the Loans contract can perform this");
totalBorrow = SUB97(totalBorrow, amount_);
}
function CALCGLOBALINTEREST773() public { //inject NONSTANDARD NAMING
marketLiquidity = ADD803(tokenMarketLiquidity, WMUL533(cTokenMarketLiquidity, CTOKENEXCHANGERATE725()));
if (now > (ADD803(lastGlobalInterestUpdated, interestUpdateDelay))) {
uint256 utilizationRatio;
if (totalBorrow != 0) {utilizationRatio = RDIV519(totalBorrow, ADD803(marketLiquidity, totalBorrow));}
if (utilizationRatio > lastUtilizationRatio) {
uint256 changeUtilizationRatio = SUB97(utilizationRatio, lastUtilizationRatio);
globalInterestRateNumerator = MIN456(maxInterestRateNumerator, ADD803(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor)));
} else {
uint256 changeUtilizationRatio = SUB97(lastUtilizationRatio, utilizationRatio);
globalInterestRateNumerator = MAX638(minInterestRateNumerator, SUB97(globalInterestRateNumerator, RDIV519(MIN456(maxUtilizationDelta, changeUtilizationRatio), utilizationInterestDivisor)));
}
globalInterestRate = ADD803(ray271, DIV358(globalInterestRateNumerator, num_seconds_in_year521));
lastGlobalInterestUpdated = now;
lastUtilizationRatio = utilizationRatio;
}
}
function CALCINTEREST818(uint256 amount_, uint256 rate_, uint256 loanDur_) public pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB97(RMUL965(amount_, RPOW933(rate_, loanDur_)), amount_);
}
function ENSURENOTZERO255(uint256 value, bool addNow) public view returns (uint256) { //inject NONSTANDARD NAMING
if (value == 0) {
if (addNow) {
return now + max_loan_length66;
}
return max_loan_length66;
}
return value;
}
function CREATELOAN338( //inject NONSTANDARD NAMING
bytes32 fund,
address borrower_,
uint256 amount_,
uint256 collateral_,
uint256 loanDur_,
uint256 requestTimestamp_
) private returns (bytes32 loanIndex) {
loanIndex = loans.CREATE943(
now + loanDur_,
[borrower_, LENDER92(fund), funds[fund].arbiter],
[
amount_,
CALCINTEREST818(amount_, INTEREST523(fund), loanDur_),
CALCINTEREST818(amount_, PENALTY434(fund), loanDur_),
CALCINTEREST818(amount_, FEE426(fund), loanDur_),
collateral_,
LIQUIDATIONRATIO684(fund),
requestTimestamp_
],
fund
);
}
function LOANSETSECRETHASHES310( //inject NONSTANDARD NAMING
bytes32 fund,
bytes32 loan,
bytes32[8] memory secretHashes_,
bytes memory pubKeyA_,
bytes memory pubKeyB_
) private {
loans.SETSECRETHASHES742(
loan,
[ secretHashes_[0], secretHashes_[1], secretHashes_[2], secretHashes_[3] ],
[ secretHashes_[4], secretHashes_[5], secretHashes_[6], secretHashes_[7] ],
GETSECRETHASHESFORLOAN447(ARBITER4(fund)),
pubKeyA_,
pubKeyB_,
pubKeys[ARBITER4(fund)]
);
}
function LOANUPDATEMARKETLIQUIDITY912(bytes32 fund, uint256 amount_) private { //inject NONSTANDARD NAMING
if (bools[fund].compoundEnabled) {
uint256 cBalanceBefore = cToken.BALANCEOF227(address(this));
REDEEMUNDERLYING614(address(cToken), amount_);
uint256 cBalanceAfter = cToken.BALANCEOF227(address(this));
uint256 cTokenToRemove = SUB97(cBalanceBefore, cBalanceAfter);
funds[fund].cBalance = SUB97(funds[fund].cBalance, cTokenToRemove);
if (!CUSTOM642(fund)) {cTokenMarketLiquidity = SUB97(cTokenMarketLiquidity, cTokenToRemove);}
} else {
funds[fund].balance = SUB97(funds[fund].balance, amount_);
if (!CUSTOM642(fund)) {tokenMarketLiquidity = SUB97(tokenMarketLiquidity, amount_);}
}
if (!CUSTOM642(fund)) {
totalBorrow = ADD803(totalBorrow, amount_);
CALCGLOBALINTEREST773();
}
}
function GETSECRETHASHESFORLOAN447(address addr_) private returns (bytes32[4] memory) { //inject NONSTANDARD NAMING
secretHashIndex[addr_] = ADD803(secretHashIndex[addr_], 4);
require(SECRETHASHESCOUNT698(addr_) >= secretHashIndex[addr_], "Funds.getSecretHashesForLoan: Not enough secrets generated");
return [
secretHashes[addr_][SUB97(secretHashIndex[addr_], 4)],
secretHashes[addr_][SUB97(secretHashIndex[addr_], 3)],
secretHashes[addr_][SUB97(secretHashIndex[addr_], 2)],
secretHashes[addr_][SUB97(secretHashIndex[addr_], 1)]
];
}
} | inject NONSTANDARD NAMING | function SETTLEMENTEXPIRATION526(bytes32) external view returns (uint256); | 1,784,101 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.1;
/**
* @dev On-chain art generation for MoonCatLootprints
* Takes individual trait values as parameters, and outputs complete representations of them.
*/
contract MoonCatLootprintsMetadata {
string[5] internal class_names =
[
"Mech",
"Sub",
"Tank",
"Cruiser",
"Unknown"
];
/**
* @dev Convert a Classification ID number into a string name
*/
function getClassName(uint8 classId) public view returns (string memory) {
return class_names[classId];
}
string[15] internal color_names =
["Hero Silver",
"Genesis White",
"Genesis Black",
"Red",
"Orange",
"Yellow",
"Chartreuse",
"Green",
"Teal",
"Cyan",
"SkyBlue",
"Blue",
"Purple",
"Magenta",
"Fuchsia"];
/**
* @dev Convert a Color ID number into a string name
*/
function getColorName(uint8 colorId) public view returns (string memory) {
return color_names[colorId];
}
// Color codes used for the background color of an image representation
string[15] internal color_codes =
["#777777", // Silver
"#cccccc", // White
"#111111", // Black
"hsl(0,60%,38%)", // Red
"hsl(30,60%,38%)", // Orange
"hsl(60,60%,38%)", // Yellow
"hsl(80,60%,38%)", // Chartreuse
"hsl(120,60%,38%)", // Green
"hsl(150,60%,38%)", // Teal
"hsl(180,60%,38%)", // Cyan
"hsl(210,60%,38%)", // SkyBlue
"hsl(240,60%,38%)", // Blue
"hsl(270,60%,38%)", // Purple
"hsl(300,60%,38%)", // Magenta
"hsl(330,60%,38%)"]; // Fuchsia
// SVG codes for the different icons for each ship classification
string[4] public ship_images =
["<path class=\"s\" d=\"M-61.74,77.79h-12.61V32.32h12.61V77.79z M-28.03,26.64l-7.58-12.63v44.12h7.58V26.64z M-0.65,52.52h10.99 L41.41,1.36L24.74-12.66H-0.65h-25.39L-42.72,1.36l31.07,51.16H-0.65z M60.43,77.79h12.61V32.32H60.43V77.79z M26.73,58.14h7.58 V14.02l-7.58,12.63V58.14z\"/><path class=\"s\" d=\"M-23.89,32.56v4.77h-44.15V8.75h29.81 M-58.76,13.76h-18.55v18.55h18.55V13.76z M22.59,32.56v4.77h44.15V8.75 H36.92 M57.46,32.32h18.55V13.76H57.46V32.32z M5.79,46.98L5.79,46.98c0-1.07-0.87-1.94-1.94-1.94h-9c-1.07,0-1.94,0.87-1.94,1.94 v0c0,1.07,0.87,1.94,1.94,1.94h9C4.92,48.93,5.79,48.06,5.79,46.98z\"/><path class=\"s s1\" d=\"M-79.92,94.43V86.1 M-56.04,94.43V86.1 M78.61,94.43V86.1 M54.74,94.43V86.1 M-14.48,5.33h28.04 M-9.45,1.1 H8.52\"/><path class=\"s s1\" d=\"M-44.11,94.43h-47.87V82.76c0-2.76,2.24-5,5-5h37.87c2.76,0,5,2.24,5,5V94.43z M-19.88,57.67v-6.18 c0-1.64-1.33-2.97-2.97-2.97h-9.15v12.13h9.15C-21.22,60.65-19.88,59.32-19.88,57.67z M42.8,94.43h47.87V82.76c0-2.76-2.24-5-5-5 H47.8c-2.76,0-5,2.24-5,5V94.43z M-0.65,31.11h14.08L33.42,3.86L25.39,2.2l-8.96,8.83H-0.65h-17.08l-8.96-8.83l-8.04,1.66 l19.99,27.25H-0.65z M21.55,60.65h9.15V48.52h-9.15c-1.64,0-2.97,1.33-2.97,2.97v6.18C18.58,59.32,19.91,60.65,21.55,60.65z\"/><path class=\"s s1\" d=\"M-26.04-12.66l-11.17,9.4v-27.46h7.51l16.17,18.06H-26.04z M24.74-12.66l11.17,9.4v-27.46H28.4L12.23-12.66 H24.74z\"/><path class=\"s s2\" d=\"M-19.88,52.86h-3.79 M-19.88,56.46h-3.79 M22.37,52.86h-3.79 M18.58,56.46h3.79\"/> <path class=\"s s2\" d=\"M-39.67,8.41l-1.58,33.83h-11.47l-1.58-33.83c0-4.04,3.28-7.32,7.32-7.32C-42.95,1.1-39.67,4.37-39.67,8.41z M-43.38,42.24h-6.9l-1.01,4.74h8.91L-43.38,42.24z M38.37,8.41l1.58,33.83h11.47L53,8.41c0-4.04-3.28-7.32-7.32-7.32 C41.64,1.1,38.37,4.37,38.37,8.41z M41.06,46.98h8.91l-1.01-4.74h-6.9L41.06,46.98z\"/>", // Mech
"<path class=\"s\" d=\"M55.52,60.62l-125.85,7.15c-13.35,0.76-24.59-9.86-24.59-23.23v0c0-13.37,11.24-23.99,24.59-23.23l125.85,7.15 V60.62z\"/><path class=\"s\" d=\"M48.39,42.2v10.28l-5.47-1.16v-7.96L48.39,42.2z M63.26,21.92L63.26,21.92c-2.75,0-4.82,2.5-4.31,5.2 l3.33,17.61h1.97l3.33-17.61C68.09,24.42,66.01,21.92,63.26,21.92z M63.26,67.55L63.26,67.55c2.75,0,4.82-2.5,4.31-5.2l-3.33-17.61 h-1.97l-3.33,17.61C58.44,65.05,60.51,67.55,63.26,67.55z M-44.97,43.64L-44.97,43.64c0.76,0.76,1.99,0.76,2.75,0l6.36-6.36 c0.76-0.76,0.76-1.99,0-2.75l0,0c-0.76-0.76-1.99-0.76-2.75,0l-6.36,6.36C-45.72,41.65-45.72,42.88-44.97,43.64z M-34.82,43.64 L-34.82,43.64c0.76,0.76,1.99,0.76,2.75,0l6.36-6.36c0.76-0.76,0.76-1.99,0-2.75l0,0c-0.76-0.76-1.99-0.76-2.75,0l-6.36,6.36 C-35.58,41.65-35.58,42.88-34.82,43.64z M63.26,43.33h-7.74v2.81h7.74V43.33z\"/><path class=\"s\" d=\"M-71.47,62.75v15.73 M-65.61,62.75v22.93\"/> <path class=\"s s1\" d=\"M52.24,60.8l1.72,11.04l19.89,4.4v6.21L38.9,88.39c-8.09,1.37-15.55-4.68-15.87-12.88l-0.51-13.03 M51.24,28.2 L67.16,2.56l-80.25-3.16c-6.16-0.24-12.13,2.16-16.4,6.61l-16.03,16.69\"/><path class=\"s s1\" d=\"M3.89,39.09l39.03,1.83v13.24L3.89,55.98c-4.66,0-8.44-3.78-8.44-8.44C-4.56,42.87-0.78,39.09,3.89,39.09z M-42.74,31.11l-31.49-1.26c-5.73,0-10.75,3.81-12.3,9.33l-0.67,5.36h29.01L-42.74,31.11z M30.03,47.53L30.03,47.53 c0-1.07-0.87-1.94-1.94-1.94h-9c-1.07,0-1.94,0.87-1.94,1.94v0c0,1.07,0.87,1.94,1.94,1.94h9C29.16,49.47,30.03,48.6,30.03,47.53z\"/>", // Sub
"<path class=\"s\" d=\"M-41.05,64.38H-76.3c-9.83,0-17.79-7.98-17.77-17.8l0.02-7.96l53-31.34V64.38z M-33.49,21.94v36.39l12.96,9.64 c7.01,5.22,15.52,8.03,24.26,8.03h50.54V7.29l-12-2.39C27.98,2.05,13.19,3.4-0.34,8.77L-33.49,21.94z\"/> <path class=\"s\" d=\"M-53.74,49.67l93.8-17.28 M-53.74,96.38h99.86 M-60.37,44.65L-60.37,44.65c0-1.07-0.87-1.94-1.94-1.94h-9 c-1.07,0-1.94,0.87-1.94,1.94v0c0,1.07,0.87,1.94,1.94,1.94h9C-61.24,46.59-60.37,45.72-60.37,44.65z M-60.37,37.78L-60.37,37.78 c0-1.07-0.87-1.94-1.94-1.94h-9c-1.07,0-1.94,0.87-1.94,1.94v0c0,1.07,0.87,1.94,1.94,1.94h9C-61.24,39.72-60.37,38.85-60.37,37.78 z M-33.49,26.33h-7.56v27.92h7.56V26.33z\"/><path class=\"s s1\" d=\"M-0.29,30.83v-9c0-1.07,0.87-1.94,1.94-1.94h0c1.07,0,1.94,0.87,1.94,1.94v9c0,1.07-0.87,1.94-1.94,1.94h0 C0.58,32.77-0.29,31.9-0.29,30.83z M1.47-0.14c-4.66,0-8.44,3.78-8.44,8.44l1.83,39.03H8.08L9.91,8.3 C9.91,3.64,6.13-0.14,1.47-0.14z\"/> <path class=\"s s1\" d=\"M42.26,32.38c-17.67,0-32,14.33-32,32s14.33,32,32,32s32-14.33,32-32S59.94,32.38,42.26,32.38z M42.26,89.98 c-14.14,0-25.6-11.46-25.6-25.6s11.46-25.6,25.6-25.6s25.6,11.46,25.6,25.6S56.4,89.98,42.26,89.98z M-51.74,49.57 c-12.93,0-23.4,10.48-23.4,23.41c0,12.93,10.48,23.4,23.4,23.4s23.4-10.48,23.4-23.4C-28.33,60.05-38.81,49.57-51.74,49.57z M-51.74,91.7c-10.34,0-18.72-8.38-18.72-18.72c0-10.34,8.38-18.72,18.72-18.72s18.72,8.38,18.72,18.72 C-33.01,83.32-41.4,91.7-51.74,91.7z M-46.35,29.02h-14.78l14.4-10.61L-46.35,29.02z M6.8,52.81H-3.49l1.16-5.47h7.96L6.8,52.81z M54.26,20.3l9-3v18.97l-9-3.28 M54.26,53.04l9-3v18.97l-9-3.28\"/>", // Tank
"<path class=\"s\" d=\"M0.26,93.33h14.33c0,0-0.76-11.46-2.27-32s13.64-76.47,19.95-99.97s-2.52-60.03-32-60.03 s-38.31,36.54-32,60.03s21.46,79.43,19.95,99.97s-2.27,32-2.27,32H0.26\"/><path class=\"s\" d=\"M-12.9,76.57l-47.02,6.06l3.03-18.95l43.64-22.42 M-26.38-18.46l-9.09,14.31v19.33l14.78-10.8 M13.42,76.57 l47.02,6.06l-3.03-18.95L13.77,41.25 M21.22,4.37L36,15.17V-4.15l-9.09-14.31\"/><path class=\"s s1\" d=\"M-33.66,46.63l-1.83,39.03h-13.24l-1.83-39.03c0-4.66,3.78-8.44,8.44-8.44 C-37.44,38.18-33.66,41.96-33.66,46.63z M34.19,46.63l1.83,39.03h13.24l1.83-39.03c0-4.66-3.78-8.44-8.44-8.44 C37.97,38.18,34.19,41.96,34.19,46.63z\"/><path class=\"s s1\" d=\"M-19.18-74.83c1.04,1.8,0.95,17.15,3.03,27c1.51,7.14,4.01,15.92,2.38,18.14c-1.43,1.94-7.59,1.24-9.95-1.37 c-3.41-3.78-4.15-10.56-4.93-16.67C-30.13-59.39-22.35-80.31-19.18-74.83z M-37.94,85.66h-7.96l-1.16,5.47h10.28L-37.94,85.66z M-10.65,93.33l-1.33,8.05H0.26h12.24l-1.33-8.05 M0.26-34.67c0,0,1.82,0,6.12,0s7.45-32,7.04-43S9.28-88.66,0.26-88.66 s-12.75-0.01-13.16,10.99c-0.41,11,2.74,43,7.04,43S0.26-34.67,0.26-34.67z M19.71-74.83c-1.04,1.8-0.95,17.15-3.03,27 c-1.51,7.14-4.01,15.92-2.38,18.14c1.43,1.94,7.59,1.24,9.95-1.37c3.41-3.78,4.15-10.56,4.93-16.67 C30.65-59.39,22.88-80.31,19.71-74.83z M37.3,91.13h10.28l-1.16-5.47h-7.96L37.3,91.13z\"/>" // Cruiser
];
/**
* @dev Render an SVG of a ship with the specified features.
*/
function getImage (uint256 lootprintId, uint8 classId, uint8 colorId, uint8 bays, string calldata shipName)
public
view
returns (string memory)
{
string memory regStr = uint2str(lootprintId);
string memory baysStr = uint2str(bays);
string[15] memory parts;
parts[0] = "<svg xmlns=\"http://www.w3.org/2000/svg\" preserveAspectRatio=\"xMinYMin meet\" viewBox=\"0 0 600 600\"><style> .s{fill:white;stroke:white;stroke-width:2;stroke-miterlimit:10;fill-opacity:0.1;stroke-linecap:round}.s1{fill-opacity:0.3}.s2{stroke-width:1}.t{ fill:white;font-family:serif;font-size:20px;}.k{font-weight:bold;text-anchor:end;fill:#ddd;}.n{font-size:22px;font-weight:bold;text-anchor:middle}.l{fill:none;stroke:rgb(230,230,230,0.5);stroke-width:1;clip-path:url(#c);}.r{fill:rgba(0,0,0,0.5);stroke:white;stroke-width:3;}.r1{stroke-width: 1} .a{fill:#FFFFFF;fill-opacity:0.1;stroke:#FFFFFF;stroke-width:2;stroke-miterlimit:10;}.b{fill:none;stroke:#FFFFFF;stroke-width:2;stroke-miterlimit:10;} .c{fill:#FFFFFF;fill-opacity:0.2;stroke:#FFFFFF;stroke-width:2;stroke-miterlimit:10;} .d{fill:#FFFFFF;fill-opacity:0.3;stroke:#FFFFFF;stroke-width:2;stroke-miterlimit:10;}</style><defs><clipPath id=\"c\"><rect width=\"600\" height=\"600\" /></clipPath></defs><rect width=\"600\" height=\"600\" fill=\"";
parts[1] = color_codes[colorId];
parts[2] = "\"/><polyline class=\"l\" points=\"40,-5 40,605 80,605 80,-5 120,-5 120,605 160,605 160,-5 200,-5 200,605 240,605 240,-5 280,-5 280,605 320,605 320,-5 360,-5 360,605 400,605 400,-5 440,-5 440,605 480,605 480,-5 520,-5 520,605 560,605 560,-5 600,-5 600,605\" /><polyline class=\"l\" points=\"-5,40 605,40 605,80 -5,80 -5,120 605,120 605,160 -5,160 -5,200 605,200 605,240 -5,240 -5,280 605,280 605,320 -5,320 -5,360 605,360 605,400 -5,400 -5,440 605,440 605,480 -5,480 -5,520 605,520 605,560 -5,560 -5,600 605,600\" /><rect class=\"r\" x=\"10\" y=\"10\" width=\"580\" height=\"50\" rx=\"15\" /><rect class=\"l r r1\" x=\"-5\" y=\"80\" width=\"285\" height=\"535\" /><text class=\"t n\" x=\"300\" y=\"42\">";
parts[3] = shipName;
parts[4] = "</text><text class=\"t k\" x=\"115\" y=\"147\">Reg:</text><text class=\"t\" x=\"125\" y=\"147\">#";
parts[5] = regStr;
parts[6] = "</text><text class=\"t k\" x=\"115\" y=\"187\">Class:</text><text class=\"t\" x=\"125\" y=\"187\">";
parts[7] = class_names[classId];
parts[8] = "</text><text class=\"t k\" x=\"115\" y=\"227\">Color:</text><text class=\"t\" x=\"125\" y=\"227\">";
parts[9] = color_names[colorId];
parts[10] = "</text><text class=\"t k\" x=\"115\" y=\"267\">Bays:</text><text class=\"t\" x=\"125\" y=\"267\">";
parts[11] = baysStr;
parts[12] = "</text><g transform=\"translate(440,440)scale(1.2)\">";
if (classId < 4) {
parts[13] = ship_images[classId];
}
parts[14] = "</g></svg>";
bytes memory svg0 = abi.encodePacked(parts[0], parts[1], parts[2],
parts[3], parts[4], parts[5],
parts[6], parts[7], parts[8]);
bytes memory svg1 = abi.encodePacked(parts[9], parts[10], parts[11],
parts[12], parts[13], parts[14]);
return string(abi.encodePacked("data:image/svg+xml;base64,", Base64.encode(abi.encodePacked(svg0, svg1))));
}
/**
* @dev Encode a key/value pair as a JSON trait property, where the value is a numeric item (doesn't need quotes)
*/
function encodeAttribute(string memory key, string memory value) internal pure returns (string memory) {
return string(abi.encodePacked("{\"trait_type\":\"", key,"\",\"value\":",value,"}"));
}
/**
* @dev Encode a key/value pair as a JSON trait property, where the value is a string item (needs quotes around it)
*/
function encodeStringAttribute(string memory key, string memory value) internal pure returns (string memory) {
return string(abi.encodePacked("{\"trait_type\":\"", key,"\",\"value\":\"",value,"\"}"));
}
/**
* @dev Render a JSON metadata object of a ship with the specified features.
*/
function getJSON(uint256 lootprintId, uint8 classId, uint8 colorId, uint8 bays, string calldata shipName)
public
view
returns (string memory) {
string memory colorName = color_names[colorId];
string memory svg = getImage(lootprintId, classId, colorId, bays, shipName);
bytes memory tokenName = abi.encodePacked("Lootprint #", uint2str(lootprintId), ": ", shipName);
bytes memory json = abi.encodePacked("{",
"\"attributes\":[",
encodeAttribute("Registration #", uint2str(lootprintId)), ",",
encodeStringAttribute("Class", class_names[classId]), ",",
encodeAttribute("Bays", uint2str(bays)), ",",
encodeStringAttribute("Color", colorName),
"],\"name\":\"", tokenName,
"\",\"description\":\"Build Plans for a MoonCat Spacecraft\",\"image\":\"", svg,
"\"}");
return string(abi.encodePacked('data:application/json;base64,', Base64.encode(json)));
}
/* Utilities */
function uint2str(uint 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);
}
}
/// [MIT License]
/// @title Base64
/// @notice Provides a function for encoding some bytes in base64
/// @author Brecht Devos <[email protected]>
library Base64 {
bytes internal constant TABLE = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
/// @notice Encodes some bytes to the base64 representation
function encode(bytes memory data) internal pure returns (string memory) {
uint256 len = data.length;
if (len == 0) return "";
// multiply by 4/3 rounded up
uint256 encodedLen = 4 * ((len + 2) / 3);
// Add some extra buffer at the end
bytes memory result = new bytes(encodedLen + 32);
bytes memory table = TABLE;
assembly {
let tablePtr := add(table, 1)
let resultPtr := add(result, 32)
for {
let i := 0
} lt(i, len) {
} {
i := add(i, 3)
let input := and(mload(add(data, i)), 0xffffff)
let out := mload(add(tablePtr, and(shr(18, input), 0x3F)))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(12, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(shr(6, input), 0x3F))), 0xFF))
out := shl(8, out)
out := add(out, and(mload(add(tablePtr, and(input, 0x3F))), 0xFF))
out := shl(224, out)
mstore(resultPtr, out)
resultPtr := add(resultPtr, 4)
}
switch mod(len, 3)
case 1 {
mstore(sub(resultPtr, 2), shl(240, 0x3d3d))
}
case 2 {
mstore(sub(resultPtr, 1), shl(248, 0x3d))
}
mstore(result, encodedLen)
}
return string(result);
}
}
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.8.1;
interface IMoonCatAcclimator {
function getApproved(uint256 tokenId) external view returns (address);
function isApprovedForAll(address owner, address operator) external view returns (bool);
function ownerOf(uint256 tokenId) external view returns (address);
}
interface IMoonCatRescue {
function rescueOrder(uint256 tokenId) external view returns (bytes5);
function catOwners(bytes5 catId) external view returns (address);
}
interface IReverseResolver {
function claim(address owner) external returns (bytes32);
}
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
interface IERC721 is IERC165 {
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
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;
}
interface IERC721Metadata is IERC721 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
interface IERC721Enumerable is IERC721 {
function totalSupply() external view returns (uint256);
function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId);
function tokenByIndex(uint256 index) external view returns (uint256);
}
interface IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
interface IERC20 {
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
}
interface IMoonCatLootprintsMetadata {
function getJSON(uint256 lootprintId,
uint8 classId,
uint8 colorId,
uint8 bays,
string calldata shipName)
external view returns (string memory);
function getImage(uint256 lootprintId,
uint8 classId,
uint8 colorId,
uint8 bays,
string calldata shipName)
external view returns (string memory);
function getClassName(uint8 classId) external view returns (string memory);
function getColorName(uint8 classId) external view returns (string memory);
}
/**
* @dev Derived from OpenZeppelin standard template
* https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/structs/EnumerableSet.sol
* b0cf6fbb7a70f31527f36579ad644e1cf12fdf4e
*/
library EnumerableSet {
struct Set {
uint256[] _values;
mapping (uint256 => uint256) _indexes;
}
function at(Set storage set, uint256 index) internal view returns (uint256) {
return set._values[index];
}
function contains(Set storage set, uint256 value) internal view returns (bool) {
return set._indexes[value] != 0;
}
function length(Set storage set) internal view returns (uint256) {
return set._values.length;
}
function add(Set storage set, uint256 value) internal 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;
}
}
function remove(Set storage set, uint256 value) internal 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) {
uint256 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;
}
}
}
/**
* @title MoonCatLootprints
* @dev MoonCats have found some plans for building spaceships
*/
contract MoonCatLootprints is IERC165, IERC721Enumerable, IERC721Metadata {
/* ERC-165 */
function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165) returns (bool) {
return (interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId);
}
/* External Contracts */
IMoonCatAcclimator MCA = IMoonCatAcclimator(0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69);
IMoonCatRescue MCR = IMoonCatRescue(0x60cd862c9C687A9dE49aecdC3A99b74A4fc54aB6);
IMoonCatLootprintsMetadata public Metadata;
/* Name String Data */
string[4] internal honorifics =
[
"Legendary",
"Notorious",
"Distinguished",
"Renowned"
];
string[32] internal adjectives =
[
"Turbo",
"Tectonic",
"Rugged",
"Derelict",
"Scratchscarred",
"Purrfect",
"Rickety",
"Sparkly",
"Ethereal",
"Hissing",
"Pouncing",
"Stalking",
"Standing",
"Sleeping",
"Playful",
"Menancing", // Poor Steve.
"Cuddly",
"Neurotic",
"Skittish",
"Impulsive",
"Sly",
"Ponderous",
"Prodigal",
"Hungry",
"Grumpy",
"Harmless",
"Mysterious",
"Frisky",
"Furry",
"Scratchy",
"Patchy",
"Hairless"
];
string[15] internal mods =
[
"Star",
"Galaxy",
"Constellation",
"World",
"Moon",
"Alley",
"Midnight",
"Wander",
"Tuna",
"Mouse",
"Catnip",
"Toy",
"Kibble",
"Hairball",
"Litterbox"
];
string[32] internal mains =
[
"Lightning",
"Wonder",
"Toebean",
"Whisker",
"Paw",
"Fang",
"Tail",
"Purrbox",
"Meow",
"Claw",
"Scratcher",
"Chomper",
"Nibbler",
"Mouser",
"Racer",
"Teaser",
"Chaser",
"Hunter",
"Leaper",
"Sleeper",
"Pouncer",
"Stalker",
"Stander",
"TopCat",
"Ambassador",
"Admiral",
"Commander",
"Negotiator",
"Vandal",
"Mischief",
"Ultimatum",
"Frolic"
];
string[16] internal designations =
[
"Alpha",
"Tau",
"Pi",
"I",
"II",
"III",
"IV",
"V",
"X",
"Prime",
"Proper",
"1",
"1701-D",
"2017",
"A",
"Runt"
];
/* Data */
bytes32[400] ColorTable;
/* Structs */
struct Lootprint {
uint16 index;
address owner;
}
/* State */
using EnumerableSet for EnumerableSet.Set;
address payable public contractOwner;
bool public frozen = true;
bool public mintingWindowOpen = true;
uint8 revealCount = 0;
uint256 public price = 50000000000000000;
bytes32[100] NoChargeList;
bytes32[20] revealBlockHashes;
Lootprint[25600] public Lootprints; // lootprints by lootprintId/rescueOrder
EnumerableSet.Set internal LootprintIdByIndex;
mapping(address => EnumerableSet.Set) internal LootprintsByOwner;
mapping(uint256 => address) private TokenApprovals; // lootprint id -> approved address
mapping(address => mapping(address => bool)) private OperatorApprovals; // owner address -> operator address -> bool
/* Modifiers */
modifier onlyContractOwner () {
require(msg.sender == contractOwner, "Only Contract Owner");
_;
}
modifier lootprintExists (uint256 lootprintId) {
require(LootprintIdByIndex.contains(lootprintId), "ERC721: operator query for nonexistent token");
_;
}
modifier onlyOwnerOrApproved(uint256 lootprintId) {
require(LootprintIdByIndex.contains(lootprintId), "ERC721: query for nonexistent token");
address owner = ownerOf(lootprintId);
require(msg.sender == owner || msg.sender == TokenApprovals[lootprintId] || OperatorApprovals[owner][msg.sender],
"ERC721: transfer caller is not owner nor approved");
_;
}
modifier notFrozen () {
require(!frozen, "Frozen");
_;
}
/* ERC-721 Helpers */
function setApprove(address to, uint256 lootprintId) private {
TokenApprovals[lootprintId] = to;
emit Approval(msg.sender, to, lootprintId);
}
function handleTransfer(address from, address to, uint256 lootprintId) private {
require(to != address(0), "ERC721: transfer to the zero address");
setApprove(address(0), lootprintId);
LootprintsByOwner[from].remove(lootprintId);
LootprintsByOwner[to].add(lootprintId);
Lootprints[lootprintId].owner = to;
emit Transfer(from, to, lootprintId);
}
/* ERC-721 */
function totalSupply() public view override returns (uint256) {
return LootprintIdByIndex.length();
}
function balanceOf(address owner) public view override returns (uint256 balance) {
return LootprintsByOwner[owner].length();
}
function ownerOf(uint256 lootprintId) public view override returns (address owner) {
return Lootprints[lootprintId].owner;
}
function approve(address to, uint256 lootprintId) public override lootprintExists(lootprintId) {
address owner = ownerOf(lootprintId);
require(to != owner, "ERC721: approval to current owner");
require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all");
setApprove(to, lootprintId);
}
function getApproved(uint256 lootprintId) public view override returns (address operator) {
return TokenApprovals[lootprintId];
}
function setApprovalForAll(address operator, bool approved) public override {
require(operator != msg.sender, "ERC721: approve to caller");
OperatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(msg.sender, operator, approved);
}
function isApprovedForAll(address owner, address operator) public view override returns (bool) {
return OperatorApprovals[owner][operator];
}
function safeTransferFrom(address from, address to, uint256 lootprintId, bytes memory _data) public override onlyOwnerOrApproved(lootprintId) {
handleTransfer(from, to, lootprintId);
uint256 size;
assembly {
size := extcodesize(to)
}
if (size > 0) {
try IERC721Receiver(to).onERC721Received(msg.sender, from, lootprintId, _data) returns (bytes4 retval) {
if (retval != IERC721Receiver.onERC721Received.selector) {
revert("ERC721: transfer to non ERC721Receiver implementer");
}
} catch (bytes memory reason) {
if (reason.length == 0) {
revert("ERC721: transfer to non ERC721Receiver implementer");
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
}
}
function safeTransferFrom(address from, address to, uint256 lootprintId) public override {
safeTransferFrom(from, to, lootprintId, "");
}
function transferFrom(address from, address to, uint256 lootprintId) public override onlyOwnerOrApproved(lootprintId) {
handleTransfer(from, to, lootprintId);
}
/* ERC-721 Enumerable */
function tokenByIndex(uint256 index) public view override returns (uint256) {
return LootprintIdByIndex.at(index);
}
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds");
return LootprintsByOwner[owner].at(index);
}
/* Reveal */
bool pendingReveal = false;
uint256 revealPrepBlock;
bytes32 revealSeedHash;
/**
* @dev How many lootprints are awaiting being revealed?
*/
function pendingRevealCount() public view returns (uint256) {
uint256 numRevealed = revealCount * 2560;
if (numRevealed > LootprintIdByIndex.length()) return 0;
return LootprintIdByIndex.length() - numRevealed;
}
/**
* @dev Start a reveal action.
* The hash submitted here must be the keccak256 hash of a secret number that will be submitted to the next function
*/
function prepReveal(bytes32 seedHash) public onlyContractOwner {
require(!pendingReveal && seedHash != revealSeedHash && revealCount < 20, "Prep Conditions Not Met");
revealSeedHash = seedHash;
revealPrepBlock = block.number;
pendingReveal = true;
}
/**
* @dev Finalize a reveal action.
* Must take place at least one block after the `prepReveal` action was taken
*/
function reveal(uint256 revealSeed) public onlyContractOwner{
require(pendingReveal
&& block.number > revealPrepBlock
&& keccak256(abi.encodePacked(revealSeed)) == revealSeedHash
, "Reveal Conditions Not Met");
if (block.number - revealPrepBlock < 255) {
bytes32 blockSeed = keccak256(abi.encodePacked(revealSeed, blockhash(revealPrepBlock)));
revealBlockHashes[revealCount] = blockSeed;
revealCount++;
}
pendingReveal = false;
}
/* Minting */
/**
* @dev Is the minting of a specific rescueOrder needing payment or is it free?
*/
function paidMint(uint256 rescueOrder) public view returns (bool) {
uint256 wordIndex = rescueOrder / 256;
uint256 bitIndex = rescueOrder % 256;
return (uint(NoChargeList[wordIndex] >> (255 - bitIndex)) & 1) == 0;
}
/**
* @dev Create the token
* Checks that the address minting is the current owner of the MoonCat, and ensures that MoonCat is Acclimated
*/
function handleMint(uint256 rescueOrder, address to) private {
require(mintingWindowOpen, "Minting Window Closed");
require(MCR.catOwners(MCR.rescueOrder(rescueOrder)) == 0xc3f733ca98E0daD0386979Eb96fb1722A1A05E69,
"Not Acclimated");
address moonCatOwner = MCA.ownerOf(rescueOrder);
require((msg.sender == moonCatOwner)
|| (msg.sender == MCA.getApproved(rescueOrder))
|| (MCA.isApprovedForAll(moonCatOwner, msg.sender)),
"Not AMC Owner or Approved"
);
require(!LootprintIdByIndex.contains(rescueOrder), "Already Minted");
Lootprints[rescueOrder] = Lootprint(uint16(LootprintIdByIndex.length()), to);
LootprintIdByIndex.add(rescueOrder);
LootprintsByOwner[to].add(rescueOrder);
emit Transfer(address(0), to, rescueOrder);
}
/**
* @dev Mint a lootprint, and give it to a specific address
*/
function mint(uint256 rescueOrder, address to) public payable notFrozen {
if (paidMint(rescueOrder)) {
require(address(this).balance >= price, "Insufficient Value");
contractOwner.transfer(price);
}
handleMint(rescueOrder, to);
if (address(this).balance > 0) {
// The buyer over-paid; transfer their funds back to them
payable(msg.sender).transfer(address(this).balance);
}
}
/**
* @dev Mint a lootprint, and give it to the address making the transaction
*/
function mint(uint256 rescueOrder) public payable {
mint(rescueOrder, msg.sender);
}
/**
* @dev Mint multiple lootprints, sending them all to a specific address
*/
function mintMultiple(uint256[] calldata rescueOrders, address to) public payable notFrozen {
uint256 totalPrice = 0;
for (uint i = 0; i < rescueOrders.length; i++) {
if (paidMint(rescueOrders[i])) {
totalPrice += price;
}
handleMint(rescueOrders[i], to);
}
require(address(this).balance >= totalPrice, "Insufficient Value");
if (totalPrice > 0) {
contractOwner.transfer(totalPrice);
}
if (address(this).balance > 0) {
// The buyer over-paid; transfer their funds back to them
payable(msg.sender).transfer(address(this).balance);
}
}
/**
* @dev Mint multiple lootprints, sending them all to the address making the transaction
*/
function mintMultiple(uint256[] calldata rescueOrders) public payable {
mintMultiple(rescueOrders, msg.sender);
}
/* Contract Owner */
constructor(address metadataContract) {
contractOwner = payable(msg.sender);
Metadata = IMoonCatLootprintsMetadata(metadataContract);
// https://docs.ens.domains/contract-api-reference/reverseregistrar#claim-address
IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148)
.claim(msg.sender);
}
/**
* @dev Mint the 160 Hero lootprint tokens, and give them to the contract owner
*/
function setupHeroShips(bool groupTwo) public onlyContractOwner {
uint startIndex = 25440;
if (groupTwo) {
startIndex = 25520;
}
require(Lootprints[startIndex].owner == address(0), "Already Set Up");
for (uint i = startIndex; i < (startIndex+80); i++) {
Lootprints[i] = Lootprint(uint16(LootprintIdByIndex.length()), contractOwner);
LootprintIdByIndex.add(i);
LootprintsByOwner[contractOwner].add(i);
emit Transfer(address(0), contractOwner, i);
}
}
/**
* @dev Update the contract used for image/JSON rendering
*/
function setMetadataContract(address metadataContract) public onlyContractOwner{
Metadata = IMoonCatLootprintsMetadata(metadataContract);
}
/**
* @dev Set configuration values for which MoonCat creates which color lootprint when minted
*/
function setColorTable(bytes32[] calldata table, uint startAt) public onlyContractOwner {
for (uint i = 0; i < table.length; i++) {
ColorTable[startAt + i] = table[i];
}
}
/**
* @dev Set configuration values for which MoonCats need to pay for minting a lootprint
*/
function setNoChargeList (bytes32[100] calldata noChargeList) public onlyContractOwner {
NoChargeList = noChargeList;
}
/**
* @dev Set configuration values for how much a paid lootprint costs
*/
function setPrice(uint256 priceWei) public onlyContractOwner {
price = priceWei;
}
/**
* @dev Allow current `owner` to transfer ownership to another address
*/
function transferOwnership (address payable newOwner) public onlyContractOwner {
contractOwner = newOwner;
}
/**
* @dev Prevent creating lootprints
*/
function freeze () public onlyContractOwner notFrozen {
frozen = true;
}
/**
* @dev Enable creating lootprints
*/
function unfreeze () public onlyContractOwner {
frozen = false;
}
/**
* @dev Prevent any further minting from happening
* Checks to ensure all have been revealed before allowing locking down the minting process
*/
function permanentlyCloseMintingWindow() public onlyContractOwner {
require(revealCount >= 20, "Reveal Pending");
mintingWindowOpen = false;
}
/* Property Decoders */
function decodeColor(uint256 rescueOrder) public view returns (uint8) {
uint256 wordIndex = rescueOrder / 64;
uint256 nibbleIndex = rescueOrder % 64;
bytes32 word = ColorTable[wordIndex];
return uint8(uint(word >> (252 - nibbleIndex * 4)) & 15);
}
function decodeName(uint32 seed) internal view returns (string memory) {
seed = seed >> 8;
uint index;
string[9] memory parts;
//honorific
index = seed & 15;
if (index < 8) {
parts[0] = "The ";
if (index < 4) {
parts[1] = honorifics[index];
parts[2] = " ";
}
}
seed >>= 4;
//adjective
if ((seed & 1) == 1) {
index = (seed >> 1) & 31;
parts[3] = adjectives[index];
parts[4] = " ";
}
seed >>= 6;
//mod
index = seed & 15;
if (index < 15) {
parts[5] = mods[index];
}
seed >>= 4;
//main
index = seed & 31;
parts[6] = mains[index];
seed >>= 5;
//designation
if ((seed & 1) == 1) {
index = (seed >> 1) & 15;
parts[7] = " ";
parts[8] = designations[index];
}
return string(abi.encodePacked(parts[0], parts[1], parts[2],
parts[3], parts[4], parts[5],
parts[6], parts[7], parts[8]));
}
function decodeClass(uint32 seed) internal pure returns (uint8) {
uint class_determiner = seed & 15;
if (class_determiner < 2) {
return 0;
} else if (class_determiner < 5) {
return 1;
} else if (class_determiner < 9) {
return 2;
} else {
return 3;
}
}
function decodeBays(uint32 seed) internal pure returns (uint8) {
uint bay_determiner = (seed >> 4) & 15;
if (bay_determiner < 3) {
return 5;
} else if (bay_determiner < 8) {
return 4;
} else {
return 3;
}
}
uint8 constant internal STATUS_NOT_MINTED = 0;
uint8 constant internal STATUS_NOT_MINTED_FREE = 1;
uint8 constant internal STATUS_PENDING = 2;
uint8 constant internal STATUS_MINTED = 3;
/**
* @dev Get detailed traits about a lootprint token
* Provides trait values in native contract return values, which can be used by other contracts
*/
function getDetails (uint256 lootprintId)
public
view
returns (uint8 status, string memory class, uint8 bays, string memory colorName, string memory shipName, address tokenOwner, uint32 seed)
{
Lootprint memory lootprint = Lootprints[lootprintId];
colorName = Metadata.getColorName(decodeColor(lootprintId));
tokenOwner = address(0);
if (LootprintIdByIndex.contains(lootprintId)) {
if (revealBlockHashes[lootprint.index / 1280] > 0) {
seed = uint32(uint256(keccak256(abi.encodePacked(lootprintId, revealBlockHashes[lootprint.index / 1280]))));
return (STATUS_MINTED,
Metadata.getClassName(decodeClass(seed)),
decodeBays(seed),
colorName,
decodeName(seed),
lootprint.owner,
seed);
}
status = STATUS_PENDING;
tokenOwner = lootprint.owner;
} else if (paidMint(lootprintId)) {
status = STATUS_NOT_MINTED;
} else {
status = STATUS_NOT_MINTED_FREE;
}
return (status, "Unknown", 0, colorName, "?", tokenOwner, 0);
}
/* ERC-721 Metadata */
function name() public pure override returns (string memory) {
return "MoonCatLootprint";
}
function symbol() public pure override returns (string memory) {
return unicode"📜";
}
function tokenURI(uint256 lootprintId) public view override lootprintExists(lootprintId) returns (string memory) {
Lootprint memory lootprint = Lootprints[lootprintId];
uint8 colorId = decodeColor(lootprintId);
if (revealBlockHashes[lootprint.index / 1280] > 0) {
uint32 seed = uint32(uint256(keccak256(abi.encodePacked(lootprintId, revealBlockHashes[lootprint.index / 1280]))));
uint8 classId = decodeClass(seed);
string memory shipName = decodeName(seed);
uint8 bays = decodeBays(seed);
return Metadata.getJSON(lootprintId, classId, colorId, bays, shipName);
} else {
return Metadata.getJSON(lootprintId, 4, colorId, 0, "?");
}
}
function imageURI(uint256 lootprintId) public view lootprintExists(lootprintId) returns (string memory) {
Lootprint memory lootprint = Lootprints[lootprintId];
uint8 colorId = decodeColor(lootprintId);
if (revealBlockHashes[lootprint.index / 1280] > 0) {
uint32 seed = uint32(uint256(keccak256(abi.encodePacked(lootprintId, revealBlockHashes[lootprint.index / 1280]))));
uint8 classId = decodeClass(seed);
string memory shipName = decodeName(seed);
uint8 bays = decodeBays(seed);
return Metadata.getImage(lootprintId, classId, colorId, bays, shipName);
} else {
return Metadata.getImage(lootprintId, 4, colorId, 0, "?");
}
}
/* Rescue Tokens */
/**
* @dev Rescue ERC20 assets sent directly to this contract.
*/
function withdrawForeignERC20(address tokenContract)
public
onlyContractOwner
{
IERC20 token = IERC20(tokenContract);
token.transfer(contractOwner, token.balanceOf(address(this)));
}
/**
* @dev Rescue ERC721 assets sent directly to this contract.
*/
function withdrawForeignERC721(address tokenContract, uint256 lootprintId)
public
onlyContractOwner
{
IERC721(tokenContract).safeTransferFrom(address(this), contractOwner, lootprintId);
}
}
| Finalize a reveal action. Must take place at least one block after the `prepReveal` action was taken/ | function reveal(uint256 revealSeed) public onlyContractOwner{
require(pendingReveal
&& block.number > revealPrepBlock
&& keccak256(abi.encodePacked(revealSeed)) == revealSeedHash
, "Reveal Conditions Not Met");
if (block.number - revealPrepBlock < 255) {
bytes32 blockSeed = keccak256(abi.encodePacked(revealSeed, blockhash(revealPrepBlock)));
revealBlockHashes[revealCount] = blockSeed;
revealCount++;
}
pendingReveal = false;
}
| 12,100,472 |
/**
*Submitted for verification at Etherscan.io on 2021-04-27
*/
// SPDX-License-Identifier: BUSL-1.1
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: @openzeppelin/contracts/math/Math.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// File: @openzeppelin/contracts/utils/ReentrancyGuard.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: @openzeppelin/contracts/utils/Context.sol
pragma solidity >=0.6.0 <0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router01.sol
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,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
// File: @uniswap/v2-periphery/contracts/interfaces/IUniswapV2Router02.sol
pragma solidity >=0.6.2;
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
// File: @uniswap/v2-core/contracts/interfaces/IUniswapV2Pair.sol
pragma solidity >=0.5.0;
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
// File: contracts/interfaces/IDMMLiquidityRouter.sol
pragma solidity 0.6.12;
/// @dev an simple interface for integration dApp to contribute liquidity
interface IDMMLiquidityRouter {
/**
* @param tokenA address of token in the pool
* @param tokenB address of token in the pool
* @param pool the address of the pool
* @param amountADesired the amount of tokenA users want to add to the pool
* @param amountBDesired the amount of tokenB users want to add to the pool
* @param amountAMin bounds to the extents to which amountB/amountA can go up
* @param amountBMin bounds to the extents to which amountB/amountA can go down
* @param vReserveRatioBounds bounds to the extents to which vReserveB/vReserveA can go (precision: 2 ** 112)
* @param to Recipient of the liquidity tokens.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function addLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
uint256[2] calldata vReserveRatioBounds,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityNewPool(
IERC20 tokenA,
IERC20 tokenB,
uint32 ampBps,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityNewPoolETH(
IERC20 token,
uint32 ampBps,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
/**
* @param token address of token in the pool
* @param pool the address of the pool
* @param amountTokenDesired the amount of token users want to add to the pool
* @dev msg.value equals to amountEthDesired
* @param amountTokenMin bounds to the extents to which WETH/token can go up
* @param amountETHMin bounds to the extents to which WETH/token can go down
* @param vReserveRatioBounds bounds to the extents to which vReserveB/vReserveA can go (precision: 2 ** 112)
* @param to Recipient of the liquidity tokens.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function addLiquidityETH(
IERC20 token,
address pool,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
uint256[2] calldata vReserveRatioBounds,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
/**
* @param tokenA address of token in the pool
* @param tokenB address of token in the pool
* @param pool the address of the pool
* @param liquidity the amount of lp token users want to burn
* @param amountAMin the minimum token retuned after burning
* @param amountBMin the minimum token retuned after burning
* @param to Recipient of the returned tokens.
* @param deadline Unix timestamp after which the transaction will revert.
*/
function removeLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
/**
* @param tokenA address of token in the pool
* @param tokenB address of token in the pool
* @param pool the address of the pool
* @param liquidity the amount of lp token users want to burn
* @param amountAMin the minimum token retuned after burning
* @param amountBMin the minimum token retuned after burning
* @param to Recipient of the returned tokens.
* @param deadline Unix timestamp after which the transaction will revert.
* @param approveMax whether users permit the router spending max lp token or not.
* @param r s v Signature of user to permit the router spending lp token
*/
function removeLiquidityWithPermit(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountA, uint256 amountB);
/**
* @param token address of token in the pool
* @param pool the address of the pool
* @param liquidity the amount of lp token users want to burn
* @param amountTokenMin the minimum token retuned after burning
* @param amountETHMin the minimum eth in wei retuned after burning
* @param to Recipient of the returned tokens.
* @param deadline Unix timestamp after which the transaction will revert
*/
function removeLiquidityETH(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
/**
* @param token address of token in the pool
* @param pool the address of the pool
* @param liquidity the amount of lp token users want to burn
* @param amountTokenMin the minimum token retuned after burning
* @param amountETHMin the minimum eth in wei retuned after burning
* @param to Recipient of the returned tokens.
* @param deadline Unix timestamp after which the transaction will revert
* @param approveMax whether users permit the router spending max lp token
* @param r s v signatures of user to permit the router spending lp token.
*/
function removeLiquidityETHWithPermit(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline,
bool approveMax,
uint8 v,
bytes32 r,
bytes32 s
) external returns (uint256 amountToken, uint256 amountETH);
/**
* @param amountA amount of 1 side token added to the pool
* @param reserveA current reserve of the pool
* @param reserveB current reserve of the pool
* @return amountB amount of the other token added to the pool
*/
function quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
}
// File: contracts/interfaces/IERC20Permit.sol
pragma solidity 0.6.12;
interface IERC20Permit is IERC20 {
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
}
// File: contracts/wrapper/LiquidityMigrator.sol
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
interface ILiquidityMigrator {
struct PermitData {
bool approveMax;
uint8 v;
bytes32 r;
bytes32 s;
}
struct PoolInfo {
address poolAddress;
uint32 poolAmp;
uint256[2] dmmVReserveRatioBounds;
}
event RemoveLiquidity(
address indexed tokenA,
address indexed tokenB,
address indexed uniPair,
uint256 liquidity,
uint256 amountA,
uint256 amountB
);
event Migrated(
address indexed tokenA,
address indexed tokenB,
uint256 dmmAmountA,
uint256 dmmAmountB,
uint256 dmmLiquidity,
PoolInfo info
);
/**
* @dev Migrate tokens from a pair to a Kyber Dmm Pool
* Supporting both normal tokens and tokens with fee on transfer
* Support create new pool with received tokens from removing, or
* add tokens to a given pool address
* @param uniPair pair for token that user wants to migrate from
* it should be compatible with UniswapPair's interface
* @param tokenA first token of the pool
* @param tokenB second token of the pool
* @param liquidity amount of LP tokens to migrate
* @param amountAMin min amount for tokenA when removing
* @param amountBMin min amount for tokenB when removing
* @param dmmAmountAMin min amount for tokenA when adding
* @param dmmAmountBMin min amount for tokenB when adding
* @param poolInfo info the the Kyber DMM Pool - (poolAddress, poolAmp)
* if poolAddress is 0x0 -> create new pool with amp factor of poolAmp
* otherwise add liquidity to poolAddress
* @param deadline only allow transaction to be executed before the deadline
*/
function migrateLpToDmmPool(
address uniPair,
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
uint256 dmmAmountAMin,
uint256 dmmAmountBMin,
PoolInfo calldata poolInfo,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 addedLiquidity
);
/**
* @dev Migrate tokens from a pair to a Kyber Dmm Pool with permit
* User doesn't have to make an approve allowance transaction, just need to sign the data
* Supporting both normal tokens and tokens with fee on transfer
* Support create new pool with received tokens from removing, or
* add tokens to a given pool address
* @param uniPair pair for token that user wants to migrate from
* it should be compatible with UniswapPair's interface
* @param tokenA first token of the pool
* @param tokenB second token of the pool
* @param liquidity amount of LP tokens to migrate
* @param amountAMin min amount for tokenA when removing
* @param amountBMin min amount for tokenB when removing
* @param dmmAmountAMin min amount for tokenA when adding
* @param dmmAmountBMin min amount for tokenB when adding
* @param poolInfo info the the Kyber DMM Pool - (poolAddress, poolAmp)
* if poolAddress is 0x0 -> create new pool with amp factor of poolAmp
* otherwise add liquidity to poolAddress
* @param deadline only allow transaction to be executed before the deadline
* @param permitData data of approve allowance
*/
function migrateLpToDmmPoolWithPermit(
address uniPair,
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
uint256 dmmAmountAMin,
uint256 dmmAmountBMin,
PoolInfo calldata poolInfo,
uint256 deadline,
PermitData calldata permitData
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 addedLiquidity
);
}
/**
* @dev Liquidity Migrator contract to help migrating liquidity
* from other sources to Kyber DMM Pool
*/
contract LiquidityMigrator2 is ILiquidityMigrator, Ownable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
address public immutable dmmRouter;
constructor(address _dmmRouter) public {
require(_dmmRouter != address(0), "Migrator: INVALID_ROUTER");
dmmRouter = _dmmRouter;
}
/**
* @dev Use only for some special tokens
*/
function manualApproveAllowance(
IERC20[] calldata tokens,
address[] calldata spenders,
uint256 allowance
) external onlyOwner {
for (uint256 i = 0; i < tokens.length; i++) {
for (uint256 j = 0; j < spenders.length; j++) {
tokens[i].safeApprove(spenders[j], allowance);
}
}
}
/**
* @dev Migrate tokens from a pair to a Kyber Dmm Pool
* Supporting both normal tokens and tokens with fee on transfer
* Support create new pool with received tokens from removing, or
* add tokens to a given pool address
* @param uniPair pair for token that user wants to migrate from
* it should be compatible with UniswapPair's interface
* @param tokenA first token of the pool
* @param tokenB second token of the pool
* @param liquidity amount of LP tokens to migrate
* @param amountAMin min amount for tokenA when removing/adding
* @param amountBMin min amount for tokenB when removing/adding
* @param poolInfo info the the Kyber DMM Pool - (poolAddress, poolAmp)
* if poolAddress is 0x0 -> create new pool with amp factor of poolAmp
* otherwise add liquidity to poolAddress
* @param deadline only allow transaction to be executed before the deadline
* @param permitData data of approve allowance
*/
function migrateLpToDmmPoolWithPermit(
address uniPair,
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
uint256 dmmAmountAMin,
uint256 dmmAmountBMin,
PoolInfo calldata poolInfo,
uint256 deadline,
PermitData calldata permitData
)
external
override
returns (
uint256 amountA,
uint256 amountB,
uint256 addedLiquidity
)
{
IERC20Permit(uniPair).permit(
msg.sender,
address(this),
permitData.approveMax ? uint256(-1) : liquidity,
deadline,
permitData.v,
permitData.r,
permitData.s
);
(amountA, amountB, addedLiquidity) = migrateLpToDmmPool(
uniPair,
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
dmmAmountAMin,
dmmAmountBMin,
poolInfo,
deadline
);
}
/**
* @dev Migrate tokens from a pair to a Kyber Dmm Pool with permit
* User doesn't have to make an approve allowance transaction, just need to sign the data
* Supporting both normal tokens and tokens with fee on transfer
* Support create new pool with received tokens from removing, or
* add tokens to a given pool address
* @param uniPair pair for token that user wants to migrate from
* it should be compatible with UniswapPair's interface
* @param tokenA first token of the pool
* @param tokenB second token of the pool
* @param liquidity amount of LP tokens to migrate
* @param amountAMin min amount for tokenA when removing/adding
* @param amountBMin min amount for tokenB when removing/adding
* @param poolInfo info the the Kyber DMM Pool - (poolAddress, poolAmp)
* if poolAddress is 0x0 -> create new pool with amp factor of poolAmp
* otherwise add liquidity to poolAddress
* @param deadline only allow transaction to be executed before the deadline
*/
function migrateLpToDmmPool(
address uniPair,
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
uint256 dmmAmountAMin,
uint256 dmmAmountBMin,
PoolInfo memory poolInfo,
uint256 deadline
)
public
override
returns (
uint256 dmmAmountA,
uint256 dmmAmountB,
uint256 dmmLiquidity
)
{
// support for both normal token and token with fee on transfer
{
uint256 balanceTokenA = IERC20(tokenA).balanceOf(address(this));
uint256 balanceTokenB = IERC20(tokenB).balanceOf(address(this));
_removeUniLiquidity(
uniPair,
tokenA,
tokenB,
liquidity,
amountAMin,
amountBMin,
deadline
);
dmmAmountA = IERC20(tokenA).balanceOf(address(this)).sub(balanceTokenA);
dmmAmountB = IERC20(tokenB).balanceOf(address(this)).sub(balanceTokenB);
require(dmmAmountA > 0 && dmmAmountB > 0, "Migrator: INVALID_AMOUNT");
emit RemoveLiquidity(tokenA, tokenB, uniPair, liquidity, dmmAmountA, dmmAmountB);
}
(dmmAmountA, dmmAmountB, dmmLiquidity) = _addLiquidityToDmmPool(
tokenA,
tokenB,
dmmAmountA,
dmmAmountB,
dmmAmountAMin,
dmmAmountBMin,
poolInfo,
deadline
);
emit Migrated(tokenA, tokenB, dmmAmountA, dmmAmountB, dmmLiquidity, poolInfo);
}
/** @dev Allow the Owner to withdraw any funds that have been 'wrongly'
* transferred to the migrator contract
*/
function withdrawFund(IERC20 token, uint256 amount) external onlyOwner {
if (token == IERC20(0)) {
(bool success, ) = owner().call{value: amount}("");
require(success, "Migrator: TRANSFER_ETH_FAILED");
} else {
token.safeTransfer(owner(), amount);
}
}
/**
* @dev Add liquidity to Kyber dmm pool, support adding to new pool or an existing pool
*/
function _addLiquidityToDmmPool(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
PoolInfo memory poolInfo,
uint256 deadline
)
internal
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
// safe approve only if needed
_safeApproveAllowance(IERC20(tokenA), address(dmmRouter));
_safeApproveAllowance(IERC20(tokenB), address(dmmRouter));
if (poolInfo.poolAddress == address(0)) {
// add to new pool
(amountA, amountB, liquidity) = _addLiquidityNewPool(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
poolInfo.poolAmp,
deadline
);
} else {
(amountA, amountB, liquidity) = _addLiquidityExistingPool(
tokenA,
tokenB,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
poolInfo.poolAddress,
poolInfo.dmmVReserveRatioBounds,
deadline
);
}
}
/**
* @dev Add liquidity to an existing pool, and return back tokens to users if any
*/
function _addLiquidityExistingPool(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address dmmPool,
uint256[2] memory vReserveRatioBounds,
uint256 deadline
)
internal
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
(amountA, amountB, liquidity) = IDMMLiquidityRouter(dmmRouter).addLiquidity(
IERC20(tokenA),
IERC20(tokenB),
dmmPool,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
vReserveRatioBounds,
msg.sender,
deadline
);
// return back token if needed
if (amountA < amountADesired) {
IERC20(tokenA).safeTransfer(msg.sender, amountADesired - amountA);
}
if (amountB < amountBDesired) {
IERC20(tokenB).safeTransfer(msg.sender, amountBDesired - amountB);
}
}
/**
* @dev Add liquidity to a new pool, and return back tokens to users if any
*/
function _addLiquidityNewPool(
address tokenA,
address tokenB,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
uint32 amps,
uint256 deadline
)
internal
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
)
{
(amountA, amountB, liquidity) = IDMMLiquidityRouter(dmmRouter).addLiquidityNewPool(
IERC20(tokenA),
IERC20(tokenB),
amps,
amountADesired,
amountBDesired,
amountAMin,
amountBMin,
msg.sender,
deadline
);
// return back token if needed
if (amountA < amountADesired) {
IERC20(tokenA).safeTransfer(msg.sender, amountADesired - amountA);
}
if (amountB < amountBDesired) {
IERC20(tokenB).safeTransfer(msg.sender, amountBDesired - amountB);
}
}
/**
* @dev Re-write remove liquidity function from Uniswap
*/
function _removeUniLiquidity(
address pair,
address tokenA,
address tokenB,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
uint256 deadline
) internal {
require(deadline >= block.timestamp, "Migratior: EXPIRED");
IERC20(pair).safeTransferFrom(msg.sender, pair, liquidity); // send liquidity to pair
(uint256 amount0, uint256 amount1) = IUniswapV2Pair(pair).burn(address(this));
(address token0, ) = _sortTokens(tokenA, tokenB);
(uint256 amountA, uint256 amountB) = tokenA == token0
? (amount0, amount1)
: (amount1, amount0);
require(amountA >= amountAMin, "Migratior: UNI_INSUFFICIENT_A_AMOUNT");
require(amountB >= amountBMin, "Migratior: UNI_INSUFFICIENT_B_AMOUNT");
}
/**
* @dev only approve if the current allowance is 0
*/
function _safeApproveAllowance(IERC20 token, address spender) internal {
if (token.allowance(address(this), spender) == 0) {
token.safeApprove(spender, uint256(-1));
}
}
/**
* @dev Copy logic of sort token from Uniswap lib
*/
function _sortTokens(address tokenA, address tokenB)
internal
pure
returns (address token0, address token1)
{
require(tokenA != tokenB, "Migrator: IDENTICAL_ADDRESSES");
(token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
require(token0 != address(0), "Migrator: ZERO_ADDRESS");
}
} | an simple interface for integration dApp to contribute liquidity | interface IDMMLiquidityRouter {
function addLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
uint256[2] calldata vReserveRatioBounds,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityNewPool(
IERC20 tokenA,
IERC20 tokenB,
uint32 ampBps,
uint256 amountADesired,
uint256 amountBDesired,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
)
external
returns (
uint256 amountA,
uint256 amountB,
uint256 liquidity
);
function addLiquidityNewPoolETH(
IERC20 token,
uint32 ampBps,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function addLiquidityETH(
IERC20 token,
address pool,
uint256 amountTokenDesired,
uint256 amountTokenMin,
uint256 amountETHMin,
uint256[2] calldata vReserveRatioBounds,
address to,
uint256 deadline
)
external
payable
returns (
uint256 amountToken,
uint256 amountETH,
uint256 liquidity
);
function removeLiquidity(
IERC20 tokenA,
IERC20 tokenB,
address pool,
uint256 liquidity,
uint256 amountAMin,
uint256 amountBMin,
address to,
uint256 deadline
) external returns (uint256 amountA, uint256 amountB);
function removeLiquidityWithPermit(
IERC20 tokenA,
IERC20 tokenB,
address pool,
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 removeLiquidityETH(
IERC20 token,
address pool,
uint256 liquidity,
uint256 amountTokenMin,
uint256 amountETHMin,
address to,
uint256 deadline
) external returns (uint256 amountToken, uint256 amountETH);
function removeLiquidityETHWithPermit(
IERC20 token,
address pool,
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 quote(
uint256 amountA,
uint256 reserveA,
uint256 reserveB
) external pure returns (uint256 amountB);
pragma solidity 0.6.12;
}
| 2,393,500 |
./partial_match/1/0xab79C816da5CFC71127da3aDe3e9604112348196/sources/contracts/UnlonelyArcadeContract.sol | Calculate required ETH amount Transfer Ether to the token owner Transfer CreatorToken to the buyer | function buyCreatorToken(address _creatorToken, uint256 tokenAmount) payable external {
require(creatorTokens[_creatorToken] != IERC20(address(0)), "Token does not exist.");
require(tokenOwners[_creatorToken] != address(0), "Token does not have an owner.");
require(tokenAmount > 0, "Token amount must be greater than zero.");
uint256 ethAmount = calculateEthAmount(_creatorToken, tokenAmount);
require(msg.value >= ethAmount, "Insufficient Ether sent.");
payable(tokenOwners[_creatorToken]).transfer(msg.value);
IERC20 token = creatorTokens[_creatorToken];
address tokenOwner = tokenOwners[_creatorToken];
token.safeTransferFrom(tokenOwner, msg.sender, tokenAmount);
}
| 4,169,038 |
//Address: 0xe0f3544280f784e82c7bacb1a7b50d4aaea55ad9
//Contract name: GameRewardToken
//Balance: 0 Ether
//Verification Date: 6/21/2018
//Transacion Count: 1
// CODE STARTS HERE
pragma solidity ^0.4.21;
contract owned {
address public owner;
constructor() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
owner = newOwner;
}
}
contract SafeMath {
function safeMul(uint a, uint b) internal pure returns (uint) {
uint c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function safeDiv(uint a, uint b) internal pure returns (uint) {
assert(b > 0);
uint c = a / b;
assert(a == b * c + a % b);
return c;
}
function safeSub(uint a, uint b) internal pure returns (uint) {
assert(b <= a);
return a - b;
}
function safeAdd(uint a, uint b) internal pure returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function max64(uint64 a, uint64 b) internal pure returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
function toWei(uint256 a) internal pure returns (uint256){
assert(a>0);
return a * 10 ** 18;
}
}
interface tokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) external;
}
contract TokenERC20 is SafeMath{
// Token information
// Public variables of the token
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
// This creates an array with all balances
mapping (address => uint256) public balanceOf;
mapping (address => mapping (address => uint256)) public allowance;
// This generates a public event on the blockchain that will notify clients
event Transfer(address indexed from, address indexed to, uint256 value);
// This notifies clients about the amount burnt
event Burn(address indexed from, uint256 value);
/**
* Constrctor function
*
* Initializes contract with initial supply tokens to the creator of the contract
*/
constructor(string _name, string _symbol, uint8 _decimals, uint256 _totalSupply) public {
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _totalSupply * 10 ** uint256(decimals);
}
/**
* Internal transfer, only can be called by this contract
*/
function _transfer(address _from, address _to, uint _value) internal {
// Prevent transfer to 0x0 address. Use burn() instead
require(_to != 0x0);
// Check if the sender has enough
require(balanceOf[_from] >= _value);
// Check for overflows
require(safeAdd(balanceOf[_to], _value) > balanceOf[_to]);
// Save this for an assertion in the future
uint previousBalances = safeAdd(balanceOf[_from],balanceOf[_to]);
// Subtract from the sender
balanceOf[_from] = safeSub(balanceOf[_from], _value);
// Add the same to the recipient
balanceOf[_to] = safeAdd(balanceOf[_to], _value);
emit Transfer(_from, _to, _value);
// Asserts are used to use static analysis to find bugs in your code. They should never fail
assert(safeAdd(balanceOf[_from],balanceOf[_to]) == previousBalances);
}
/**
* Transfer tokens
*
* Send `_value` tokens to `_to` from your account
*
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transfer(address _to, uint256 _value) public {
_transfer(msg.sender, _to, _value);
}
/**
* Transfer tokens from other address
*
* Send `_value` tokens to `_to` in behalf of `_from`
*
* @param _from The address of the sender
* @param _to The address of the recipient
* @param _value the amount to send
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]); // Check allowance
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender],_value);
_transfer(_from, _to, _value);
return true;
}
/**
* Set allowance for other address
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
*/
function approve(address _spender, uint256 _value) public
returns (bool success) {
allowance[msg.sender][_spender] = _value;
return true;
}
/**
* Set allowance for other address and notify
*
* Allows `_spender` to spend no more than `_value` tokens in your behalf, and then ping the contract about it
*
* @param _spender The address authorized to spend
* @param _value the max amount they can spend
* @param _extraData some extra information to send to the approved contract
*/
function approveAndCall(address _spender, uint256 _value, bytes _extraData)
public
returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
/**
* Destroy tokens
*
* Remove `_value` tokens from the system irreversibly
*
* @param _value the amount of money to burn
*/
function burn(uint256 _value) public returns (bool success) {
require(balanceOf[msg.sender] >= _value); // Check if the sender has enough
balanceOf[msg.sender] = safeSub(balanceOf[msg.sender], _value); // Subtract from the sender
totalSupply = safeSub(totalSupply,_value); // Updates totalSupply
emit Burn(msg.sender, _value);
return true;
}
/**
* Destroy tokens from other account
*
* Remove `_value` tokens from the system irreversibly on behalf of `_from`.
*
* @param _from the address of the sender
* @param _value the amount of money to burn
*/
function burnFrom(address _from, uint256 _value) public returns (bool success) {
require(balanceOf[_from] >= _value); // Check if the targeted balance is enough
require(_value <= allowance[_from][msg.sender]); // Check allowance
balanceOf[_from] = safeSub(balanceOf[_from], _value); // Subtract from the targeted balance
allowance[_from][msg.sender] = safeSub(allowance[_from][msg.sender], _value); // Subtract from the sender's allowance
totalSupply = safeSub(totalSupply,_value); // Update totalSupply
emit Burn(_from, _value);
return true;
}
}
/******************************************/
/* GAMEREWARD TOKEN */
/******************************************/
contract GameRewardToken is owned, TokenERC20 {
// State machine
enum State{PrivateFunding, PreFunding, Funding, Success, Failure}
mapping (address => bool) public frozenAccount;
mapping (address => uint256) public bounties;
mapping (address => uint256) public bonus;
mapping (address => address) public referrals;
mapping (address => uint256) public investors;
mapping (address => uint256) public funders;
/* This generates a public event on the blockchain that will notify clients */
event FrozenFunds(address indexed target, bool frozen);
event FundTransfer(address indexed to, uint256 eth , uint256 value, uint block);
event Fee(address indexed from, address indexed collector, uint256 fee);
event FreeDistribution(address indexed to, uint256 value, uint block);
event Refund(address indexed to, uint256 value, uint block);
event BonusTransfer(address indexed to, uint256 value, uint block);
event BountyTransfer(address indexed to, uint256 value, uint block);
event SetReferral(address indexed target, address indexed broker);
event ChangeCampaign(uint256 fundingStartBlock, uint256 fundingEndBlock);
event AddBounty(address indexed bountyHunter, uint256 value);
event ReferralBonus(address indexed investor, address indexed broker, uint256 value);
// Crowdsale information
bool public finalizedCrowdfunding = false;
uint256 public fundingStartBlock = 0; // crowdsale start block
uint256 public fundingEndBlock = 0; // crowdsale end block
uint256 public constant lockedTokens = 250000000*10**18; //25% tokens to Vault and locked for 6 months - 250 millions
uint256 public bonusAndBountyTokens = 50000000*10**18; //5% tokens for referral bonus and bounty - 50 millions
uint256 public constant devsTokens = 100000000*10**18; //10% tokens for team - 100 millions
uint256 public constant hundredPercent = 100;
uint256 public constant tokensPerEther = 20000; //GRD:ETH exchange rate - 20.000 GRD per ETH
uint256 public constant tokenCreationMax = 600000000*10**18; //ICO hard target - 600 millions
uint256 public constant tokenCreationMin = 60000000*10**18; //ICO soft target - 60 millions
uint256 public constant tokenPrivateMax = 100000000*10**18; //Private-sale must stop when 100 millions tokens sold
uint256 public constant minContributionAmount = 0.1*10**18; //Investor must buy atleast 0.1ETH in open-sale
uint256 public constant maxContributionAmount = 100*10**18; //Max 100 ETH in open-sale and pre-sale
uint256 public constant minPrivateContribution = 5*10**18; //Investor must buy atleast 5ETH in private-sale
uint256 public constant minPreContribution = 1*10**18; //Investor must buy atleast 1ETH in pre-sale
uint256 public constant minAmountToGetBonus = 1*10**18; //Investor must buy atleast 1ETH to receive referral bonus
uint256 public constant referralBonus = 5; //5% for referral bonus
uint256 public constant privateBonus = 40; //40% bonus in private-sale
uint256 public constant preBonus = 20; //20% bonus in pre-sale;
uint256 public tokensSold;
uint256 public collectedETH;
uint256 public constant numBlocksLocked = 1110857; //180 days locked vault tokens
bool public releasedBountyTokens = false; //bounty release status
uint256 public unlockedAtBlockNumber;
address public lockedTokenHolder;
address public releaseTokenHolder;
address public devsHolder;
address public multiSigWalletAddress;
constructor(address _lockedTokenHolder,
address _releaseTokenHolder,
address _devsAddress,
address _multiSigWalletAddress
) TokenERC20("GameReward", // Name
"GRD", // Symbol
18, // Decimals
1000000000 // Total Supply 1 Billion
) public {
require (_lockedTokenHolder != 0x0);
require (_releaseTokenHolder != 0x0);
require (_devsAddress != 0x0);
require (_multiSigWalletAddress != 0x0);
lockedTokenHolder = _lockedTokenHolder;
releaseTokenHolder = _releaseTokenHolder;
devsHolder = _devsAddress;
multiSigWalletAddress = _multiSigWalletAddress;
}
/* Internal transfer, only can be called by this contract */
function _transfer(address _from, address _to, uint _value) internal {
require (getState() == State.Success);
require (_to != 0x0); // Prevent transfer to 0x0 address. Use burn() instead
require (balanceOf[_from] >= _value); // Prevent transfer to 0x0 address. Use burn() instead
require (safeAdd(balanceOf[_to],_value) > balanceOf[_to]); // Check for overflows
require (!frozenAccount[_from]); // Check if sender is frozen
require (!frozenAccount[_to]); // Check if recipient is frozen
require (_from != lockedTokenHolder);
balanceOf[_from] = safeSub(balanceOf[_from],_value); // Subtract from the sender
balanceOf[_to] = safeAdd(balanceOf[_to],_value); // Add the same to the recipient
emit Transfer(_from, _to, _value);
}
///@notice change token's name and symbol
function updateNameAndSymbol(string _newname, string _newsymbol) onlyOwner public{
name = _newname;
symbol = _newsymbol;
}
/// @notice `freeze? Prevent | Allow` `target` from sending & receiving tokens
/// @param _target Address to be frozen
/// @param _freeze either to freeze it or not
function freezeAccount(address _target, bool _freeze) onlyOwner public {
frozenAccount[_target] = _freeze;
emit FrozenFunds(_target, _freeze);
}
function setMultiSigWallet(address newWallet) external {
require (msg.sender == multiSigWalletAddress);
multiSigWalletAddress = newWallet;
}
//Crowdsale Functions
/// @notice get early bonus for Investor
function _getEarlyBonus() internal view returns(uint){
if(getState()==State.PrivateFunding) return privateBonus;
else if(getState()==State.PreFunding) return preBonus;
else return 0;
}
/// @notice set start and end block for funding
/// @param _fundingStartBlock start funding
/// @param _fundingEndBlock end funding
function setCampaign(uint256 _fundingStartBlock, uint256 _fundingEndBlock) onlyOwner public{
if(block.number < _fundingStartBlock){
fundingStartBlock = _fundingStartBlock;
}
if(_fundingEndBlock > fundingStartBlock && _fundingEndBlock > block.number){
fundingEndBlock = _fundingEndBlock;
}
emit ChangeCampaign(_fundingStartBlock,_fundingEndBlock);
}
function releaseBountyTokens() onlyOwner public{
require(!releasedBountyTokens);
require(getState()==State.Success);
releasedBountyTokens = true;
}
/// @notice set Broker for Investor
/// @param _target address of Investor
/// @param _broker address of Broker
function setReferral(address _target, address _broker, uint256 _amount) onlyOwner public {
require (_target != 0x0);
require (_broker != 0x0);
referrals[_target] = _broker;
emit SetReferral(_target, _broker);
if(_amount>0x0){
uint256 brokerBonus = safeDiv(safeMul(_amount,referralBonus),hundredPercent);
bonus[_broker] = safeAdd(bonus[_broker],brokerBonus);
emit ReferralBonus(_target,_broker,brokerBonus);
}
}
/// @notice set token for bounty hunter to release when ICO success
function addBounty(address _hunter, uint256 _amount) onlyOwner public{
require(_hunter!=0x0);
require(toWei(_amount)<=safeSub(bonusAndBountyTokens,toWei(_amount)));
bounties[_hunter] = safeAdd(bounties[_hunter],toWei(_amount));
bonusAndBountyTokens = safeSub(bonusAndBountyTokens,toWei(_amount));
emit AddBounty(_hunter, toWei(_amount));
}
/// @notice Create tokens when funding is active. This fallback function require 90.000 gas or more
/// @dev Required state: Funding
/// @dev State transition: -> Funding Success (only if cap reached)
function() payable public{
// Abort if not in Funding Active state.
// Do not allow creating 0 or more than the cap tokens.
require (getState() != State.Success);
require (getState() != State.Failure);
require (msg.value != 0);
if(getState()==State.PrivateFunding){
require(msg.value>=minPrivateContribution);
}else if(getState()==State.PreFunding){
require(msg.value>=minPreContribution && msg.value < maxContributionAmount);
}else{
require(msg.value>=minContributionAmount && msg.value < maxContributionAmount);
}
// multiply by exchange rate to get newly created token amount
uint256 createdTokens = safeMul(msg.value, tokensPerEther);
uint256 brokerBonus = 0;
uint256 earlyBonus = safeDiv(safeMul(createdTokens,_getEarlyBonus()),hundredPercent);
createdTokens = safeAdd(createdTokens,earlyBonus);
// don't go over the limit!
if(getState()==State.PrivateFunding){
require(safeAdd(tokensSold,createdTokens) <= tokenPrivateMax);
}else{
require (safeAdd(tokensSold,createdTokens) <= tokenCreationMax);
}
// we are creating tokens, so increase the tokenSold
tokensSold = safeAdd(tokensSold, createdTokens);
collectedETH = safeAdd(collectedETH,msg.value);
// add bonus if has referral
if(referrals[msg.sender]!= 0x0){
brokerBonus = safeDiv(safeMul(createdTokens,referralBonus),hundredPercent);
bonus[referrals[msg.sender]] = safeAdd(bonus[referrals[msg.sender]],brokerBonus);
emit ReferralBonus(msg.sender,referrals[msg.sender],brokerBonus);
}
// Save funder info for refund and free distribution
funders[msg.sender] = safeAdd(funders[msg.sender],msg.value);
investors[msg.sender] = safeAdd(investors[msg.sender],createdTokens);
// Assign new tokens to the sender
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender], createdTokens);
// Log token creation event
emit FundTransfer(msg.sender,msg.value, createdTokens, block.number);
emit Transfer(0, msg.sender, createdTokens);
}
/// @notice send bonus token to broker
function requestBonus() external{
require(getState()==State.Success);
uint256 bonusAmount = bonus[msg.sender];
assert(bonusAmount>0);
require(bonusAmount<=safeSub(bonusAndBountyTokens,bonusAmount));
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender],bonusAmount);
bonus[msg.sender] = 0;
bonusAndBountyTokens = safeSub(bonusAndBountyTokens,bonusAmount);
emit BonusTransfer(msg.sender,bonusAmount,block.number);
emit Transfer(0,msg.sender,bonusAmount);
}
/// @notice send lockedTokens to devs address
/// require State == Success
/// require tokens unlocked
function releaseLockedToken() external {
require (getState() == State.Success);
require (balanceOf[lockedTokenHolder] > 0x0);
require (block.number >= unlockedAtBlockNumber);
balanceOf[devsHolder] = safeAdd(balanceOf[devsHolder],balanceOf[lockedTokenHolder]);
emit Transfer(lockedTokenHolder,devsHolder,balanceOf[lockedTokenHolder]);
balanceOf[lockedTokenHolder] = 0;
}
/// @notice request to receive bounty tokens
/// @dev require State == Succes
function requestBounty() external{
require(releasedBountyTokens); //locked bounty hunter's token for 7 days after end of campaign
require(getState()==State.Success);
assert (bounties[msg.sender]>0);
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender],bounties[msg.sender]);
emit BountyTransfer(msg.sender,bounties[msg.sender],block.number);
emit Transfer(0,msg.sender,bounties[msg.sender]);
bounties[msg.sender] = 0;
}
/// @notice Finalize crowdfunding
/// @dev If cap was reached or crowdfunding has ended then:
/// create GRD for the Vault and developer,
/// transfer ETH to the devs address.
/// @dev Required state: Success
function finalizeCrowdfunding() external {
// Abort if not in Funding Success state.
require (getState() == State.Success); // don't finalize unless we won
require (!finalizedCrowdfunding); // can't finalize twice (so sneaky!)
// prevent more creation of tokens
finalizedCrowdfunding = true;
// Endowment: 25% of total goes to vault, timelocked for 6 months
balanceOf[lockedTokenHolder] = safeAdd(balanceOf[lockedTokenHolder], lockedTokens);
// Transfer lockedTokens to lockedTokenHolder address
unlockedAtBlockNumber = block.number + numBlocksLocked;
emit Transfer(0, lockedTokenHolder, lockedTokens);
// Endowment: 10% of total goes to devs
balanceOf[devsHolder] = safeAdd(balanceOf[devsHolder], devsTokens);
emit Transfer(0, devsHolder, devsTokens);
// Transfer ETH to the multiSigWalletAddress address.
multiSigWalletAddress.transfer(address(this).balance);
}
/// @notice send @param _unSoldTokens to all Investor base on their share
function requestFreeDistribution() external{
require(getState()==State.Success);
assert(investors[msg.sender]>0);
uint256 unSoldTokens = safeSub(tokenCreationMax,tokensSold);
require(unSoldTokens>0);
uint256 freeTokens = safeDiv(safeMul(unSoldTokens,investors[msg.sender]),tokensSold);
balanceOf[msg.sender] = safeAdd(balanceOf[msg.sender],freeTokens);
investors[msg.sender] = 0;
emit FreeDistribution(msg.sender,freeTokens,block.number);
emit Transfer(0,msg.sender, freeTokens);
}
/// @notice Get back the ether sent during the funding in case the funding
/// has not reached the soft cap.
/// @dev Required state: Failure
function requestRefund() external {
// Abort if not in Funding Failure state.
assert (getState() == State.Failure);
assert (funders[msg.sender]>0);
msg.sender.transfer(funders[msg.sender]);
emit Refund( msg.sender, funders[msg.sender],block.number);
funders[msg.sender]=0;
}
/// @notice This manages the crowdfunding state machine
/// We make it a function and do not assign the result to a variable
/// So there is no chance of the variable being stale
function getState() public constant returns (State){
// once we reach success, lock in the state
if (finalizedCrowdfunding) return State.Success;
if(fundingStartBlock ==0 && fundingEndBlock==0) return State.PrivateFunding;
else if (block.number < fundingStartBlock) return State.PreFunding;
else if (block.number <= fundingEndBlock && tokensSold < tokenCreationMax) return State.Funding;
else if (tokensSold >= tokenCreationMin) return State.Success;
else return State.Failure;
}
}
| change token's name and symbol | function updateNameAndSymbol(string _newname, string _newsymbol) onlyOwner public{
name = _newname;
symbol = _newsymbol;
}
| 5,530,349 |
./full_match/3/0x7295C2BE0Fabca03ED3514C3dd99658EbC25f3f3/sources/browser/Contract_Code_v2_Min.sol | SignIn/check time | function SignIn()
external
isHuman()
_isOpen()
{
User storage user = userMapping[msg.sender];
initUserID(user);
checkUserID(user.id);
require(paramsMapping[7011] == 1, "SignIn Not Open");
if (user.sgnInDataIndex != 0) {
require(now / 1 days > (user.sgnInData[user.sgnInDataIndex - 1].time + 1 days) / 1 days, "today signed");
}
uint ETTMoney = randRange(paramsMapping[7001] / 10000000000000000, paramsMapping[7002] / 10000000000000000) * 10000000000000000;
user.sgnInDataIndex ++;
signInData.time = uint40(now);
signInData.amount = ETTMoney;
}
| 8,114,346 |
// SPDX-License-Identifier: UNLICENSED
pragma solidity =0.6.10;
import {OracleInterface} from "../interfaces/OracleInterface.sol";
import {OpynPricerInterface} from "../interfaces/OpynPricerInterface.sol";
import {WSTETHInterface} from "../interfaces/WSTETHInterface.sol";
import {SafeMath} from "../packages/oz/SafeMath.sol";
/**
* Error Codes
* W1: cannot deploy pricer, wstETH address cannot be 0
* W2: cannot deploy pricer, underlying address cannot be 0
* W3: cannot deploy pricer, oracle address cannot be 0
* W4: cannot retrieve price, underlying price is 0
* W5: cannot set expiry price in oracle, underlying price is 0 and has not been set
* W6: cannot retrieve historical prices, getHistoricalPrice has been deprecated
*/
/**
* @title WstethPricer
* @author Opyn Team
* @notice A Pricer contract for a wstETH token
*/
contract WstethPricer is OpynPricerInterface {
using SafeMath for uint256;
/// @notice opyn oracle address
OracleInterface public oracle;
/// @notice wstETH token
WSTETHInterface public wstETH;
/// @notice underlying asset (WETH)
address public underlying;
/**
* @param _wstETH wstETH
* @param _underlying underlying asset for wstETH
* @param _oracle Opyn Oracle contract address
*/
constructor(
address _wstETH,
address _underlying,
address _oracle
) public {
require(_wstETH != address(0), "W1");
require(_underlying != address(0), "W2");
require(_oracle != address(0), "W3");
wstETH = WSTETHInterface(_wstETH);
oracle = OracleInterface(_oracle);
underlying = _underlying;
}
/**
* @notice get the live price for the asset
* @dev overrides the getPrice function in OpynPricerInterface
* @return price of 1 wstETH in USD, scaled by 1e8
*/
function getPrice() external view override returns (uint256) {
uint256 underlyingPrice = oracle.getPrice(underlying);
require(underlyingPrice > 0, "W4");
return _underlyingPriceToWstethPrice(underlyingPrice);
}
/**
* @notice set the expiry price in the oracle
* @dev requires that the underlying price has been set before setting a wstETH price
* @param _expiryTimestamp expiry to set a price for
*/
function setExpiryPriceInOracle(uint256 _expiryTimestamp) external {
(uint256 underlyingPriceExpiry, ) = oracle.getExpiryPrice(underlying, _expiryTimestamp);
require(underlyingPriceExpiry > 0, "W5");
uint256 wstEthPrice = _underlyingPriceToWstethPrice(underlyingPriceExpiry);
oracle.setExpiryPrice(address(wstETH), _expiryTimestamp, wstEthPrice);
}
/**
* @dev convert underlying price to wstETH price with the wstETH to stETH exchange rate (1 stETH ≈ 1 ETH)
* @param _underlyingPrice price of 1 underlying token (ie 1e18 WETH) in USD, scaled by 1e8
* @return price of 1 wstETH in USD, scaled by 1e8
*/
function _underlyingPriceToWstethPrice(uint256 _underlyingPrice) private view returns (uint256) {
uint256 stEthPerWsteth = wstETH.stEthPerToken();
return stEthPerWsteth.mul(_underlyingPrice).div(1e18);
}
function getHistoricalPrice(uint80) external view override returns (uint256, uint256) {
revert("W6");
}
}
| set the expiry price in the oracle requires that the underlying price has been set before setting a wstETH price _expiryTimestamp expiry to set a price for/ | function setExpiryPriceInOracle(uint256 _expiryTimestamp) external {
(uint256 underlyingPriceExpiry, ) = oracle.getExpiryPrice(underlying, _expiryTimestamp);
require(underlyingPriceExpiry > 0, "W5");
uint256 wstEthPrice = _underlyingPriceToWstethPrice(underlyingPriceExpiry);
oracle.setExpiryPrice(address(wstETH), _expiryTimestamp, wstEthPrice);
}
| 15,788,960 |
./full_match/4/0x49d529eEfbd50864D4C9814E130EBd8C04e57ef3/sources/contracts/upgradeable_contracts/omnibridge_nft/modules/forwarding_rules/NFTForwardingRulesManager.sol | Allows a particular address to receive bridged tokens from the oracle-driven lane for a particular token. Only owner can call this method. _token address of the token contract on the foreign side. _receiver address of the tokens receiver on the foreign side of the bridge. _enable true, if bridge operations for a given token and receiver should be forwarded to the oracle-driven lane./ | function setRuleForTokenAndReceiverToPBO(
address _token,
address _receiver,
bool _enable
) external {
require(_token != ANY_ADDRESS);
require(_receiver != ANY_ADDRESS);
_setForwardingRule(_token, ANY_ADDRESS, _receiver, _enable ? int256(1) : int256(0));
}
| 773,154 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.10;
import {Ownable} from "../../lib/Ownable.sol";
import {IMirrorAllocatedEditionsLogic} from "./interface/IMirrorAllocatedEditionsLogic.sol";
import {IERC721, IERC721Events, IERC721Receiver, IERC721Metadata} from "../../lib/ERC721/interface/IERC721.sol";
import {IERC165} from "../../lib/ERC165/interface/IERC165.sol";
import {IERC2981} from "../../lib/ERC2981/interface/IERC2981.sol";
import {IMirrorOpenSaleV0} from "../../distributors/open-sale/interface/IMirrorOpenSaleV0.sol";
import {IERC2309} from "../../lib/ERC2309/interface/IERC2309.sol";
/**
* @title MirrorAllocatedEditionsLogic
* @author MirrorXYZ
*/
contract MirrorAllocatedEditionsLogic is
Ownable,
IMirrorAllocatedEditionsLogic,
IERC721,
IERC721Events,
IERC165,
IERC721Metadata,
IERC2309,
IERC2981
{
/// @notice Token name
string public override name;
/// @notice Token symbol
string public override symbol;
/// @notice Token baseURI
string public baseURI;
/// @notice Token contentHash
bytes32 public contentHash;
/// @notice Token supply
uint256 public totalSupply;
/// @notice Burned tokens
mapping(uint256 => bool) internal _burned;
/// @notice Token owners
mapping(uint256 => address) internal _owners;
/// @notice Token balances
mapping(address => uint256) internal _balances;
/// @notice Token approvals
mapping(uint256 => address) internal _tokenApprovals;
/// @notice Token operator approvals
mapping(address => mapping(address => bool)) internal _operatorApprovals;
/// @notice Mirror open sale address
address public immutable mirrorOpenSale;
// ============ Royalty Info (ERC2981) ============
/// @notice Account that will receive royalties
/// @dev set address(0) to avoid royalties
address public royaltyRecipient;
/// @notice Royalty percentage
uint256 public royaltyPercentage;
/// @dev Sets zero address as owner since this is a logic contract
/// @param mirrorOpenSale_ sale contract address
constructor(address mirrorOpenSale_) Ownable(address(0)) {
mirrorOpenSale = mirrorOpenSale_;
}
// ============ Constructor ============
/// @dev Initialize contract
/// @param metadata ERC721Metadata parameters
/// @param owner_ owner of this contract
/// @param fundingRecipient_ account that will receive funds from sales
/// @param royaltyRecipient_ account that will receive royalties
/// @param royaltyPercentage_ royalty percentage
/// @param price sale listing price
/// @param list whether to list on sale contract
/// @param open whether to list with a closed or open sale
/// @dev Initialize parameters, mint total suppply to owner. Reverts if called
/// after contract deployment. If list is true, the open sale contract gets approval
/// for all tokens.
function initialize(
NFTMetadata memory metadata,
address owner_,
address payable fundingRecipient_,
address payable royaltyRecipient_,
uint256 royaltyPercentage_,
uint256 price,
bool list,
bool open,
uint256 feePercentage
) external override {
// ensure that this function is only callable during contract construction.
assembly {
if extcodesize(address()) {
revert(0, 0)
}
}
// NFT Metadata
name = metadata.name;
symbol = metadata.symbol;
baseURI = metadata.baseURI;
contentHash = metadata.contentHash;
totalSupply = metadata.quantity;
// Set owner
_setOwner(address(0), owner_);
// Royalties
royaltyRecipient = royaltyRecipient_;
royaltyPercentage = royaltyPercentage_;
emit ConsecutiveTransfer(
// fromTokenId
0,
// toTokenId
metadata.quantity - 1,
// fromAddress
address(0),
// toAddress
owner_
);
_balances[owner_] = totalSupply;
if (list) {
IMirrorOpenSaleV0(mirrorOpenSale).register(
IMirrorOpenSaleV0.SaleConfig({
token: address(this),
startTokenId: 0,
endTokenId: totalSupply - 1,
operator: owner_,
recipient: fundingRecipient_,
price: price,
open: open,
feePercentage: feePercentage
})
);
_operatorApprovals[owner_][mirrorOpenSale] = true;
emit ApprovalForAll(
// owner
owner_,
// operator
mirrorOpenSale,
// approved
true
);
}
}
// ============ ERC721 Methods ============
function balanceOf(address owner_) public view override returns (uint256) {
require(
owner_ != address(0),
"ERC721: balance query for the zero address"
);
return _balances[owner_];
}
function ownerOf(uint256 tokenId) public view override returns (address) {
address _owner = _owners[tokenId];
// if there is not owner set, and the token is not burned, the operator owns it
if (_owner == address(0) && !_burned[tokenId]) {
return owner;
}
require(_owner != address(0), "ERC721: query for nonexistent token");
return _owner;
}
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(msg.sender, tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
require(
_isApprovedOrOwner(msg.sender, tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
function approve(address to, uint256 tokenId) public override {
address owner_ = ownerOf(tokenId);
require(to != owner_, "ERC721: approval to current owner");
require(
msg.sender == owner_ || isApprovedForAll(owner_, msg.sender),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
require(
_exists(tokenId),
"ERC721: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
function setApprovalForAll(address operator, bool approved)
public
override
{
require(operator != msg.sender, "ERC721: approve to caller");
_operatorApprovals[msg.sender][operator] = approved;
emit ApprovalForAll(
// owner
msg.sender,
// operator
operator,
// approved
approved
);
}
function isApprovedForAll(address owner_, address operator_)
public
view
override
returns (bool)
{
return _operatorApprovals[owner_][operator_];
}
// ============ ERC721 Metadata Methods ============
function tokenURI(uint256 tokenId)
public
view
override
returns (string memory)
{
return string(abi.encodePacked(baseURI, _toString(tokenId)));
}
function contractURI() public view returns (string memory) {
return string(abi.encodePacked(baseURI, "metadata"));
}
function getContentHash(uint256) public view returns (bytes32) {
return contentHash;
}
// ============ Burn Method ============
function burn(uint256 tokenId) public {
require(
_isApprovedOrOwner(msg.sender, tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_burn(tokenId);
}
// ============ ERC2981 Methods ============
/// @notice Get royalty info
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
override
returns (address receiver, uint256 royaltyAmount)
{
receiver = royaltyRecipient;
royaltyAmount = (_salePrice * royaltyPercentage) / 10_000;
}
function setRoyaltyInfo(
address payable royaltyRecipient_,
uint256 royaltyPercentage_
) external override onlyOwner {
royaltyRecipient = royaltyRecipient_;
royaltyPercentage = royaltyPercentage_;
emit RoyaltyChange(
// oldRoyaltyRecipient
royaltyRecipient,
// oldRoyaltyPercentage
royaltyPercentage,
// newRoyaltyRecipient
royaltyRecipient_,
// newRoyaltyPercentage
royaltyPercentage_
);
}
// ============ IERC165 Method ============
function supportsInterface(bytes4 interfaceId)
public
pure
override
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC165).interfaceId ||
interfaceId == type(IERC2981).interfaceId;
}
// ============ Internal Methods ============
function _transfer(
address from,
address to,
uint256 tokenId
) internal {
require(
ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
);
require(
to != address(0),
"ERC721: transfer to the zero address (use burn instead)"
);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_balances[from] -= 1;
_owners[tokenId] = to;
_balances[to] += 1;
emit Transfer(
// from
from,
// to
to,
// tokenId
tokenId
);
}
function _exists(uint256 tokenId) internal view returns (bool) {
return !_burned[tokenId];
}
function _burn(uint256 tokenId) internal {
address owner_ = ownerOf(tokenId);
// Clear approvals
_approve(address(0), tokenId);
_balances[owner_] -= 1;
delete _owners[tokenId];
_burned[tokenId] = true;
emit Transfer(
// from
owner_,
// to
address(0),
// tokenId
tokenId
);
}
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
returns (bool)
{
require(_exists(tokenId), "ERC721: query for nonexistent token");
address owner_ = ownerOf(tokenId);
return (spender == owner_ ||
getApproved(tokenId) == spender ||
isApprovedForAll(owner_, spender));
}
function _approve(address to, uint256 tokenId) internal {
_tokenApprovals[tokenId] = to;
emit Approval(
// owner
ownerOf(tokenId),
// approved
to,
// tokenId
tokenId
);
}
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (_isContract(to)) {
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(
"ERC721: transfer to non ERC721Receiver implementer"
);
} else {
// solhint-disable-next-line no-inline-assembly
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
// https://github.com/OpenZeppelin/openzeppelin-contracts/blob/7f6a1666fac8ecff5dd467d0938069bc221ea9e0/contracts/utils/Address.sol
function _isContract(address account) internal view returns (bool) {
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol
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);
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.10;
interface IOwnableEvents {
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
}
contract Ownable is IOwnableEvents {
address public owner;
address private nextOwner;
// modifiers
modifier onlyOwner() {
require(isOwner(), "caller is not the owner.");
_;
}
modifier onlyNextOwner() {
require(isNextOwner(), "current owner must set caller as next owner.");
_;
}
/**
* @dev Initialize contract by setting transaction submitter as initial owner.
*/
constructor(address owner_) {
owner = owner_;
emit OwnershipTransferred(address(0), owner);
}
/**
* @dev Initiate ownership transfer by setting nextOwner.
*/
function transferOwnership(address nextOwner_) external onlyOwner {
require(nextOwner_ != address(0), "Next owner is the zero address.");
nextOwner = nextOwner_;
}
/**
* @dev Cancel ownership transfer by deleting nextOwner.
*/
function cancelOwnershipTransfer() external onlyOwner {
delete nextOwner;
}
/**
* @dev Accepts ownership transfer by setting owner.
*/
function acceptOwnership() external onlyNextOwner {
delete nextOwner;
owner = msg.sender;
emit OwnershipTransferred(owner, msg.sender);
}
/**
* @dev Renounce ownership by setting owner to zero address.
*/
function renounceOwnership() external onlyOwner {
_renounceOwnership();
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return msg.sender == owner;
}
/**
* @dev Returns true if the caller is the next owner.
*/
function isNextOwner() public view returns (bool) {
return msg.sender == nextOwner;
}
function _setOwner(address previousOwner, address newOwner) internal {
owner = newOwner;
emit OwnershipTransferred(previousOwner, owner);
}
function _renounceOwnership() internal {
owner = address(0);
emit OwnershipTransferred(owner, address(0));
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.10;
interface IMirrorAllocatedEditionsLogic {
event RoyaltyChange(
address indexed oldRoyaltyRecipient,
uint256 oldRoyaltyPercentage,
address indexed newRoyaltyRecipient,
uint256 newRoyaltyPercentage
);
struct NFTMetadata {
string name;
string symbol;
string baseURI;
bytes32 contentHash;
uint256 quantity;
}
function initialize(
NFTMetadata memory metadata,
address operator_,
address payable fundingRecipient_,
address payable royaltyRecipient_,
uint256 royaltyPercentage_,
uint256 price,
bool list,
bool open,
uint256 feePercentage
) external;
function setRoyaltyInfo(
address payable royaltyRecipient_,
uint256 royaltyPercentage_
) external;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.10;
interface IERC721 {
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;
}
interface IERC721Events {
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
);
}
interface IERC721Metadata {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function tokenURI(uint256 tokenId) external view returns (string memory);
}
interface IERC721Burnable is IERC721 {
function burn(uint256 tokenId) external;
}
interface IERC721Receiver {
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
interface IERC721Royalties {
function getFeeRecipients(uint256 id)
external
view
returns (address payable[] memory);
function getFeeBps(uint256 id) external view returns (uint256[] memory);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.10;
interface IERC165 {
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
abstract contract ERC165 is IERC165 {
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return interfaceId == type(IERC165).interfaceId;
}
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.10;
/**
* @title IERC2981
* @notice Interface for the NFT Royalty Standard
*/
interface IERC2981 {
// / bytes4(keccak256("royaltyInfo(uint256,uint256)")) == 0x2a55205a
/**
* @notice Called with the sale price to determine how much royalty
* is owed and to whom.
* @param _tokenId - the NFT asset queried for royalty information
* @param _salePrice - the sale price of the NFT asset specified by _tokenId
* @return receiver - address of who should be sent the royalty payment
* @return royaltyAmount - the royalty payment amount for _salePrice
*/
function royaltyInfo(uint256 _tokenId, uint256 _salePrice)
external
view
returns (address receiver, uint256 royaltyAmount);
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.10;
interface IMirrorOpenSaleV0Events {
event RegisteredSale(
bytes32 h,
address indexed token,
uint256 startTokenId,
uint256 endTokenId,
address indexed operator,
address indexed recipient,
uint256 price,
bool open,
uint256 feePercentage
);
event Purchase(
bytes32 h,
address indexed token,
uint256 tokenId,
address indexed buyer,
address indexed recipient
);
event Withdraw(
bytes32 h,
uint256 amount,
uint256 fee,
address indexed recipient
);
event OpenSale(bytes32 h);
event CloseSale(bytes32 h);
}
interface IMirrorOpenSaleV0 {
struct Sale {
bool registered;
bool open;
uint256 sold;
address operator;
}
struct SaleConfig {
address token;
uint256 startTokenId;
uint256 endTokenId;
address operator;
address recipient;
uint256 price;
bool open;
uint256 feePercentage;
}
function treasuryConfig() external returns (address);
function feeRegistry() external returns (address);
function tributaryRegistry() external returns (address);
function sale(bytes32 h) external view returns (Sale memory);
function register(SaleConfig calldata saleConfig_) external;
function close(SaleConfig calldata saleConfig_) external;
function open(SaleConfig calldata saleConfig_) external;
function purchase(SaleConfig calldata saleConfig_, address recipient)
external
payable;
}
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.10;
interface IERC2309 {
event ConsecutiveTransfer(
uint256 indexed fromTokenId,
uint256 toTokenId,
address indexed fromAddress,
address indexed toAddress
);
} | Clear approvals from to tokenId | function _burn(uint256 tokenId) internal {
address owner_ = ownerOf(tokenId);
_approve(address(0), tokenId);
_balances[owner_] -= 1;
delete _owners[tokenId];
_burned[tokenId] = true;
emit Transfer(
owner_,
address(0),
tokenId
);
}
| 1,308,350 |
pragma solidity 0.5.17;
import "./CErc20Immutable.sol";
import "./CEther.sol";
import "./ErrorReporter.sol";
import "./EIP20Interface.sol";
import "./Strings.sol";
import "./TriggerInterface.sol";
/**
* @notice Interface so ProtectionMarketFactory can use the same admin as the Comptroller
*/
interface ComptrollerAdmin {
function admin() external view returns (address);
}
/**
* @notice Factory contract for deploying protection markets
* @dev The functionality of cEtherFactory and cErc20Factory lives in separate contracts, instead of directly in
* this contract, since including them here would put this contract over the size limit
*/
contract ProtectionMarketFactory is ProtectionMarketFactoryErrorReporter {
/// @notice Address of the comptroller
ComptrollerInterface public comptroller;
/// @notice Address of the CEtherFactory contract
CEtherFactory public cEtherFactory;
/// @notice Address of the CErc20Factory contract
CErc20Factory public cErc20Factory;
/// @notice Mapping of underlying to last-used index for protection token naming
mapping(address => uint256) public tokenIndices;
/// @notice Default InterestRateModel assigned to protection markets at deployment
InterestRateModel public defaultInterestRateModel;
/// @notice Special address used to represent ETH
address internal constant ethUnderlyingAddress = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
/// @notice Number of decimals used for protection market cToken when deployed
uint8 internal constant decimals = 8;
/// @notice Prefix to prepend to protection token symbols
string internal constant tokenSymbolPrefix = "Cozy";
/// @notice Separator used in protection token symbols
string internal constant tokenSymbolSeparator = "-";
/// @notice Indicator that this is ProtectionMarketFactory contract (for inspection)
bool public constant isProtectionMarketFactory = true;
/// @notice Emitted when protection market default interest rate model is changed by admin
event NewDefaultInterestRateModel(InterestRateModel oldModel, InterestRateModel newModel);
/**
* @param cEtherFactory_ Address of the CEtherFactory contract
* @param cErc20Factory_ Address of the CErc20Factory contract
* @param comptroller_ Address of the system's comptroller
* @param defaultInterestRateModel_ Address of the default interest rate model to use for new markets
*/
constructor(
CEtherFactory cEtherFactory_,
CErc20Factory cErc20Factory_,
ComptrollerInterface comptroller_,
InterestRateModel defaultInterestRateModel_
) public {
cEtherFactory = cEtherFactory_;
cErc20Factory = cErc20Factory_;
comptroller = comptroller_;
require(_setDefaultInterestRateModel(defaultInterestRateModel_) == 0, "Set interest rate model failed");
}
/**
* @notice Deploy a new protection market
* @dev We could use the Comptroller address in storage instead of requiring it as an input, but passing it as an
* input makes this contract more flexible, and also saves some gas since address(this) is much cheaper than SLOAD
* @param _underlying The address of the underlying asset
* @param _comptroller Address of the system's comptroller
* @param _admin Address of the administrator of this token
* @param _trigger Address of the trigger contract
* @param interestRateModel_ Address of the interest rate model to use, or zero address to use the default
*/
function deployProtectionMarket(
address _underlying,
ComptrollerInterface _comptroller,
address payable _admin,
TriggerInterface _trigger,
address interestRateModel_
) external returns (address) {
require(msg.sender == address(_comptroller), "Caller not authorized");
// Get initial token symbol, token name, and initial exchange rate
(string memory symbol, string memory name) = createTokenSymbolAndName(_trigger, _underlying);
uint256 initialExchangeRateMantissa;
{
// Scope to avoid stack too deep errors
uint256 underlyingDecimals = _underlying == ethUnderlyingAddress ? 18 : EIP20Interface(_underlying).decimals();
uint256 scale = 18 + underlyingDecimals - decimals;
initialExchangeRateMantissa = 2 * 10**(scale - 2); // (scale - 2) so initial exchange rate is equivalent to 0.02
}
// Deploy market
if (_underlying == ethUnderlyingAddress) {
return
cEtherFactory.deployCEther(
_comptroller,
getInterestRateModel(interestRateModel_), // inline helper method to avoid stack too deep errors
initialExchangeRateMantissa,
name,
symbol,
decimals,
_admin,
address(_trigger)
);
} else {
return
cErc20Factory.deployCErc20(
_underlying,
_comptroller,
getInterestRateModel(interestRateModel_), // inline helper method to avoid stack too deep errors
initialExchangeRateMantissa,
name,
symbol,
decimals,
_admin,
address(_trigger)
);
}
}
/**
* @notice Returns the default interest rate model if none was provided
* @param _interestRateModel Provided interest rate model
*/
function getInterestRateModel(address _interestRateModel) internal returns (InterestRateModel) {
return _interestRateModel == address(0) ? defaultInterestRateModel : InterestRateModel(_interestRateModel);
}
/**
* @notice Derive a cToken name and symbol based on the trigger, underlying, and previously deployed markets
* @dev Used internally in the factory method for creating protection markets
* @param _trigger The address of the trigger that will be associated with this market
* @param _underlying The address of the underlying asset used for this cToken
* @return (symbol, name) The symbol and name for the new cToken, respectively
*/
function createTokenSymbolAndName(TriggerInterface _trigger, address _underlying)
internal
returns (string memory symbol, string memory name)
{
// Generate string for index postfix
uint256 nextIndex = tokenIndices[_underlying] + 1;
string memory indexString = Strings.toString(nextIndex);
// Remember that this token index has been used
tokenIndices[_underlying] = nextIndex;
// Get symbol for underlying asset
string memory underlyingSymbol;
if (_underlying == ethUnderlyingAddress) {
underlyingSymbol = "ETH";
} else {
EIP20Interface underlyingToken = EIP20Interface(_underlying);
underlyingSymbol = underlyingToken.symbol();
}
// Generate token symbol, example "Cozy-DAI-1"
string memory tokenSymbol =
string(
abi.encodePacked(tokenSymbolPrefix, tokenSymbolSeparator, underlyingSymbol, tokenSymbolSeparator, indexString)
);
// Generate token name, example "Cozy-DAI-1-Some Protocol Failure"
string memory tokenName = string(abi.encodePacked(tokenSymbol, tokenSymbolSeparator, _trigger.name()));
return (tokenSymbol, tokenName);
}
/**
* @notice Sets defaultInterestRateModel
* @dev Admin function to set defaultInterestRateModel, must be called by Comptroller admin
* @param _newModel New defaultInterestRateModel
* @return uint 0=success, otherwise a failure. (See ErrorReporter for details)
*/
function _setDefaultInterestRateModel(InterestRateModel _newModel) public returns (uint256) {
// Check caller is the Comptroller admin
if (msg.sender != ComptrollerAdmin(address(comptroller)).admin()) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_DEFAULT_INTEREST_RATE_MODEL_OWNER_CHECK);
}
// Sanity check the new contract
if (!_newModel.isInterestRateModel()) {
return fail(Error.INTEREST_RATE_MODEL_ERROR, FailureInfo.SET_DEFAULT_INTEREST_RATE_MODEL_VALIDITY_CHECK);
}
// Emit event with old model, new model
emit NewDefaultInterestRateModel(defaultInterestRateModel, _newModel);
// Set default model to the new model
defaultInterestRateModel = _newModel;
return uint256(Error.NO_ERROR);
}
}
/**
* @notice Simple contract with one method to deploy a new CEther contract with the specified parameters
*/
contract CEtherFactory {
/**
* @notice Deploy a new CEther money market or protection market
* @param comptroller The address of the Comptroller
* @param interestRateModel The address of the interest rate model
* @param initialExchangeRateMantissa The initial exchange rate, scaled by 1e18
* @param name ERC-20 name of this token
* @param symbol ERC-20 symbol of this token
* @param decimals ERC-20 decimal precision of this token
* @param admin Address of the administrator of this token
* @param trigger Trigger contract address for protection markets, or the zero address for money markets
*/
function deployCEther(
ComptrollerInterface comptroller,
InterestRateModel interestRateModel,
uint256 initialExchangeRateMantissa,
string calldata name,
string calldata symbol,
uint8 decimals,
address payable admin,
address trigger
) external returns (address) {
CEther cToken =
new CEther(comptroller, interestRateModel, initialExchangeRateMantissa, name, symbol, decimals, admin, trigger);
return address(cToken);
}
}
/**
* @notice Simple contract with one method to deploy a new CErc20 contract with the specified parameters
*/
contract CErc20Factory {
/**
* @notice Construct a new CErc20 money market or protection market
* @param underlying The address of the underlying asset
* @param comptroller The address of the Comptroller
* @param interestRateModel The address of the interest rate model
* @param initialExchangeRateMantissa The initial exchange rate, scaled by 1e18
* @param name ERC-20 name of this token
* @param symbol ERC-20 symbol of this token
* @param decimals ERC-20 decimal precision of this token
* @param admin Address of the administrator of this token
* @param trigger Trigger contract address for protection markets, or the zero address for money markets
*/
function deployCErc20(
address underlying,
ComptrollerInterface comptroller,
InterestRateModel interestRateModel,
uint256 initialExchangeRateMantissa,
string calldata name,
string calldata symbol,
uint8 decimals,
address payable admin,
address trigger
) external returns (address) {
CErc20Immutable cToken =
new CErc20Immutable(
underlying,
comptroller,
interestRateModel,
initialExchangeRateMantissa,
name,
symbol,
decimals,
admin,
trigger
);
return address(cToken);
}
}
pragma solidity 0.5.17;
import "./CErc20.sol";
/**
* @notice CTokens which wrap an EIP-20 underlying and are immutable
*/
contract CErc20Immutable is CErc20 {
/**
* @notice Construct a new money market or protection market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
* @param trigger_ Trigger contract address for protection markets, or the zero address for money markets
*/
constructor(
address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint256 initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_,
address trigger_
) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
// Initialize the market
initialize(
underlying_,
comptroller_,
interestRateModel_,
initialExchangeRateMantissa_,
name_,
symbol_,
decimals_,
trigger_
);
// Set the proper admin now that initialization is done
admin = admin_;
}
}
pragma solidity 0.5.17;
import "./CToken.sol";
/**
* @notice CToken which wraps Ether
*/
contract CEther is CToken {
/**
* @notice Construct a new CEther money market or protection market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param admin_ Address of the administrator of this token
* @param trigger_ Trigger contract address for protection markets, or the zero address for money markets
*/
constructor(
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint256 initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address payable admin_,
address trigger_
) public {
// Creator of the contract is admin during initialization
admin = msg.sender;
initialize(comptroller_, interestRateModel_, initialExchangeRateMantissa_, name_, symbol_, decimals_, trigger_);
// Set the proper admin now that initialization is done
admin = admin_;
// Set the underlying to the special address used to indicate ETH
underlying = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE;
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Reverts upon any failure
*/
function mint() external payable {
(uint256 err, ) = mintInternal(msg.value);
requireNoError(err, "mint failed");
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint256 redeemTokens) external returns (uint256) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint256 redeemAmount) external returns (uint256) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint256 borrowAmount) external returns (uint256) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @dev Reverts upon any failure
*/
function repayBorrow() external payable {
(uint256 err, ) = repayBorrowInternal(msg.value);
requireNoError(err, "repayBorrow failed");
}
/**
* @notice Sender repays a borrow belonging to borrower
* @dev Reverts upon any failure
* @param borrower the account with the debt being payed off
*/
function repayBorrowBehalf(address borrower) external payable {
(uint256 err, ) = repayBorrowBehalfInternal(borrower, msg.value);
requireNoError(err, "repayBorrowBehalf failed");
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @dev Reverts upon any failure
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
*/
function liquidateBorrow(address borrower, CToken cTokenCollateral) external payable {
(uint256 err, ) = liquidateBorrowInternal(borrower, msg.value, cTokenCollateral);
requireNoError(err, "liquidateBorrow failed");
}
/**
* @notice Send Ether to CEther to mint
*/
function() external payable {
(uint256 err, ) = mintInternal(msg.value);
requireNoError(err, "mint failed");
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of Ether, before this message
* @dev This excludes the value of the current message, if any
* @return The quantity of Ether owned by this contract
*/
function getCashPrior() internal view returns (uint256) {
(MathError err, uint256 startingBalance) = subUInt(address(this).balance, msg.value);
require(err == MathError.NO_ERROR);
return startingBalance;
}
/**
* @notice Perform the actual transfer in, which is a no-op
* @param from Address sending the Ether
* @param amount Amount of Ether being sent
* @return The actual amount of Ether transferred
*/
function doTransferIn(address from, uint256 amount) internal returns (uint256) {
// Sanity checks
require(msg.sender == from, "sender mismatch");
require(msg.value == amount, "value mismatch");
return amount;
}
function doTransferOut(address payable to, uint256 amount) internal {
/* Send the Ether, with minimal gas and revert on failure */
to.transfer(amount);
}
function requireNoError(uint256 errCode, string memory message) internal pure {
if (errCode == uint256(Error.NO_ERROR)) {
return;
}
bytes memory fullMessage = new bytes(bytes(message).length + 5);
uint256 i;
for (i = 0; i < bytes(message).length; i++) {
fullMessage[i] = bytes(message)[i];
}
fullMessage[i + 0] = bytes1(uint8(32));
fullMessage[i + 1] = bytes1(uint8(40));
fullMessage[i + 2] = bytes1(uint8(48 + (errCode / 10)));
fullMessage[i + 3] = bytes1(uint8(48 + (errCode % 10)));
fullMessage[i + 4] = bytes1(uint8(41));
require(errCode == uint256(Error.NO_ERROR), string(fullMessage));
}
}
pragma solidity 0.5.17;
contract ComptrollerErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
COMPTROLLER_MISMATCH,
INSUFFICIENT_SHORTFALL,
INSUFFICIENT_LIQUIDITY,
INVALID_CLOSE_FACTOR,
INVALID_COLLATERAL_FACTOR,
INVALID_LIQUIDATION_INCENTIVE,
MARKET_NOT_ENTERED, // no longer possible
MARKET_NOT_LISTED,
MARKET_ALREADY_LISTED,
MATH_ERROR,
NONZERO_BORROW_BALANCE,
PRICE_ERROR,
REJECTION,
SNAPSHOT_ERROR,
TOO_MANY_ASSETS,
TOO_MUCH_REPAY,
INVALID_TRIGGER,
PROTECTION_MARKET_FACTORY_ERROR
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCEPT_PENDING_IMPLEMENTATION_ADDRESS_CHECK,
EXIT_MARKET_BALANCE_OWED,
EXIT_MARKET_REJECTION,
SET_CLOSE_FACTOR_OWNER_CHECK,
SET_CLOSE_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_NO_EXISTS,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COLLATERAL_FACTOR_WITHOUT_PRICE,
SET_IMPLEMENTATION_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_OWNER_CHECK,
SET_LIQUIDATION_INCENTIVE_VALIDATION,
SET_MAX_ASSETS_OWNER_CHECK,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_PENDING_IMPLEMENTATION_OWNER_CHECK,
SET_PRICE_ORACLE_OWNER_CHECK,
SUPPORT_MARKET_EXISTS,
SUPPORT_MARKET_OWNER_CHECK,
SET_PAUSE_GUARDIAN_OWNER_CHECK,
SET_TRIGGER_CHECK,
SET_PROTECTION_WITH_INVALID_UNDERLYING,
SET_PROTECTION_UNDERLYING_WITHOUT_PRICE,
SET_PROTECTION_MARKET_FACTORY_OWNER_CHECK,
SET_PROTECTION_MARKET_FACTORY_VALIDITY_CHECK,
SET_RESERVE_GUARDIAN_OWNER_CHECK
}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint256 error, uint256 info, uint256 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 (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return uint256(err);
}
}
contract TokenErrorReporter {
enum Error {
NO_ERROR,
UNAUTHORIZED,
BAD_INPUT,
COMPTROLLER_REJECTION,
COMPTROLLER_CALCULATION_ERROR,
INTEREST_RATE_MODEL_ERROR,
INVALID_ACCOUNT_PAIR,
INVALID_CLOSE_AMOUNT_REQUESTED,
INVALID_COLLATERAL_FACTOR,
MATH_ERROR,
MARKET_NOT_FRESH,
MARKET_NOT_LISTED,
TOKEN_INSUFFICIENT_ALLOWANCE,
TOKEN_INSUFFICIENT_BALANCE,
TOKEN_INSUFFICIENT_CASH,
TOKEN_TRANSFER_IN_FAILED,
TOKEN_TRANSFER_OUT_FAILED,
INVALID_GUARDIAN,
MARKET_TRIGGERED
}
enum FailureInfo {
ACCEPT_ADMIN_PENDING_ADMIN_CHECK,
ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
ACCRUE_INTEREST_BORROW_RATE_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_BORROW_INDEX_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
ACCRUE_INTEREST_NEW_TOTAL_RESERVES_CALCULATION_FAILED,
ACCRUE_INTEREST_SIMPLE_INTEREST_FACTOR_CALCULATION_FAILED,
BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
BORROW_ACCRUE_INTEREST_FAILED,
BORROW_CASH_NOT_AVAILABLE,
BORROW_FRESHNESS_CHECK,
BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
BORROW_MARKET_NOT_LISTED,
BORROW_COMPTROLLER_REJECTION,
LIQUIDATE_ACCRUE_BORROW_INTEREST_FAILED,
LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED,
LIQUIDATE_COLLATERAL_FRESHNESS_CHECK,
LIQUIDATE_COMPTROLLER_REJECTION,
LIQUIDATE_COMPTROLLER_CALCULATE_AMOUNT_SEIZE_FAILED,
LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX,
LIQUIDATE_CLOSE_AMOUNT_IS_ZERO,
LIQUIDATE_FRESHNESS_CHECK,
LIQUIDATE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_REPAY_BORROW_FRESH_FAILED,
LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED,
LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED,
LIQUIDATE_SEIZE_COMPTROLLER_REJECTION,
LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER,
LIQUIDATE_SEIZE_TOO_MUCH,
MINT_ACCRUE_INTEREST_FAILED,
MINT_COMPTROLLER_REJECTION,
MINT_EXCHANGE_CALCULATION_FAILED,
MINT_EXCHANGE_RATE_READ_FAILED,
MINT_FRESHNESS_CHECK,
MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
MINT_TRANSFER_IN_FAILED,
MINT_TRANSFER_IN_NOT_POSSIBLE,
REDEEM_ACCRUE_INTEREST_FAILED,
REDEEM_COMPTROLLER_REJECTION,
REDEEM_EXCHANGE_TOKENS_CALCULATION_FAILED,
REDEEM_EXCHANGE_AMOUNT_CALCULATION_FAILED,
REDEEM_EXCHANGE_RATE_READ_FAILED,
REDEEM_FRESHNESS_CHECK,
REDEEM_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED,
REDEEM_NEW_TOTAL_SUPPLY_CALCULATION_FAILED,
REDEEM_TRANSFER_OUT_NOT_POSSIBLE,
REDUCE_RESERVES_ACCRUE_INTEREST_FAILED,
REDUCE_RESERVES_ADMIN_CHECK,
REDUCE_RESERVES_CASH_NOT_AVAILABLE,
REDUCE_RESERVES_FRESH_CHECK,
REDUCE_RESERVES_VALIDATION,
REPAY_BEHALF_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCRUE_INTEREST_FAILED,
REPAY_BORROW_ACCUMULATED_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_COMPTROLLER_REJECTION,
REPAY_BORROW_FRESHNESS_CHECK,
REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED,
REPAY_BORROW_TRANSFER_IN_NOT_POSSIBLE,
SET_COLLATERAL_FACTOR_OWNER_CHECK,
SET_COLLATERAL_FACTOR_VALIDATION,
SET_COMPTROLLER_OWNER_CHECK,
SET_INTEREST_RATE_MODEL_ACCRUE_INTEREST_FAILED,
SET_INTEREST_RATE_MODEL_FRESH_CHECK,
SET_INTEREST_RATE_MODEL_OWNER_CHECK,
SET_MAX_ASSETS_OWNER_CHECK,
SET_ORACLE_MARKET_NOT_LISTED,
SET_PENDING_ADMIN_OWNER_CHECK,
SET_RESERVE_FACTOR_ACCRUE_INTEREST_FAILED,
SET_RESERVE_FACTOR_ADMIN_CHECK,
SET_RESERVE_FACTOR_FRESH_CHECK,
SET_RESERVE_FACTOR_BOUNDS_CHECK,
TRANSFER_COMPTROLLER_REJECTION,
TRANSFER_NOT_ALLOWED,
TRANSFER_NOT_ENOUGH,
TRANSFER_TOO_MUCH,
ADD_RESERVES_ACCRUE_INTEREST_FAILED,
ADD_RESERVES_FRESH_CHECK,
ADD_RESERVES_TRANSFER_IN_NOT_POSSIBLE,
REDUCE_RESERVES_GUARDIAN_NOT_SET,
TRIGGER_ACTIVATED_BEFORE_REDEEM_OR_BORROW
}
/**
* @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(uint256 error, uint256 info, uint256 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 (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return uint256(err);
}
}
contract ProtectionMarketFactoryErrorReporter {
enum Error {NO_ERROR, UNAUTHORIZED, INTEREST_RATE_MODEL_ERROR}
enum FailureInfo {SET_DEFAULT_INTEREST_RATE_MODEL_OWNER_CHECK, SET_DEFAULT_INTEREST_RATE_MODEL_VALIDITY_CHECK}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint256 error, uint256 info, uint256 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 (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return uint256(err);
}
}
contract OracleErrorReporter {
enum Error {NO_ERROR, UNAUTHORIZED}
enum FailureInfo {ACCEPT_ADMIN_PENDING_ADMIN_CHECK, ADD_OR_UPDATE_ORACLES_OWNER_CHECK, SET_PENDING_ADMIN_OWNER_CHECK}
/**
* @dev `error` corresponds to enum Error; `info` corresponds to enum FailureInfo, and `detail` is an arbitrary
* contract-specific code that enables us to report opaque error codes from upgradeable contracts.
**/
event Failure(uint256 error, uint256 info, uint256 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 (uint256) {
emit Failure(uint256(err), uint256(info), 0);
return uint256(err);
}
/**
* @dev use this when reporting an opaque error from an upgradeable collaborator contract
*/
function failOpaque(
Error err,
FailureInfo info,
uint256 opaqueError
) internal returns (uint256) {
emit Failure(uint256(err), uint256(info), opaqueError);
return uint256(err);
}
}
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);
}
// SPDX-License-Identifier: MIT
pragma solidity 0.5.17;
/**
* @notice String operations
* @dev Sourced from the OpenZeppelin implementation here: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/c789941d76dd713333bdeafe5b4484f6d9543c4e/contracts/utils/Strings.sol
*/
library Strings {
/**
* @dev Converts a `uint256` to its ASCII `string` representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
uint256 index = digits - 1;
temp = value;
while (temp != 0) {
buffer[index--] = bytes1(uint8(48 + (temp % 10)));
temp /= 10;
}
return string(buffer);
}
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity 0.5.17;
/**
* @notice Interface for creating or interacting with a Trigger contract
* @dev All trigger contracts created must conform to this interface
*/
contract TriggerInterface {
/// @notice Trigger name
function name() external view returns (string memory);
/// @notice Trigger symbol
function symbol() external view returns (string memory);
/// @notice Trigger description
function description() external view returns (string memory);
/// @notice Returns array of IDs, where each ID corresponds to a platform covered by this trigger
/// @dev See documentation for mapping of ID number to platform
function getPlatformIds() external view returns (uint256[] memory);
/// @notice Returns address of recipient who receives subsidies for creating the trigger and associated protection market
function recipient() external view returns (address);
/// @notice Returns true if trigger condition has been met
function isTriggered() external view returns (bool);
/// @notice Checks trigger condition, sets isTriggered flag to true if condition is met, and returns the new trigger status
function checkAndToggleTrigger() external returns (bool);
}
pragma solidity 0.5.17;
import "./CToken.sol";
/**
* @notice CTokens which wrap an EIP-20 underlying
*/
contract CErc20 is CToken, CErc20Interface {
/**
* @notice Initialize a new money market or protection market
* @param underlying_ The address of the underlying asset
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ ERC-20 name of this token
* @param symbol_ ERC-20 symbol of this token
* @param decimals_ ERC-20 decimal precision of this token
* @param trigger_ Trigger contract address for protection markets, or the zero address for money markets
*/
function initialize(
address underlying_,
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint256 initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address trigger_
) public {
// CToken initialize does the bulk of the work
super.initialize(
comptroller_,
interestRateModel_,
initialExchangeRateMantissa_,
name_,
symbol_,
decimals_,
trigger_
);
// Set underlying and sanity check it
underlying = underlying_;
EIP20Interface(underlying).totalSupply();
}
/*** User Interface ***/
/**
* @notice Sender supplies assets into the market and receives cTokens in exchange
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param mintAmount The amount of the underlying asset to supply
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function mint(uint256 mintAmount) external returns (uint256) {
(uint256 err, ) = mintInternal(mintAmount);
return err;
}
/**
* @notice Sender redeems cTokens in exchange for the underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemTokens The number of cTokens to redeem into underlying
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeem(uint256 redeemTokens) external returns (uint256) {
return redeemInternal(redeemTokens);
}
/**
* @notice Sender redeems cTokens in exchange for a specified amount of underlying asset
* @dev Accrues interest whether or not the operation succeeds, unless reverted
* @param redeemAmount The amount of underlying to redeem
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function redeemUnderlying(uint256 redeemAmount) external returns (uint256) {
return redeemUnderlyingInternal(redeemAmount);
}
/**
* @notice Sender borrows assets from the protocol to their own address
* @param borrowAmount The amount of the underlying asset to borrow
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function borrow(uint256 borrowAmount) external returns (uint256) {
return borrowInternal(borrowAmount);
}
/**
* @notice Sender repays their own borrow
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrow(uint256 repayAmount) external returns (uint256) {
(uint256 err, ) = repayBorrowInternal(repayAmount);
return err;
}
/**
* @notice Sender repays a borrow belonging to borrower
* @param borrower the account with the debt being payed off
* @param repayAmount The amount to repay
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256) {
(uint256 err, ) = repayBorrowBehalfInternal(borrower, repayAmount);
return err;
}
/**
* @notice The sender liquidates the borrowers collateral.
* The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param repayAmount The amount of the underlying borrowed asset to repay
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function liquidateBorrow(
address borrower,
uint256 repayAmount,
CTokenInterface cTokenCollateral
) external returns (uint256) {
(uint256 err, ) = liquidateBorrowInternal(borrower, repayAmount, cTokenCollateral);
return err;
}
/**
* @notice The sender adds to reserves.
* @param addAmount The amount fo underlying token to add as reserves
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function _addReserves(uint256 addAmount) external returns (uint256) {
return _addReservesInternal(addAmount);
}
/*** Safe Token ***/
/**
* @notice Gets balance of this contract in terms of the underlying
* @dev This excludes the value of the current message, if any
* @return The quantity of underlying tokens owned by this contract
*/
function getCashPrior() internal view returns (uint256) {
EIP20Interface token = EIP20Interface(underlying);
return token.balanceOf(address(this));
}
/**
* @dev Similar to EIP20 transfer, except it handles a False result from `transferFrom` and reverts in that case.
* This will revert due to insufficient balance or insufficient allowance.
* This function returns the actual amount received,
* which may be less than `amount` if there is a fee attached to the transfer.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferIn(address from, uint256 amount) internal returns (uint256) {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
uint256 balanceBefore = EIP20Interface(underlying).balanceOf(address(this));
token.transferFrom(from, address(this), amount);
bool success;
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_IN_FAILED");
// Calculate the amount that was *actually* transferred
uint256 balanceAfter = EIP20Interface(underlying).balanceOf(address(this));
require(balanceAfter >= balanceBefore, "TOKEN_TRANSFER_IN_OVERFLOW");
return balanceAfter - balanceBefore; // underflow already checked above, just subtract
}
/**
* @dev Similar to EIP20 transfer, except it handles a False success from `transfer` and returns an explanatory
* error code rather than reverting. If caller has not called checked protocol's balance, this may revert due to
* insufficient cash held in this contract. If caller has checked protocol's balance prior to this call, and verified
* it is >= amount, this should not revert in normal conditions.
*
* Note: This wrapper safely handles non-standard ERC-20 tokens that do not return a value.
* See here: https://medium.com/coinmonks/missing-return-value-bug-at-least-130-tokens-affected-d67bf08521ca
*/
function doTransferOut(address payable to, uint256 amount) internal {
EIP20NonStandardInterface token = EIP20NonStandardInterface(underlying);
token.transfer(to, amount);
bool success;
assembly {
switch returndatasize()
case 0 {
// This is a non-standard ERC-20
success := not(0) // set success to true
}
case 32 {
// This is a compliant ERC-20
returndatacopy(0, 0, 32)
success := mload(0) // Set `success = returndata` of external call
}
default {
// This is an excessively non-compliant ERC-20, revert.
revert(0, 0)
}
}
require(success, "TOKEN_TRANSFER_OUT_FAILED");
}
}
pragma solidity 0.5.17;
import "./ComptrollerInterface.sol";
import "./CTokenInterfaces.sol";
import "./TriggerInterface.sol";
import "./ErrorReporter.sol";
import "./Exponential.sol";
import "./EIP20Interface.sol";
import "./EIP20NonStandardInterface.sol";
import "./InterestRateModel.sol";
/**
* @notice Abstract base for CTokens
*/
contract CToken is CTokenInterface, Exponential, TokenErrorReporter {
/// @notice The EIP-712 typehash for the contract's domain (computed inline later to reduce contract size)
/// @dev Not exposing DOMAIN_SEPARATOR means this implementation not conform to EIP-2612
// bytes32 public constant DOMAIN_SEPARATOR = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the ballot struct used by the contract (inlined later to reduce contract size)
// bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
// = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9
/// @notice Nonce mapping for permit support
mapping(address => uint256) public nonces;
/**
* @notice Initialize a new money market or protection market
* @param comptroller_ The address of the Comptroller
* @param interestRateModel_ The address of the interest rate model
* @param initialExchangeRateMantissa_ The initial exchange rate, scaled by 1e18
* @param name_ EIP-20 name of this token
* @param symbol_ EIP-20 symbol of this token
* @param decimals_ EIP-20 decimal precision of this token
* @param trigger_ Trigger contract address for protection markets, or the zero address for money markets
*/
function initialize(
ComptrollerInterface comptroller_,
InterestRateModel interestRateModel_,
uint256 initialExchangeRateMantissa_,
string memory name_,
string memory symbol_,
uint8 decimals_,
address trigger_
) public {
require(msg.sender == admin, "only admin may initialize market");
require(accrualBlockNumber == 0 && borrowIndex == 0, "market already initialized");
// Set initial exchange rate
initialExchangeRateMantissa = initialExchangeRateMantissa_;
require(initialExchangeRateMantissa > 0, "initial exchange rate must be above zero");
// Set the comptroller
// Ensure invoke comptroller.isComptroller() returns true
require(comptroller_.isComptroller(), "marker method returned false");
// Set market's comptroller to newComptroller
emit NewComptroller(comptroller, comptroller_);
comptroller = comptroller_;
// 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)
uint256 err = _setInterestRateModelFresh(interestRateModel_);
require(err == uint256(Error.NO_ERROR), "setting interest rate model failed");
name = name_;
symbol = symbol_;
decimals = decimals_;
// The counter starts true to prevent changing it from zero to non-zero (i.e. smaller cost/refund)
_notEntered = true;
// Set trigger contract address and market type
trigger = trigger_;
emit TriggerSet(false);
}
/**
* @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,
uint256 tokens
) internal returns (uint256) {
/* Fail if transfer not allowed */
uint256 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 */
uint256 startingAllowance = 0;
if (spender == src) {
startingAllowance = uint256(-1);
} else {
startingAllowance = transferAllowances[src][spender];
}
/* Do the calculations, checking for {under,over}flow */
MathError mathErr;
uint256 allowanceNew;
uint256 srcTokensNew;
uint256 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 != uint256(-1)) {
transferAllowances[src][spender] = allowanceNew;
}
/* We emit a Transfer event */
emit Transfer(src, dst, tokens);
return uint256(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) == uint256(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) == uint256(Error.NO_ERROR);
}
/**
* @notice Approve `spender` to transfer up to `amount` from `owner` (base method)
* @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 owner The address of the account that owns the tokens
* @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 owner,
address spender,
uint256 amount
) private returns (bool) {
transferAllowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
return true;
}
/**
* @notice Approve `spender` to transfer up to `amount` from `msg.sender`
* @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) {
return _approve(msg.sender, spender, amount);
}
/**
* @notice Permit - approve a 'spender' to transfer up to 'amount' from owner if signatore denotes owner
* @dev This will overwrite the approval amount for `spender` should the signature indicate the proper owner
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external {
require(deadline >= block.timestamp, "Permit expired");
// Original address recovery and digest creation code
// bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_SEPARATOR, keccak256(bytes(name)), getChainId(), address(this)));
// bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, value, nonces[owner]++, deadline));
// bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
// address recoveredAddress = ecrecover(digest, v, r, s);
// Digest creation and address recovery code with everything in-line and permit hash pre-hashed to reduce code size
address recoveredAddress =
ecrecover(
keccak256(
abi.encodePacked(
"\x19\x01",
keccak256(
abi.encode(
keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"),
keccak256(bytes(name)),
getChainId(),
address(this)
)
),
keccak256(
abi.encode(
0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9,
owner,
spender,
value,
nonces[owner]++,
deadline
)
)
)
),
v,
r,
s
);
require(recoveredAddress != address(0) && recoveredAddress == owner, "Invalid signature");
_approve(owner, spender, value);
}
/**
* @notice Get the chain ID (uses assembly)
* @return The chain ID
*/
function getChainId() internal pure returns (uint256) {
uint256 chainId;
assembly {
chainId := chainid()
}
return chainId;
}
/**
* @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 (uint256) {
Exp memory exchangeRate = Exp({mantissa: exchangeRateCurrent()});
(MathError mErr, uint256 balance) = mulScalarTruncate(exchangeRate, accountTokens[owner]);
require(mErr == MathError.NO_ERROR, "could not calculate balance");
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 (
uint256,
uint256,
uint256,
uint256
)
{
uint256 cTokenBalance = accountTokens[account];
uint256 borrowBalance;
uint256 exchangeRateMantissa;
MathError mErr;
(mErr, borrowBalance) = borrowBalanceStoredInternal(account);
if (mErr != MathError.NO_ERROR) {
return (uint256(Error.MATH_ERROR), 0, 0, 0);
}
(mErr, exchangeRateMantissa) = exchangeRateStoredInternal();
if (mErr != MathError.NO_ERROR) {
return (uint256(Error.MATH_ERROR), 0, 0, 0);
}
return (uint256(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 (uint256) {
return block.number;
}
/**
* @notice Returns the current per-block borrow interest rate for this cToken
* @return The borrow interest rate per block, scaled by 1e18
*/
function borrowRatePerBlock() external view returns (uint256) {
if (isTriggered) {
return 0;
}
return interestRateModel.getBorrowRate(getCashPrior(), totalBorrows, totalReserves);
}
/**
* @notice Returns the current per-block supply interest rate for this cToken
* @return The supply interest rate per block, scaled by 1e18
*/
function supplyRatePerBlock() external view returns (uint256) {
if (isTriggered) {
return 0;
}
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 (uint256) {
require(accrueInterest() == uint256(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 (uint256) {
require(accrueInterest() == uint256(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 (uint256) {
(MathError err, uint256 result) = borrowBalanceStoredInternal(account);
require(err == MathError.NO_ERROR, "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, uint256) {
if (isTriggered) {
return (MathError.NO_ERROR, 0);
}
/* Note: we do not assert that the market is up to date */
MathError mathErr;
uint256 principalTimesIndex;
uint256 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 (uint256) {
require(accrueInterest() == uint256(Error.NO_ERROR), "accrue interest failed");
return exchangeRateStored();
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return Calculated exchange rate scaled by 1e18
*/
function exchangeRateStored() public view returns (uint256) {
(MathError err, uint256 result) = exchangeRateStoredInternal();
require(err == MathError.NO_ERROR, "exchangeRateStoredInternal failed");
return result;
}
/**
* @notice Calculates the exchange rate from the underlying to the CToken
* @dev This function does not accrue interest before calculating the exchange rate
* @return (error code, calculated exchange rate scaled by 1e18)
*/
function exchangeRateStoredInternal() internal view returns (MathError, uint256) {
uint256 _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
*/
uint256 totalCash = getCashPrior();
uint256 cashPlusBorrowsMinusReserves;
Exp memory exchangeRate;
MathError mathErr;
(mathErr, cashPlusBorrowsMinusReserves) = addThenSubUInt(totalCash, totalBorrows, totalReserves);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
(mathErr, exchangeRate) = getExp(cashPlusBorrowsMinusReserves, _totalSupply);
if (mathErr != MathError.NO_ERROR) {
return (mathErr, 0);
}
return (MathError.NO_ERROR, exchangeRate.mantissa);
}
}
/**
* @notice Get cash balance of this cToken in the underlying asset
* @return The quantity of underlying asset owned by this contract
*/
function getCash() external view returns (uint256) {
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 (uint256) {
/* Short-circuit if trigger event occured */
if (isTriggered) {
accrualBlockNumber = getBlockNumber(); // required to allow redemptions
return uint256(Error.NO_ERROR);
}
/* Remember the initial block number */
uint256 currentBlockNumber = getBlockNumber();
uint256 accrualBlockNumberPrior = accrualBlockNumber;
/* Short-circuit accumulating 0 interest */
if (accrualBlockNumberPrior == currentBlockNumber) {
return uint256(Error.NO_ERROR);
}
/* Read the previous values out of storage */
uint256 cashPrior = getCashPrior();
uint256 borrowsPrior = totalBorrows;
uint256 reservesPrior = totalReserves;
uint256 borrowIndexPrior = borrowIndex;
/* Calculate the current borrow interest rate */
uint256 borrowRateMantissa = interestRateModel.getBorrowRate(cashPrior, borrowsPrior, reservesPrior);
require(borrowRateMantissa <= borrowRateMaxMantissa, "borrow rate too high");
/* Calculate the number of blocks elapsed since the last accrual */
(MathError mathErr, uint256 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;
uint256 interestAccumulated;
uint256 totalBorrowsNew;
uint256 totalReservesNew;
uint256 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,
uint256(mathErr)
);
}
(mathErr, interestAccumulated) = mulScalarTruncate(simpleInterestFactor, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return
failOpaque(
Error.MATH_ERROR,
FailureInfo.ACCRUE_INTEREST_ACCUMULATED_INTEREST_CALCULATION_FAILED,
uint256(mathErr)
);
}
(mathErr, totalBorrowsNew) = addUInt(interestAccumulated, borrowsPrior);
if (mathErr != MathError.NO_ERROR) {
return
failOpaque(
Error.MATH_ERROR,
FailureInfo.ACCRUE_INTEREST_NEW_TOTAL_BORROWS_CALCULATION_FAILED,
uint256(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,
uint256(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, uint256(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 uint256(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(uint256 mintAmount) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(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;
uint256 exchangeRateMantissa;
uint256 mintTokens;
uint256 totalSupplyNew;
uint256 accountTokensNew;
uint256 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, uint256 mintAmount) internal whenNotTriggered returns (uint256, uint256) {
/* Fail if mint not allowed */
uint256 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, uint256(vars.mathErr)), 0);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call `doTransferIn` for the minter and the mintAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* `doTransferIn` reverts if anything goes wrong, since we can't be sure if
* side-effects occurred. The function returns the amount actually transferred,
* in case of a fee. On success, the cToken holds an additional `actualMintAmount`
* of cash.
*/
vars.actualMintAmount = doTransferIn(minter, mintAmount);
/*
* We get the current exchange rate and calculate the number of cTokens to be minted:
* mintTokens = actualMintAmount / exchangeRate
*/
(vars.mathErr, vars.mintTokens) = divScalarByExpTruncate(
vars.actualMintAmount,
Exp({mantissa: vars.exchangeRateMantissa})
);
require(vars.mathErr == MathError.NO_ERROR, "MINT_EXCHANGE_CALCULATION_FAILED");
/*
* We calculate the new total supply of cTokens and minter token balance, checking for overflow:
* totalSupplyNew = totalSupply + mintTokens
* accountTokensNew = accountTokens[minter] + mintTokens
*/
(vars.mathErr, vars.totalSupplyNew) = addUInt(totalSupply, vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_TOTAL_SUPPLY_CALCULATION_FAILED");
(vars.mathErr, vars.accountTokensNew) = addUInt(accountTokens[minter], vars.mintTokens);
require(vars.mathErr == MathError.NO_ERROR, "MINT_NEW_ACCOUNT_BALANCE_CALCULATION_FAILED");
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[minter] = vars.accountTokensNew;
/* We emit a Mint event, and a Transfer event */
emit Mint(minter, vars.actualMintAmount, vars.mintTokens);
emit Transfer(address(this), minter, vars.mintTokens);
return (uint256(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(uint256 redeemTokens) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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(uint256 redeemAmount) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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;
uint256 exchangeRateMantissa;
uint256 redeemTokens;
uint256 redeemAmount;
uint256 totalSupplyNew;
uint256 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,
uint256 redeemTokensIn,
uint256 redeemAmountIn
) internal returns (uint256) {
// If trigger has not been toggled yet, check the condition, and if toggled exit this function and return failure
// code indicating this. We have the `!isTriggered` check because without this suppliers would be blocked from
// redeeming funds after a trigger occurs. In other words, we allow redeems in transactions before the trigger
// was toggled, and in transactions after the trigger was toggled, but not if the trigger was just toggled in
// this transaction
if (!isTriggered && checkAndToggleTriggerInternal()) {
return fail(Error.MARKET_TRIGGERED, FailureInfo.TRIGGER_ACTIVATED_BEFORE_REDEEM_OR_BORROW);
}
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, uint256(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, uint256(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, uint256(vars.mathErr));
}
vars.redeemAmount = redeemAmountIn;
}
/* Fail if redeem not allowed */
uint256 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, uint256(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, uint256(vars.mathErr));
}
/* Fail gracefully if protocol has insufficient cash */
if (getCashPrior() < vars.redeemAmount) {
return fail(Error.TOKEN_INSUFFICIENT_CASH, FailureInfo.REDEEM_TRANSFER_OUT_NOT_POSSIBLE);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the redeemer and the redeemAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken has redeemAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(redeemer, vars.redeemAmount);
/* We write previously calculated values into storage */
totalSupply = vars.totalSupplyNew;
accountTokens[redeemer] = vars.accountTokensNew;
/* We emit a Transfer event, and a Redeem event */
emit Transfer(redeemer, address(this), vars.redeemTokens);
emit Redeem(redeemer, vars.redeemAmount, vars.redeemTokens);
/* Require tokens is zero or amount is also zero */
if (vars.redeemTokens == 0 && vars.redeemAmount > 0) {
revert("redeemTokens zero");
}
return uint256(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(uint256 borrowAmount) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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;
uint256 accountBorrows;
uint256 accountBorrowsNew;
uint256 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, uint256 borrowAmount) internal whenNotTriggered returns (uint256) {
// Check trigger condition, and if triggered, exit function and return failure code indicating this
if (checkAndToggleTriggerInternal()) {
return fail(Error.MARKET_TRIGGERED, FailureInfo.TRIGGER_ACTIVATED_BEFORE_REDEEM_OR_BORROW);
}
/* Fail if borrow not allowed */
uint256 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, uint256(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,
uint256(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, uint256(vars.mathErr));
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We invoke doTransferOut for the borrower and the borrowAmount.
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken borrowAmount less of cash.
* doTransferOut reverts if anything goes wrong, since we can't be sure if side effects occurred.
*/
doTransferOut(borrower, borrowAmount);
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a Borrow event */
emit Borrow(borrower, borrowAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
return uint256(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(uint256 repayAmount) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(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, uint256 repayAmount)
internal
nonReentrant
returns (uint256, uint256)
{
uint256 error = accrueInterest();
if (error != uint256(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;
uint256 repayAmount;
uint256 borrowerIndex;
uint256 accountBorrows;
uint256 accountBorrowsNew;
uint256 totalBorrowsNew;
uint256 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,
uint256 repayAmount
) internal whenNotTriggered returns (uint256, uint256) {
/* Fail if repayBorrow not allowed */
uint256 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,
uint256(vars.mathErr)
),
0
);
}
/* If repayAmount == -1, repayAmount = accountBorrows */
if (repayAmount == uint256(-1)) {
vars.repayAmount = vars.accountBorrows;
} else {
vars.repayAmount = repayAmount;
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the payer and the repayAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional repayAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
vars.actualRepayAmount = doTransferIn(payer, vars.repayAmount);
/*
* We calculate the new borrower and total borrow balances, failing on underflow:
* accountBorrowsNew = accountBorrows - actualRepayAmount
* totalBorrowsNew = totalBorrows - actualRepayAmount
*/
(vars.mathErr, vars.accountBorrowsNew) = subUInt(vars.accountBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_ACCOUNT_BORROW_BALANCE_CALCULATION_FAILED");
(vars.mathErr, vars.totalBorrowsNew) = subUInt(totalBorrows, vars.actualRepayAmount);
require(vars.mathErr == MathError.NO_ERROR, "REPAY_BORROW_NEW_TOTAL_BALANCE_CALCULATION_FAILED");
/* We write the previously calculated values into storage */
accountBorrows[borrower].principal = vars.accountBorrowsNew;
accountBorrows[borrower].interestIndex = borrowIndex;
totalBorrows = vars.totalBorrowsNew;
/* We emit a RepayBorrow event */
emit RepayBorrow(payer, borrower, vars.actualRepayAmount, vars.accountBorrowsNew, vars.totalBorrowsNew);
return (uint256(Error.NO_ERROR), vars.actualRepayAmount);
}
/**
* @notice The sender liquidates the borrowers collateral. The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowInternal(
address borrower,
uint256 repayAmount,
CTokenInterface cTokenCollateral
) internal nonReentrant returns (uint256, uint256) {
uint256 error = accrueInterest();
if (error != uint256(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 != uint256(Error.NO_ERROR)) {
// accrueInterest emits logs on errors, but we still want to log the fact that an attempted liquidation failed
return (fail(Error(error), FailureInfo.LIQUIDATE_ACCRUE_COLLATERAL_INTEREST_FAILED), 0);
}
// liquidateBorrowFresh emits borrow-specific logs on errors, so we don't need to
return liquidateBorrowFresh(msg.sender, borrower, repayAmount, cTokenCollateral);
}
/**
* @notice The liquidator liquidates the borrowers collateral. The collateral seized is transferred to the liquidator.
* @param borrower The borrower of this cToken to be liquidated
* @param liquidator The address repaying the borrow and seizing collateral
* @param cTokenCollateral The market in which to seize collateral from the borrower
* @param repayAmount The amount of the underlying borrowed asset to repay
* @return (uint, uint) An error code (0=success, otherwise a failure, see ErrorReporter.sol), and the actual repayment amount.
*/
function liquidateBorrowFresh(
address liquidator,
address borrower,
uint256 repayAmount,
CTokenInterface cTokenCollateral
) internal whenNotTriggered returns (uint256, uint256) {
/* Fail if liquidate not allowed */
uint256 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 == uint256(-1)) {
return (fail(Error.INVALID_CLOSE_AMOUNT_REQUESTED, FailureInfo.LIQUIDATE_CLOSE_AMOUNT_IS_UINT_MAX), 0);
}
/* Fail if repayBorrow fails */
(uint256 repayBorrowError, uint256 actualRepayAmount) = repayBorrowFresh(liquidator, borrower, repayAmount);
if (repayBorrowError != uint256(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 */
(uint256 amountSeizeError, uint256 seizeTokens) =
comptroller.liquidateCalculateSeizeTokens(address(this), address(cTokenCollateral), actualRepayAmount);
require(amountSeizeError == uint256(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
uint256 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 == uint256(Error.NO_ERROR), "token seizure failed");
/* We emit a LiquidateBorrow event */
emit LiquidateBorrow(liquidator, borrower, actualRepayAmount, address(cTokenCollateral), seizeTokens);
return (uint256(Error.NO_ERROR), actualRepayAmount);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Will fail unless called by another cToken during the process of liquidation.
* It's absolutely critical to use msg.sender as the borrowed cToken and not a parameter.
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external nonReentrant returns (uint256) {
return seizeInternal(msg.sender, liquidator, borrower, seizeTokens);
}
/**
* @notice Transfers collateral tokens (this market) to the liquidator.
* @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken.
* It's absolutely critical to use msg.sender as the seizer cToken and not a parameter.
* @param seizerToken The contract seizing the collateral (i.e. borrowed cToken)
* @param liquidator The account receiving seized collateral
* @param borrower The account having collateral seized
* @param seizeTokens The number of cTokens to seize
* @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)
*/
function seizeInternal(
address seizerToken,
address liquidator,
address borrower,
uint256 seizeTokens
) internal returns (uint256) {
/* Fail if seize not allowed */
uint256 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;
uint256 borrowerTokensNew;
uint256 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, uint256(mathErr));
}
(mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens);
if (mathErr != MathError.NO_ERROR) {
return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint256(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);
return uint256(Error.NO_ERROR);
}
/**
* @notice Checks the trigger contract, and if triggered updates the state
* @dev Implemented as a wrapper around borrow to avoid reentrancy risks. If this method simply called
* `checkAndToggleTriggerInternal`, you have can have a reentrancy risk as follows:
* Call `checkAndToggleTriggerInternal` > enter trigger contract > trigger contract tries to borrow funds >
* borrow method enters `checkAndToggleTriggerInternal` > trigger contract returns false > borrow succeeds >
* trigger contract returns true > debts canceled for a borrow that occured in the triggering transaction
* But you cannot do that if you enter `checkAndToggleTriggerInternal` from the borrow method, because the only way
* to proceed with a borrow is for the trigger to return false
* @return Returns the new trigger status
*/
function checkAndToggleTrigger() external whenNotTriggered returns (bool) {
borrowInternal(0); // this calls `checkAndToggleTriggerInternal`
return isTriggered;
}
/**
* @notice Checks the trigger contract, and if triggered updates the state
* @return Returns the new trigger status
*/
function checkAndToggleTriggerInternal() internal returns (bool) {
/* Trigger can never be toggled for Money Markets, which have the zero address as the trigger address */
if (trigger == address(0)) return false;
/*
* Untrusted call, since anyone can deploy a new protection market with any trigger. However, nothing
* malicious can occur from reentering here, so a reentrancy guard and the checks-effects-interaction
* are not required. The reason nothing malicious can happen is because the reentrancy must come from
* the malicious trigger, and if we had a malicious trigger that tried to exploit reentrancy, here are
* the options:
* 1. Trigger is not toggled: You reenter during the trigger call, you'd call `accrueInterest()` again
* and that method does nothing when called twice in the same block. After `trigger.checkAndToggleTriggerInternal()`
* finally returns false, things continue as normal
* 2. Trigger is toggled: As above, if you reenter during the trigger call, you'd call `accrueInterest()`
* again which will do nothing. If you try to borrow or redeem funds, this method will ultimately return true
* and prevent borrowing/redeeming (along with the `nonReentrant` modifier in `borrowInternal`). If you try to
* supply funds to get more COZY, you'll accrue that COZY for zero blocks and then lose some supplied funds
*/
isTriggered = TriggerInterface(trigger).checkAndToggleTrigger();
if (isTriggered) {
/*
* After the trigger event protection providers cannot redeem the full amount they supplied,
* but can still redeem a fraction of the amount they supplied. This is because the only
* funds left for suppliers to redeem is the unborrowed funds, as borrowed funds do not need
* to be paid back. The amount you can redeem is proportional to how much you supplied.
*
* For example, if $1000 is supplied by protection providers, but only $800 is borrowed by
* protection seekers, then when the trigger happens protection providers can withdraw a total
* of $200 instead of $1000. That $200 is split proportionally between all providers. So if
* Alice provided $300 and Bob provided $700 of the $1000, after the trigger Alice can redeem
* her cTokens for $300 / $1000 * 200 = $60 and Bob can redeem his for $700 / $1000 * 200 = $140
*
* The exchange rate is calculated as:
* exchangeRate = (totalCash + totalBorrows - totalReserves) / totalSupply
*
* Therefore, if we zero out total borrows, the exchange rate methods will calculate the
* desired exchange rate after the trigger event without needing to be modified.
*/
totalBorrows = 0;
emit TriggerSet(isTriggered);
/* End subsidies to the market */
comptroller._zeroOutCozySpeeds(address(this));
}
return isTriggered;
}
/*** 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 (uint256) {
// Check caller = admin
if (msg.sender != admin) {
return fail(Error.UNAUTHORIZED, FailureInfo.SET_PENDING_ADMIN_OWNER_CHECK);
}
emit NewPendingAdmin(pendingAdmin, newPendingAdmin);
// Store pendingAdmin with value newPendingAdmin
pendingAdmin = newPendingAdmin;
return uint256(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 (uint256) {
// 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 uint256(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(uint256 newReserveFactorMantissa) external nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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(uint256 newReserveFactorMantissa) internal returns (uint256) {
// 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);
}
emit NewReserveFactor(reserveFactorMantissa, newReserveFactorMantissa);
reserveFactorMantissa = newReserveFactorMantissa;
return uint256(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(uint256 addAmount) internal nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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(uint256 addAmount) internal returns (uint256, uint256) {
// totalReserves + actualAddAmount
uint256 totalReservesNew;
uint256 actualAddAmount;
// We fail gracefully unless market's block number equals current block number
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
/////////////////////////
// EFFECTS & INTERACTIONS
// (No safe failures beyond this point)
/*
* We call doTransferIn for the caller and the addAmount
* Note: The cToken must handle variations between ERC-20 and ETH underlying.
* On success, the cToken holds an additional addAmount of cash.
* doTransferIn reverts if anything goes wrong, since we can't be sure if side effects occurred.
* it returns the amount actually transferred, in case of a fee.
*/
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
/* Revert on overflow */
require(totalReservesNew >= totalReserves, "add reserves 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 (uint256(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(uint256 reduceAmount) external nonReentrant returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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(uint256 reduceAmount) internal returns (uint256) {
// totalReserves - reduceAmount
uint256 totalReservesNew;
// Check caller is Reserve Guardian or admin
if (msg.sender != comptroller.reserveGuardian() && 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);
}
// Make sure reserve guardian was set to avoid transferring reserves to the zero address
if (comptroller.reserveGuardian() == address(0)) {
return fail(Error.INVALID_GUARDIAN, FailureInfo.REDUCE_RESERVES_GUARDIAN_NOT_SET);
}
/////////////////////////
// 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 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(comptroller.reserveGuardian(), reduceAmount);
emit ReservesReduced(comptroller.reserveGuardian(), reduceAmount, totalReservesNew);
return uint256(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) external returns (uint256) {
uint256 error = accrueInterest();
if (error != uint256(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 (uint256) {
// 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);
}
// Ensure invoke newInterestRateModel.isInterestRateModel() returns true
require(newInterestRateModel.isInterestRateModel(), "marker method returned false");
// Set the interest rate model to newInterestRateModel
emit NewMarketInterestRateModel(interestRateModel, newInterestRateModel);
interestRateModel = newInterestRateModel;
return uint256(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 (uint256);
/**
* @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, uint256 amount) internal returns (uint256);
/**
* @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, uint256 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
}
/**
* @dev Prevents execution of a function if the trigger event has occured
*/
modifier whenNotTriggered() {
require(!isTriggered, "Not allowed once triggered");
_;
}
}
pragma solidity 0.5.17;
/**
* @notice Partial implementation of Comptroller interface. The methods listed here are the set used by CTokens
*/
contract ComptrollerInterface {
/// @notice Indicator that this is a Comptroller contract (for inspection)
bool public constant isComptroller = true;
/// @notice Address that CToken reserves are transferred to
address payable public reserveGuardian;
/*** Assets You Are In ***/
function enterMarkets(address[] calldata cTokens) external returns (uint256[] memory);
function exitMarket(address cToken) external returns (uint256);
/*** Policy Hooks ***/
function mintAllowed(
address cToken,
address minter,
uint256 mintAmount
) external returns (uint256);
function redeemAllowed(
address cToken,
address redeemer,
uint256 redeemTokens
) external returns (uint256);
function borrowAllowed(
address cToken,
address borrower,
uint256 borrowAmount
) external returns (uint256);
function repayBorrowAllowed(
address cToken,
address payer,
address borrower,
uint256 repayAmount
) external returns (uint256);
function liquidateBorrowAllowed(
address cTokenBorrowed,
address cTokenCollateral,
address liquidator,
address borrower,
uint256 repayAmount
) external returns (uint256);
function seizeAllowed(
address cTokenCollateral,
address cTokenBorrowed,
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
function transferAllowed(
address cToken,
address src,
address dst,
uint256 transferTokens
) external returns (uint256);
/*** Liquidity/Liquidation Calculations ***/
function liquidateCalculateSeizeTokens(
address cTokenBorrowed,
address cTokenCollateral,
uint256 repayAmount
) external view returns (uint256, uint256);
/*** COZY ***/
/// @notice Sets supply and borrow COZY subsidies to a market to zero
function _zeroOutCozySpeeds(address cToken) external;
}
pragma solidity 0.5.17;
import "./ComptrollerInterface.sol";
import "./InterestRateModel.sol";
contract CTokenStorage {
/**
* @dev Guard variable for re-entrancy checks
*/
bool internal _notEntered;
/**
* @notice EIP-20 token name for this token
*/
string public name;
/**
* @notice EIP-20 token symbol for this token
*/
string public symbol;
/**
* @notice EIP-20 token decimals for this token
*/
uint8 public decimals;
/**
* @notice Underlying asset for this CToken
*/
address public underlying;
/**
* @notice Maximum borrow rate that can ever be applied (.0005% / block)
*/
uint256 internal constant borrowRateMaxMantissa = 0.0005e16;
/**
* @notice Maximum fraction of interest that can be set aside for reserves
*/
uint256 internal constant reserveFactorMaxMantissa = 1e18;
/**
* @notice Administrator for this contract
*/
address payable public admin;
/**
* @notice Pending administrator for this contract
*/
address payable public pendingAdmin;
/**
* @notice Contract which oversees inter-cToken operations
*/
ComptrollerInterface public comptroller;
/**
* @notice Model which tells what the current interest rate should be
*/
InterestRateModel public interestRateModel;
/**
* @notice Initial exchange rate used when minting the first CTokens (used when totalSupply = 0)
*/
uint256 internal initialExchangeRateMantissa;
/**
* @notice Fraction of interest currently set aside for reserves
*/
uint256 public reserveFactorMantissa;
/**
* @notice Block number that interest was last accrued at
*/
uint256 public accrualBlockNumber;
/**
* @notice Accumulator of the total earned interest rate since the opening of the market
*/
uint256 public borrowIndex;
/**
* @notice Total amount of outstanding borrows of the underlying in this market
*/
uint256 public totalBorrows;
/**
* @notice Total amount of reserves of the underlying held in this market
*/
uint256 public totalReserves;
/**
* @notice Total number of tokens in circulation
*/
uint256 public totalSupply;
/**
* @notice Official record of token balances for each account
*/
mapping(address => uint256) internal accountTokens;
/**
* @notice Approved token transfer amounts on behalf of others
*/
mapping(address => mapping(address => uint256)) 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 {
uint256 principal;
uint256 interestIndex;
}
/**
* @notice Mapping of account addresses to outstanding borrow balances
*/
mapping(address => BorrowSnapshot) internal accountBorrows;
/**
* @notice Trigger address if token is part of the protection market, zero address otherwise
*/
address public trigger;
/**
* @notice Total number of tokens in circulation at the time the trigger event was activated
* @dev This variable is not used, but for some reason removing it increases contract size (compiler bug?) so it's kept
*/
uint256 public totalSupplyWhenTriggered;
}
contract CTokenInterface is CTokenStorage {
/**
* @notice Indicator that this is a CToken contract (for inspection)
*/
bool public constant isCToken = true;
/**
* @notice Becomes true when the associated `trigger` contract signals that trigger event has occured
* @dev This is a one-way toggle: Once set to true it cannot be set back to false
*/
bool public isTriggered = false;
/*** Market Events ***/
/**
* @notice Event emitted when interest is accrued
*/
event AccrueInterest(uint256 cashPrior, uint256 interestAccumulated, uint256 borrowIndex, uint256 totalBorrows);
/**
* @notice Event emitted when tokens are minted
*/
event Mint(address minter, uint256 mintAmount, uint256 mintTokens);
/**
* @notice Event emitted when tokens are redeemed
*/
event Redeem(address redeemer, uint256 redeemAmount, uint256 redeemTokens);
/**
* @notice Event emitted when underlying is borrowed
*/
event Borrow(address borrower, uint256 borrowAmount, uint256 accountBorrows, uint256 totalBorrows);
/**
* @notice Event emitted when a borrow is repaid
*/
event RepayBorrow(address payer, address borrower, uint256 repayAmount, uint256 accountBorrows, uint256 totalBorrows);
/**
* @notice Event emitted when a borrow is liquidated
*/
event LiquidateBorrow(
address liquidator,
address borrower,
uint256 repayAmount,
address cTokenCollateral,
uint256 seizeTokens
);
/*** Admin Events ***/
/**
* @notice Event emitted when pendingAdmin is changed
*/
event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin);
/**
* @notice Event emitted when pendingAdmin is accepted, which means admin is updated
*/
event NewAdmin(address oldAdmin, address newAdmin);
/**
* @notice Event emitted when 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(uint256 oldReserveFactorMantissa, uint256 newReserveFactorMantissa);
/**
* @notice Event emitted when the reserves are added
*/
event ReservesAdded(address benefactor, uint256 addAmount, uint256 newTotalReserves);
/**
* @notice Event emitted when the reserves are reduced
*/
event ReservesReduced(address admin, uint256 reduceAmount, uint256 newTotalReserves);
/**
* @notice EIP20 Transfer event
*/
event Transfer(address indexed from, address indexed to, uint256 amount);
/**
* @notice EIP20 Approval event
*/
event Approval(address indexed owner, address indexed spender, uint256 amount);
/**
* @notice Event emitted when trigger status is set
*/
event TriggerSet(bool isTriggered);
/**
* @notice Failure event
*/
event Failure(uint256 error, uint256 info, uint256 detail);
/*** User Interface ***/
function transfer(address dst, uint256 amount) external returns (bool);
function transferFrom(
address src,
address dst,
uint256 amount
) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
function balanceOf(address owner) external view returns (uint256);
function balanceOfUnderlying(address owner) external returns (uint256);
function getAccountSnapshot(address account)
external
view
returns (
uint256,
uint256,
uint256,
uint256
);
function borrowRatePerBlock() external view returns (uint256);
function supplyRatePerBlock() external view returns (uint256);
function totalBorrowsCurrent() external returns (uint256);
function borrowBalanceCurrent(address account) external returns (uint256);
function borrowBalanceStored(address account) public view returns (uint256);
function exchangeRateCurrent() public returns (uint256);
function exchangeRateStored() public view returns (uint256);
function getCash() external view returns (uint256);
function accrueInterest() public returns (uint256);
function seize(
address liquidator,
address borrower,
uint256 seizeTokens
) external returns (uint256);
/*** Admin Functions ***/
function _setPendingAdmin(address payable newPendingAdmin) external returns (uint256);
function _acceptAdmin() external returns (uint256);
function _setReserveFactor(uint256 newReserveFactorMantissa) external returns (uint256);
function _reduceReserves(uint256 reduceAmount) external returns (uint256);
function _setInterestRateModel(InterestRateModel newInterestRateModel) external returns (uint256);
}
contract CErc20Storage {}
contract CErc20Interface is CErc20Storage {
/*** User Interface ***/
function mint(uint256 mintAmount) external returns (uint256);
function redeem(uint256 redeemTokens) external returns (uint256);
function redeemUnderlying(uint256 redeemAmount) external returns (uint256);
function borrow(uint256 borrowAmount) external returns (uint256);
function repayBorrow(uint256 repayAmount) external returns (uint256);
function repayBorrowBehalf(address borrower, uint256 repayAmount) external returns (uint256);
function liquidateBorrow(
address borrower,
uint256 repayAmount,
CTokenInterface cTokenCollateral
) external returns (uint256);
/*** Admin Functions ***/
function _addReserves(uint256 addAmount) external returns (uint256);
}
contract CDelegationStorage {
/**
* @notice Implementation address for this contract
*/
address public implementation;
}
contract CDelegatorInterface is CDelegationStorage {
/**
* @notice Emitted when implementation is changed
*/
event NewImplementation(address oldImplementation, address newImplementation);
/**
* @notice Called by the admin to update the implementation of the delegator
* @param implementation_ The address of the new implementation for delegation
* @param allowResign Flag to indicate whether to call _resignImplementation on the old implementation
* @param becomeImplementationData The encoded bytes data to be passed to _becomeImplementation
*/
function _setImplementation(
address implementation_,
bool allowResign,
bytes memory becomeImplementationData
) public;
}
contract CDelegateInterface is CDelegationStorage {
/**
* @notice Called by the delegator on a delegate to initialize it for duty
* @dev Should revert if any issues arise which make it unfit for delegation
* @param data The encoded bytes data for any initialization
*/
function _becomeImplementation(bytes memory data) public;
/**
* @notice Called by the delegator on a delegate to forfeit its responsibility
*/
function _resignImplementation() public;
}
pragma solidity 0.5.17;
import "./CarefulMath.sol";
import "./ExponentialNoError.sol";
/**
* @title Exponential module for storing fixed-precision decimals
* @author Compound
* @dev Legacy contract for compatibility reasons with existing contracts that still use MathError
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract Exponential is CarefulMath, ExponentialNoError {
/**
* @dev Creates an exponential from numerator and denominator values.
* Note: Returns an error if (`num` * 10e18) > MAX_INT,
* or if `denom` is zero.
*/
function getExp(uint256 num, uint256 denom) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 scaledNumerator) = mulUInt(num, expScale);
if (err0 != MathError.NO_ERROR) {
return (err0, Exp({mantissa: 0}));
}
(MathError err1, uint256 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) internal pure returns (MathError, Exp memory) {
(MathError error, uint256 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) internal pure returns (MathError, Exp memory) {
(MathError error, uint256 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, uint256 scalar) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 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, uint256 scalar) internal pure returns (MathError, uint256) {
(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,
uint256 scalar,
uint256 addend
) internal pure returns (MathError, uint256) {
(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, uint256 scalar) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 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(uint256 scalar, Exp memory divisor) internal pure 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, uint256 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(uint256 scalar, Exp memory divisor) internal pure returns (MathError, uint256) {
(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) internal pure returns (MathError, Exp memory) {
(MathError err0, uint256 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, uint256 doubleScaledProductWithHalfScale) = addUInt(halfExpScale, doubleScaledProduct);
if (err1 != MathError.NO_ERROR) {
return (err1, Exp({mantissa: 0}));
}
(MathError err2, uint256 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(uint256 a, uint256 b) internal pure 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
) internal pure 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) internal pure returns (MathError, Exp memory) {
return getExp(a.mantissa, b.mantissa);
}
}
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);
}
pragma solidity 0.5.17;
/**
* @title Compound's InterestRateModel Interface
* @author Compound
*/
contract InterestRateModel {
/// @notice Indicator that this is an InterestRateModel contract (for inspection)
bool public constant isInterestRateModel = true;
/**
* @notice Calculates the current borrow interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @return The borrow rate per block (as a percentage, and scaled by 1e18)
*/
function getBorrowRate(
uint256 cash,
uint256 borrows,
uint256 reserves
) external view returns (uint256);
/**
* @notice Calculates the current supply interest rate per block
* @param cash The total amount of cash the market has
* @param borrows The total amount of borrows the market has outstanding
* @param reserves The total amount of reserves the market has
* @param reserveFactorMantissa The current reserve factor the market has
* @return The supply rate per block (as a percentage, and scaled by 1e18)
*/
function getSupplyRate(
uint256 cash,
uint256 borrows,
uint256 reserves,
uint256 reserveFactorMantissa
) external view returns (uint256);
}
pragma solidity 0.5.17;
/**
* @title Careful Math
* @author Compound
* @notice Derived from OpenZeppelin's SafeMath library
* https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract CarefulMath {
/**
* @dev Possible error codes that we can return
*/
enum MathError {NO_ERROR, DIVISION_BY_ZERO, INTEGER_OVERFLOW, INTEGER_UNDERFLOW}
/**
* @dev Multiplies two numbers, returns an error on overflow.
*/
function mulUInt(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
if (a == 0) {
return (MathError.NO_ERROR, 0);
}
uint256 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(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
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(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
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(uint256 a, uint256 b) internal pure returns (MathError, uint256) {
uint256 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(
uint256 a,
uint256 b,
uint256 c
) internal pure returns (MathError, uint256) {
(MathError err0, uint256 sum) = addUInt(a, b);
if (err0 != MathError.NO_ERROR) {
return (err0, 0);
}
return subUInt(sum, c);
}
}
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 ExponentialNoError {
uint256 constant expScale = 1e18;
uint256 constant doubleScale = 1e36;
uint256 constant halfExpScale = expScale / 2;
uint256 constant mantissaOne = expScale;
struct Exp {
uint256 mantissa;
}
struct Double {
uint256 mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) internal pure returns (uint256) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint256 scalar) internal pure returns (uint256) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(
Exp memory a,
uint256 scalar,
uint256 addend
) internal pure returns (uint256) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) internal pure returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) internal pure returns (bool) {
return value.mantissa == 0;
}
function safe224(uint256 n, string memory errorMessage) internal pure returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint256 n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint256 a, uint256 b) internal pure returns (uint256) {
return add_(a, b, "addition overflow");
}
function add_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint256 a, uint256 b) internal pure returns (uint256) {
return sub_(a, b, "subtraction underflow");
}
function sub_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Exp memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint256 b) internal pure returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint256 a, Double memory b) internal pure returns (uint256) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint256 a, uint256 b) internal pure returns (uint256) {
return mul_(a, b, "multiplication overflow");
}
function mul_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint256 b) internal pure returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Exp memory b) internal pure returns (uint256) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) internal pure returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint256 b) internal pure returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint256 a, Double memory b) internal pure returns (uint256) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint256 a, uint256 b) internal pure returns (uint256) {
return div_(a, b, "divide by zero");
}
function div_(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint256 a, uint256 b) internal pure returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
| Add reserves by transferring from caller Requires fresh interest accrual 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/ totalReserves + actualAddAmount We fail gracefully unless market's block number equals current block number | function _addReservesFresh(uint256 addAmount) internal returns (uint256, uint256) {
uint256 totalReservesNew;
uint256 actualAddAmount;
if (accrualBlockNumber != getBlockNumber()) {
return (fail(Error.MARKET_NOT_FRESH, FailureInfo.ADD_RESERVES_FRESH_CHECK), actualAddAmount);
}
actualAddAmount = doTransferIn(msg.sender, addAmount);
totalReservesNew = totalReserves + actualAddAmount;
}
| 14,760,597 |
pragma solidity ^0.4.21;
/*
* Creator: WGW (White Girl Wasted)
*/
/*
* Abstract Token Smart Contract
*
*/
/*
* Safe Math Smart Contract.
* https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
*/
contract SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function safeDiv(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 safeSub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* ERC-20 standard token interface, as defined
* <a href="http://github.com/ethereum/EIPs/issues/20">here</a>.
*/
contract Token {
function totalSupply() constant returns (uint256 supply);
function balanceOf(address _owner) constant returns (uint256 balance);
function transfer(address _to, uint256 _value) returns (bool success);
function transferFrom(address _from, address _to, uint256 _value) returns (bool success);
function approve(address _spender, uint256 _value) returns (bool success);
function allowance(address _owner, address _spender) constant returns (uint256 remaining);
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
}
/**
* Abstract Token Smart Contract that could be used as a base contract for
* ERC-20 token contracts.
*/
contract AbstractToken is Token, SafeMath {
/**
* Create new Abstract Token contract.
*/
function AbstractToken () {
// Do nothing
}
/**
* Get number of tokens currently belonging to given owner.
*
* @param _owner address to get number of tokens currently belonging to the
* owner of
* @return number of tokens currently belonging to the owner of given address
*/
function balanceOf(address _owner) constant returns (uint256 balance) {
return accounts [_owner];
}
/**
* Transfer given number of tokens from message sender to given recipient.
*
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
* accounts [_to] + _value > accounts [_to] for overflow check
* which is already in safeMath
*/
function transfer(address _to, uint256 _value) returns (bool success) {
require(_to != address(0));
if (accounts [msg.sender] < _value) return false;
if (_value > 0 && msg.sender != _to) {
accounts [msg.sender] = safeSub (accounts [msg.sender], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
Transfer (msg.sender, _to, _value);
return true;
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
* accounts [_to] + _value > accounts [_to] for overflow check
* which is already in safeMath
*/
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(_to != address(0));
if (allowances [_from][msg.sender] < _value) return false;
if (accounts [_from] < _value) return false;
if (_value > 0 && _from != _to) {
allowances [_from][msg.sender] = safeSub (allowances [_from][msg.sender], _value);
accounts [_from] = safeSub (accounts [_from], _value);
accounts [_to] = safeAdd (accounts [_to], _value);
}
Transfer(_from, _to, _value);
return true;
}
/**
* Allow given spender to transfer given number of tokens from message sender.
* @param _spender address to allow the owner of to transfer tokens from message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value) returns (bool success) {
allowances [msg.sender][_spender] = _value;
Approval (msg.sender, _spender, _value);
return true;
}
/**
* Tell how many tokens given spender is currently allowed to transfer from
* given owner.
*
* @param _owner address to get number of tokens allowed to be transferred
* from the owner of
* @param _spender address to get number of tokens allowed to be transferred
* by the owner of
* @return number of tokens given spender is currently allowed to transfer
* from given owner
*/
function allowance(address _owner, address _spender) constant
returns (uint256 remaining) {
return allowances [_owner][_spender];
}
/**
* Mapping from addresses of token holders to the numbers of tokens belonging
* to these token holders.
*/
mapping (address => uint256) accounts;
/**
* Mapping from addresses of token holders to the mapping of addresses of
* spenders to the allowances set by these token holders to these spenders.
*/
mapping (address => mapping (address => uint256)) private allowances;
}
/**
* White Girl Wasted token smart contract.
*/
contract WGWToken is AbstractToken {
/**
* Maximum allowed number of tokens in circulation.
* tokenSupply = tokensIActuallyWant * (10 ^ decimals)
*/
uint256 constant MAX_TOKEN_COUNT = 2150400000 * (10**18);
/**
* Address of the owner of this smart contract.
*/
address private owner;
/**
* Frozen account list holder
*/
mapping (address => bool) private frozenAccount;
/**
* Current number of tokens in circulation.
*/
uint256 tokenCount = 0;
/**
* True if tokens transfers are currently frozen, false otherwise.
*/
bool frozen = false;
/**
* Create new token smart contract and make msg.sender the
* owner of this smart contract.
*/
function WGWToken () {
owner = msg.sender;
}
/**
* Get total number of tokens in circulation.
*
* @return total number of tokens in circulation
*/
function totalSupply() constant returns (uint256 supply) {
return tokenCount;
}
string constant public name = "White Girl Wasted";
string constant public symbol = "WGW";
uint8 constant public decimals = 18;
/**
* Transfer given number of tokens from message sender to given recipient.
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer to the owner of given address
* @return true if tokens were transferred successfully, false otherwise
*/
function transfer(address _to, uint256 _value) returns (bool success) {
require(!frozenAccount[msg.sender]);
if (frozen) return false;
else return AbstractToken.transfer (_to, _value);
}
/**
* Transfer given number of tokens from given owner to given recipient.
*
* @param _from address to transfer tokens from the owner of
* @param _to address to transfer tokens to the owner of
* @param _value number of tokens to transfer from given owner to given
* recipient
* @return true if tokens were transferred successfully, false otherwise
*/
function transferFrom(address _from, address _to, uint256 _value)
returns (bool success) {
require(!frozenAccount[_from]);
if (frozen) return false;
else return AbstractToken.transferFrom (_from, _to, _value);
}
/**
* Change how many tokens given spender is allowed to transfer from message
* spender. In order to prevent double spending of allowance,
* 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
* @param _spender address to allow the owner of to transfer tokens from
* message sender
* @param _value number of tokens to allow to transfer
* @return true if token transfer was successfully approved, false otherwise
*/
function approve (address _spender, uint256 _value)
returns (bool success) {
require(allowance (msg.sender, _spender) == 0 || _value == 0);
return AbstractToken.approve (_spender, _value);
}
/**
* Create _value new tokens and give new created tokens to msg.sender.
* May only be called by smart contract owner.
*
* @param _value number of tokens to create
* @return true if tokens were created successfully, false otherwise
*/
function createTokens(uint256 _value)
returns (bool success) {
require (msg.sender == owner);
if (_value > 0) {
if (_value > safeSub (MAX_TOKEN_COUNT, tokenCount)) return false;
accounts [msg.sender] = safeAdd (accounts [msg.sender], _value);
tokenCount = safeAdd (tokenCount, _value);
// adding transfer event and _from address as null address
Transfer(0x0, msg.sender, _value);
return true;
}
return false;
}
/**
* Set new owner for the smart contract.
* May only be called by smart contract owner.
*
* @param _newOwner address of new owner of the smart contract
*/
function setOwner(address _newOwner) {
require (msg.sender == owner);
owner = _newOwner;
}
/**
* Freeze ALL token transfers.
* May only be called by smart contract owner.
*/
function freezeTransfers () {
require (msg.sender == owner);
if (!frozen) {
frozen = true;
Freeze ();
}
}
/**
* Unfreeze ALL token transfers.
* May only be called by smart contract owner.
*/
function unfreezeTransfers () {
require (msg.sender == owner);
if (frozen) {
frozen = false;
Unfreeze ();
}
}
/*A user is able to unintentionally send tokens to a contract
* and if the contract is not prepared to refund them they will get stuck in the contract.
* The same issue used to happen for Ether too but new Solidity versions added the payable modifier to
* prevent unintended Ether transfers. However, there’s no such mechanism for token transfers.
* so the below function is created
*/
function refundTokens(address _token, address _refund, uint256 _value) {
require (msg.sender == owner);
require(_token != address(this));
AbstractToken token = AbstractToken(_token);
token.transfer(_refund, _value);
RefundTokens(_token, _refund, _value);
}
/**
* Freeze specific account
* May only be called by smart contract owner.
*/
function freezeAccount(address _target, bool freeze) {
require (msg.sender == owner);
require (msg.sender != _target);
frozenAccount[_target] = freeze;
FrozenFunds(_target, freeze);
}
/**
* Logged when token transfers were frozen.
*/
event Freeze ();
/**
* Logged when token transfers were unfrozen.
*/
event Unfreeze ();
/**
* Logged when a particular account is frozen.
*/
event FrozenFunds(address target, bool frozen);
/**
* when accidentally send other tokens are refunded
*/
event RefundTokens(address _token, address _refund, uint256 _value);
} | Maximum allowed number of tokens in circulation. tokenSupply = tokensIActuallyWant (10 ^ decimals)/ Address of the owner of this smart contract./ Frozen account list holder/ Current number of tokens in circulation./ True if tokens transfers are currently frozen, false otherwise./ Create new token smart contract and make msg.sender the owner of this smart contract./ | function WGWToken () {
owner = msg.sender;
}
| 6,946,269 |
./partial_match/80001/0xa8Ce1F7dE0b2649B0190bB2B33A9c5112ca937C6/sources/Voting.sol | function to add multiple candidates to the main candidate array | function addCandidates(string[] memory _name, string[] memory _rollno, string[] memory _position, string[] memory _hostel, string[] memory _gender, string[] memory _cy) public onlyOwner{
for(uint256 i = 0; i < _name.length; i++)
{
addCandidate(_name[i], _rollno[i], _position[i], _hostel[i], _gender[i], _cy[i]);
}
}
| 8,821,427 |
pragma solidity ^0.6.7;
import "./ConsumesPriceReferenceXUA_CL.sol";
import "./ConsumesPriceReferenceETH_CL.sol";
contract Mooney {
string public constant name = "XXX";
string public constant symbol = "XXX";
uint8 public constant decimals = 18;
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Transfer(address indexed from, address indexed to, uint tokens);
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(uint => uint256[]) taxableThresholds;
uint256 totalSupply_;
address DAO_address;
//this will likely just be a delegate, maybe add this to the constructor as a delegate of the DAO
address liquidityGenAddress;
using SafeMath for uint256;
ConsumesPriceReferenceXUA_CL public PF;
ConsumesPriceReferenceETH_CL public PF2;
//Constructur takes arguement of total tokens
constructor() public {
totalSupply_ = 45000000000000000;
DAO_address = 0x7C717f804301fe6C51F4Ec8bae9BB653Ae558F63;
liquidityGenAddress = 0xD8bD4C443B0b96f4d7aE6035a247f200AF34FdA6;
//Assign initial token amount to the DAO
balances[msg.sender] = totalSupply_;
PF = new ConsumesPriceReferenceXUA_CL();
PF2 = new ConsumesPriceReferenceETH_CL();
//initiate simple tax structure
taxableThresholds[0] = [3000, 0];
taxableThresholds[1] = [5000, 200];
taxableThresholds[2] = [6000, 300];
taxableThresholds[3] = [7000, 400];
taxableThresholds[4] = [8000, 500];
taxableThresholds[5] = [0, 600];
}
function isContractOwner() public returns (bool) {
return msg.sender == DAO_address;
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function balanceOf(address tokenOwner) public view returns (uint) {
return balances[tokenOwner];
}
function transferTaxFree(address receiver, uint numTokens) public returns (bool) {
require(numTokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(numTokens);
balances[receiver] = balances[receiver].add(numTokens);
emit Transfer(msg.sender, receiver, numTokens);
return true;
}
function transfer(address receiver, uint256 numTokens) public returns (bool) {
require(numTokens <= balances[msg.sender]);
//where taxValues[0] is the primary transfer balance and taxValues[1] is the tax
uint256[] memory taxValues = determineTax(numTokens);
//primary transfer
balances[msg.sender] = balances[msg.sender].sub(taxValues[0]);
balances[receiver] = balances[receiver].add(taxValues[0]);
emit Transfer(msg.sender, receiver, taxValues[0]);
//tax transfer
balances[msg.sender] = balances[msg.sender].sub(taxValues[1]);
balances[DAO_address] = balances[DAO_address].add(taxValues[1]);
emit Transfer(msg.sender, DAO_address, taxValues[1]);
return true;
}
// this allows people to approve third parties to manage a percentage of their funds.
// The DAO (for example) could assign a portion of it's funds to a third party for management
function approve(address delegate, uint numTokens) public returns (bool) {
allowed[msg.sender][delegate] = numTokens;
emit Approval(msg.sender, delegate, numTokens);
return true;
}
// this returns the amount of your funds you allowed someone to delegate
function allowance(address owner, address delegate) public view returns (uint) {
return allowed[owner][delegate];
}
//this is transferFunction which is from a delegate and does not include a tax
function transferFrom(address owner, address buyer, uint256 numTokens) public returns (bool) {
require(numTokens <= balances[owner]);
require(numTokens <= allowed[owner][msg.sender]);
balances[owner] = balances[owner].sub(numTokens);
allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens);
balances[buyer] = balances[buyer].add(numTokens);
emit Transfer(owner, buyer, numTokens);
return true;
}
function determineTax(uint256 basis) public view returns (uint256[] memory){
uint256[] memory results = new uint256[](2);
if(basis < taxableThresholds[0][0]){
// no tax for our friends who are broke
results[0] = basis;
results[1] = 0;
return results;
}
if(basis < taxableThresholds[1][0]){
results[0] = basis.sub(taxableThresholds[1][1]);
results[1] = taxableThresholds[1][1];
return results;
}
if(basis < taxableThresholds[2][0]){
results[0] = basis.sub(taxableThresholds[2][1]);
results[1] = taxableThresholds[2][1];
return results;
}
if(basis < taxableThresholds[3][0]){
results[0] = basis.sub(taxableThresholds[3][1]);
results[1] = taxableThresholds[3][1];
return results;
}
if(basis < taxableThresholds[4][0]){
results[0] = basis.sub(taxableThresholds[4][1]);
results[1] = taxableThresholds[4][1];
return results;
}
// catches everything above the conditions above
results[0] = basis.sub(taxableThresholds[5][1]);
results[1] = taxableThresholds[5][1];
return results;
}
function updateTaxableThresholds(uint256 a,uint256 b,uint256 c) public returns(bool){
if(isContractOwner()){
taxableThresholds[a] = [b,c];
return true;
}
}
//function liquidityGenerationSale(){
//
//}
function getPriceOfXUA() public view returns (int256) {
return PF.getLatestPrice();
}
function getPriceOfETH() public view returns (int256) {
return PF2.getLatestPrice();
}
}
library SafeMath {
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;
}
}
1 eth = 1000000000000000000 wei
Assume target market cap of 30 million dollars for presale:
1000000000000000 / 30,000,000 = 33333333 Mooney = 1 dollar
assume chainlink api for ETH/USD price returns 256917152482...i.e.
1000000000000000000 / (chainlinkValue / 10^8) = 1 wei to dollar
which means...
383499241784770 wei = one dollar
----------------------------------------------------------------------
so with an incoming transaction of .5 ETH (500000000000000000 wei)
(1000000000000000 / 30,000,0000) x (1000000000000000 / 30,000,0000)
500000000000000000 /*383499241784770* = value of incoming ETH in dollars
...multiplied by...
1000000000000000 (market cap) / 30,000,000 = 33333333 Mooney
33333333 X 1303 = 43,433,332,899
one quadrillion
1000000000000000000000000000000000
kovan address
0x9326BFA02ADD2366b30bacB125260Af641031331
wei
1000000000000000000
pragma solidity ^0.6.7;
import "./ConsumesPriceReferenceETH_CL.sol";
contract PrePurchaseMooney {
address owner;
uint256 prePurchaseTargetMarketCap_;
uint256 totalSupply_;
mapping(address => uint256) prePurcahseBalances;
using SafeMath for uint256;
ConsumesPriceReferenceETH_CL public PF2;
//Constructur takes arguement of total tokens
constructor(uint256 startingBalance) public {
totalSupply_ = startingBalance;
prePurchaseTargetMarketCap_ = 500000000;
owner = msg.sender;
PF2 = new ConsumesPriceReferenceETH_CL();
}
function getContractOwner() public returns (address) {
return owner;
}
function isContractOwner(address potentialOwner) public returns (bool) {
return potentialOwner == owner;
}
function balanceOf(address tokenOwner) public view returns (uint) {
return prePurcahseBalances[tokenOwner];
}
function subtractPrePurchaseBalanceOf(address tokenOwner, uint256 numTokens) public returns (uint) {
require(isContractOwner(msg.sender));
prePurcahseBalances[tokenOwner] = prePurcahseBalances[msg.sender].sub(numTokens);
return prePurcahseBalances[tokenOwner];
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function getCurrentPrePurchaseTargetMarketCap() public view returns (uint256) {
return prePurchaseTargetMarketCap_;
}
function setCurrentPrePurchaseTargetMarketCap(uint256 newTargetMC) public returns (uint256) {
require(isContractOwner(msg.sender));
prePurchaseTargetMarketCap_ = newTargetMC;
return prePurchaseTargetMarketCap_;
}
function getPriceOfETH() public view returns (uint256) {
return uint256(PF2.getLatestPrice());
}
function getNumberOfWeiInDollar() public view returns (uint256) {
uint256 weiBase = 1000000000000000000;
return weiBase.div(getPriceOfETH().div(100000000));
}
function getUserEthBalance() public payable returns (uint256) {
return msg.sender.balance;
}
function prepurchaseEthNetwork(address receiver, uint256 numTokens) public payable returns (bool) {
require(numTokens <= msg.sender.balance);
require(prePurchaseTargetMarketCap_ != 0);
uint256 numWeiInDollar = getNumberOfWeiInDollar();
// minimum purchase is 5 dollars
require(numTokens <= numWeiInDollar.mul(5));
uint256 pricePerToken = totalSupply_.div(prePurchaseTargetMarketCap_);
uint256 pricePerWei = numTokens.div(numWeiInDollar);
uint256 awardedTokens = pricePerWei.mul(pricePerToken);
payable(owner).transfer(numTokens);
prePurcahseBalances[msg.sender] = prePurcahseBalances[msg.sender].add(numTokens);
return true;
}
}
library SafeMath {
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;
}
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) {
uint256 c = a / b;
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.7;
import "./ConsumesPriceReferenceETH_CL.sol";
contract PrePurchaseMooney {
address owner;
uint256 prePurchaseTargetMarketCap_;
uint256 totalSupply_;
mapping(address => uint256) prePurcahseBalances;
using SafeMath for uint256;
ConsumesPriceReferenceETH_CL public PF2;
//Constructur takes arguement of total tokens
constructor(uint256 startingBalance) public {
totalSupply_ = startingBalance;
prePurchaseTargetMarketCap_ = 500000000;
owner = msg.sender;
PF2 = new ConsumesPriceReferenceETH_CL();
}
function getContractOwner() public view returns (address) {
return owner;
}
function isContractOwner(address potentialOwner) public view returns (bool) {
return potentialOwner == owner;
}
function balanceOf(address tokenOwner) public view returns (uint) {
return prePurcahseBalances[tokenOwner];
}
function subtractPrePurchaseBalanceOf(address tokenOwner, uint256 numTokens) public returns (uint) {
require(isContractOwner(msg.sender));
prePurcahseBalances[tokenOwner] = prePurcahseBalances[msg.sender].sub(numTokens);
return prePurcahseBalances[tokenOwner];
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function getCurrentPrePurchaseTargetMarketCap() public view returns (uint256) {
return prePurchaseTargetMarketCap_;
}
function setCurrentPrePurchaseTargetMarketCap(uint256 newTargetMC) public returns (uint256) {
require(isContractOwner(msg.sender));
prePurchaseTargetMarketCap_ = newTargetMC;
return prePurchaseTargetMarketCap_;
}
function getPriceOfETH() public view returns (uint256) {
return uint256(PF2.getLatestPrice());
}
function getNumberOfWeiInDollar() public view returns (uint256) {
uint256 weiBase = 1000000000000000000;
return weiBase.div(getPriceOfETH().div(100000000));
}
function getUserEthBalance() public payable returns (uint256) {
return msg.sender.balance;
}
function prePurchaseOnEthNetwork(address receiver, uint256 numTokens) public payable returns (bool) {
require(receiver == msg.sender);
require(numTokens <= msg.sender.balance);
require(prePurchaseTargetMarketCap_ != 0);
uint256 numWeiInDollar = getNumberOfWeiInDollar();
// minimum purchase is 5 dollars
require(numTokens <= numWeiInDollar.mul(5));
uint256 pricePerToken = totalSupply_.div(prePurchaseTargetMarketCap_);
uint256 pricePerWei = numTokens.div(numWeiInDollar);
uint256 awardedTokens = pricePerWei.mul(pricePerToken);
payable(owner).transfer(numTokens);
prePurcahseBalances[msg.sender] = prePurcahseBalances[msg.sender].add(awardedTokens);
return true;
}
}
library SafeMath {
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;
}
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) {
uint256 c = a / b;
return c;
}
}
**********newwejsdfkshjdkjfhsdkj bew wbeew
pragma solidity ^0.6.7;
import "./ConsumesPriceReferenceETH_CL.sol";
contract Mooney {
string public constant name = "XXX";
string public constant symbol = "XXX";
uint8 public constant decimals = 18;
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Transfer(address indexed from, address indexed to, uint tokens);
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(uint => uint256[]) taxableThresholds;
uint256 totalSupply_;
uint256 prePurchaseTargetMarketCap_;
address DAO_address;
address BURN_address;
//this will likely just be a delegate, maybe add this to the constructor as a delegate of the DAO
address liquidityGenAddress;
using SafeMath for uint256;
ConsumesPriceReferenceETH_CL public PF2;
//Constructur takes arguement of total tokens
constructor(uint256 startingBalance) public {
totalSupply_ = startingBalance;
prePurchaseTargetMarketCap_ = 500000000;
DAO_address = msg.sender;
BURN_address = 0x000000000000000000000000000000000000dEaD;
liquidityGenAddress = 0xD8bD4C443B0b96f4d7aE6035a247f200AF34FdA6;
//Assign initial token amount to the DAO
balances[msg.sender] = totalSupply_;
PF2 = new ConsumesPriceReferenceETH_CL();
//initiate simple tax structure
taxableThresholds[0] = [3000, 0, 3, 0, 0, 0];
taxableThresholds[1] = [5000, 1, 3, 0, 0, 0];
taxableThresholds[2] = [6000, 1, 3, 0, 0, 0];
taxableThresholds[3] = [7000, 1, 3, 0, 0, 0];
taxableThresholds[4] = [800000000, 1, 3, 0, 0, 0];
taxableThresholds[5] = [0, 2, 6, 0, 0, 0];
}
function getContractOwner() public returns (address) {
return DAO_address;
}
function isContractOwner(address potentialOwner) public returns (bool) {
return potentialOwner == DAO_address;
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function getCurrentPrePurchaseTargetMarketCap() public view returns (uint256) {
return prePurchaseTargetMarketCap_;
}
function setCurrentPrePurchaseTargetMarketCap(uint256 newTargetMC) public returns (uint256) {
prePurchaseTargetMarketCap_ = newTargetMC;
return prePurchaseTargetMarketCap_;
}
function balanceOf(address tokenOwner) public view returns (uint) {
return balances[tokenOwner];
}
function transferTaxFree(address receiver, uint numTokens) public returns (bool) {
require(isContractOwner(msg.sender));
require(numTokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(numTokens);
balances[receiver] = balances[receiver].add(numTokens);
emit Transfer(msg.sender, receiver, numTokens);
return true;
}
function transfer(address receiver, uint256 numTokens) public returns (bool) {
require(numTokens <= balances[msg.sender]);
//where taxValues[0] is the primary transfer balance and taxValues[1] is the tax
uint256[] memory taxValues = determineTax(numTokens);
//primary transfer
balances[msg.sender] = balances[msg.sender].sub(taxValues[0]);
balances[receiver] = balances[receiver].add(taxValues[0]);
emit Transfer(msg.sender, receiver, taxValues[0]);
//tax transfer DAO
balances[msg.sender] = balances[msg.sender].sub(taxValues[1]);
balances[DAO_address] = balances[DAO_address].add(taxValues[1]);
emit Transfer(msg.sender, DAO_address, taxValues[1]);
//tax transfer Burn
balances[msg.sender] = balances[msg.sender].sub(taxValues[2]);
balances[BURN_address] = balances[BURN_address].add(taxValues[2]);
emit Transfer(msg.sender, DAO_address, taxValues[2]);
return true;
}
// this allows people to approve third parties to manage a percentage of their funds.
// The DAO (for example) could assign a portion of it's funds to a third party for management
function approve(address delegate, uint numTokens) public returns (bool) {
require(isContractOwner(msg.sender));
allowed[msg.sender][delegate] = numTokens;
emit Approval(msg.sender, delegate, numTokens);
return true;
}
// this returns the amount of your funds you allowed someone to delegate
function allowance(address owner, address delegate) public view returns (uint) {
return allowed[owner][delegate];
}
//this is transferFunction which is from a delegate and does not include a tax
function transferFrom(address owner, address buyer, uint256 numTokens) public returns (bool) {
require(numTokens <= balances[owner]);
require(numTokens <= allowed[owner][msg.sender]);
balances[owner] = balances[owner].sub(numTokens);
allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens);
balances[buyer] = balances[buyer].add(numTokens);
emit Transfer(owner, buyer, numTokens);
return true;
}
function getTaxFee(uint256 amount, uint256 tax) public pure returns (uint256) {
return amount.mul(tax.div(10**2));
}
function determineTax(uint256 basis) public view returns (uint256[] memory){
uint256[] memory results = new uint256[](4);
if (basis < taxableThresholds[0][0]){
// no tax for our friends who are broke
results[1] = 0;
if (taxableThresholds[0][5] == 1) {
// fixed fee
results[2] = taxableThresholds[0][4];
} else {
// dynamic fee
results[2] = getTaxFee(taxableThresholds[0][2], basis);
}
results[0] = basis.sub(results[2]);
return results;
}
if (basis < taxableThresholds[1][0]){
if (taxableThresholds[1][5] == 1) {
// fixed fee
results[1] = taxableThresholds[1][3];
results[2] = taxableThresholds[1][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[1][1], basis);
results[2] = getTaxFee(taxableThresholds[1][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
if (basis < taxableThresholds[2][0]){
if (taxableThresholds[2][5] == 1) {
// fixed fee
results[1] = taxableThresholds[2][3];
results[2] = taxableThresholds[2][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[2][1], basis);
results[2] = getTaxFee(taxableThresholds[2][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
if (basis < taxableThresholds[3][0]){
if (taxableThresholds[3][5] == 1) {
// fixed fee
results[1] = taxableThresholds[3][3];
results[2] = taxableThresholds[3][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[3][1], basis);
results[2] = getTaxFee(taxableThresholds[3][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
if (basis < taxableThresholds[4][0]){
if (taxableThresholds[4][5] == 1) {
// fixed fee
results[1] = taxableThresholds[4][3];
results[2] = taxableThresholds[4][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[4][1], basis);
results[2] = getTaxFee(taxableThresholds[4][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
// catches everything above the conditions above
if (taxableThresholds[5][5] == 1) {
// fixed fee
results[1] = taxableThresholds[5][3];
results[2] = taxableThresholds[5][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[5][1], basis);
results[2] = getTaxFee(taxableThresholds[5][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
function updateTaxableThresholdsAtIndex(uint256 indexToMod, uint256 thresHoldFixed, uint256 taxPerc, uint256 burnPerc, uint256 taxFixed, uint256 burnFixed, uint256 isFixed) public payable returns(bool){
if(isContractOwner(msg.sender)){
taxableThresholds[indexToMod] = [thresHoldFixed, taxPerc, burnPerc, taxFixed, burnFixed, isFixed];
return true;
}
}
function getPriceOfETH() public view returns (uint256) {
return uint256(PF2.getLatestPrice());
}
function getNumberOfWeiInDollar() public view returns (uint256) {
uint256 weiBase = 1000000000000000000;
return weiBase.div(getPriceOfETH().div(100000000));
}
function getUserEthBalance() public payable returns (uint256) {
return msg.sender.balance;
}
function prepurchaseEthNetwork(address receiver, uint256 numTokens) public payable returns (bool) {
require(numTokens <= msg.sender.balance);
uint256 numWeiInDollar = getNumberOfWeiInDollar();
// minimum purchase is 5 dollars
require(numTokens <= numWeiInDollar.mul(5));
uint256 pricePerToken = totalSupply_.div(prePurchaseTargetMarketCap_);
uint256 pricePerWei = msg.value.div(numWeiInDollar);
uint256 awardedTokens = pricePerWei.mul(pricePerToken);
payable(owner).transfer(msg.value);
//where taxValues[0] is the primary transfer balance and taxValues[1] is the tax
uint256[] memory taxValues = determineTax(numTokens);
//primary transfer
balances[msg.sender] = balances[msg.sender].sub(taxValues[0]);
balances[receiver] = balances[receiver].add(taxValues[0]);
emit Transfer(msg.sender, receiver, taxValues[0]);
//tax transfer DAO
balances[msg.sender] = balances[msg.sender].sub(taxValues[1]);
balances[DAO_address] = balances[DAO_address].add(taxValues[1]);
emit Transfer(msg.sender, DAO_address, taxValues[1]);
//tax transfer Burn
balances[msg.sender] = balances[msg.sender].sub(taxValues[2]);
balances[BURN_address] = balances[BURN_address].add(taxValues[2]);
emit Transfer(msg.sender, DAO_address, taxValues[2]);
return true;
}
}
library SafeMath {
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;
}
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) {
uint256 c = a / b;
return c;
}
}
!!!!
5000000000000000 this amount will transfer!
goood prepurchase
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.7;
import "./ConsumesPriceReferenceETH_CL.sol";
contract PrePurchaseMooney {
address ownerX;
uint256 prePurchaseTargetMarketCap_;
uint256 totalSupply_;
mapping(address => uint256) prePurchaseBalances;
using SafeMath2 for uint256;
event Recieved(address indexed sender, uint256 msgVal, address indexed ownerX);
//emit Recieved(msg.sender, msg.value, owner, numWeiInDollar, pricePerToken, pricePerWei, awardedTokens);
ConsumesPriceReferenceETH_CL public PF2;
//Constructur takes arguement of total tokens
constructor(uint256 startingBalance, address chainLinkAggregatorAddress) public {
totalSupply_ = startingBalance;
prePurchaseTargetMarketCap_ = 350000000;
ownerX = msg.sender;
PF2 = new ConsumesPriceReferenceETH_CL(chainLinkAggregatorAddress);
}
function getContractOwner() public view returns (address) {
return ownerX;
}
function isContractOwner(address potentialOwner) public view returns (bool) {
return potentialOwner == ownerX;
}
function balanceOf(address tokenOwner) public view returns (uint) {
return prePurchaseBalances[tokenOwner];
}
function addPrePurchaseBalanceOf(address tokenOwner, uint256 numTokens) public returns (uint) {
require(isContractOwner(msg.sender));
prePurchaseBalances[tokenOwner] = prePurchaseBalances[msg.sender].add(numTokens);
return prePurchaseBalances[tokenOwner];
}
function subtractPrePurchaseBalanceOf(address tokenOwner, uint256 numTokens) public returns (uint) {
require(isContractOwner(msg.sender));
prePurchaseBalances[tokenOwner] = prePurchaseBalances[msg.sender].sub(numTokens);
return prePurchaseBalances[tokenOwner];
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function setTotalSupply(uint256 newTargetTS) public returns (uint256) {
require(isContractOwner(msg.sender));
totalSupply_ = newTargetTS;
return totalSupply_;
}
function getCurrentPrePurchaseTargetMarketCap() public view returns (uint256) {
return prePurchaseTargetMarketCap_;
}
function setCurrentPrePurchaseTargetMarketCap(uint256 newTargetMC) public returns (uint256) {
require(isContractOwner(msg.sender));
prePurchaseTargetMarketCap_ = newTargetMC;
return prePurchaseTargetMarketCap_;
}
function getUserEthBalance() public view returns (uint256) {
return msg.sender.balance;
}
function prePurchaseOnEthNetwork(address receiver, uint256 numTokens) public payable returns (uint256) {
require(numTokens <= msg.sender.balance);
require(prePurchaseTargetMarketCap_ != 0);
// minimum purchase is 5 dollars
//require(numTokens <= numWeiInDollar.mul(5));
uint256 awardedTokens = PF2.calculateTokensBack(msg.value, prePurchaseTargetMarketCap_, totalSupply_);
payable(ownerX).transfer(awardedTokens);
emit Recieved(msg.sender, msg.value, ownerX);
prePurchaseBalances[msg.sender] = prePurchaseBalances[msg.sender].add(awardedTokens);
return awardedTokens;
}
}
library SafeMath2 {
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;
}
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) {
uint256 c = a / b;
return c;
}
}
good consumes price
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.7;
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorInterface.sol";
contract ConsumesPriceReferenceETH_CL {
AggregatorInterface internal priceFeed;
event Calculated(uint256 numWeiInDollar, uint256 pricePerToken, uint256 pricePerWei, uint256 Awardedtokens);
using SafeMath for uint256;
/**
* Network: Kovan
* Aggregator: ETH/USD
* Address: 0x9326BFA02ADD2366b30bacB125260Af641031331
*/
constructor(address AggregatorInterfaceAddress) public {
priceFeed = AggregatorInterface(AggregatorInterfaceAddress);
}
/**
* Returns the latest price
*/
function getLatestPrice() public view returns (int256) {
return priceFeed.latestAnswer();
}
/**
* Returns the timestamp of the latest price update
*/
function getLatestPriceTimestamp() public view returns (uint256) {
return priceFeed.latestTimestamp();
}
function getPriceOfETH() private view returns (uint256) {
return uint256(getLatestPrice());
}
function getNumberOfWeiInDollar() public view returns (uint256) {
uint256 weiBase = 1000000000000000000;
return weiBase.div(getPriceOfETH().div(100000000));
}
function calculateTokensBack(uint256 ethIn, uint256 prePurchaseTargetMarketCap,uint256 totalSupply) public returns (uint256) {
uint256 numWeiInDollar = getNumberOfWeiInDollar();
uint256 pricePerToken = totalSupply.div(prePurchaseTargetMarketCap);
uint256 pricePerWei = ethIn.div(numWeiInDollar);
uint256 awardedTokens = pricePerWei.mul(pricePerToken);
emit Calculated(numWeiInDollar, pricePerToken, pricePerWei, awardedTokens);
return awardedTokens;
}
}
library SafeMath {
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;
}
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) {
uint256 c = a / b;
return c;
}
}
pragma solidity ^0.6.7;
import "./ConsumesPriceReferenceETH_CL.sol";
contract Mooney {
string public constant name = "XXX";
string public constant symbol = "XXX";
uint8 public constant decimals = 18;
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Transfer(address indexed from, address indexed to, uint tokens);
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(uint => uint256[]) taxableThresholds;
uint256 totalSupply_;
uint256 prePurchaseTargetMarketCap_;
address DAO_address;
address BURN_address;
//this will likely just be a delegate, maybe add this to the constructor as a delegate of the DAO
address liquidityGenAddress;
using SafeMath2 for uint256;
ConsumesPriceReferenceETH_CL public PF2;
//Constructur takes arguement of total tokens
constructor(uint256 startingBalance) public {
totalSupply_ = startingBalance;
prePurchaseTargetMarketCap_ = 500000000;
DAO_address = msg.sender;
BURN_address = 0x000000000000000000000000000000000000dEaD;
liquidityGenAddress = 0xD8bD4C443B0b96f4d7aE6035a247f200AF34FdA6;
//Assign initial token amount to the DAO
balances[msg.sender] = totalSupply_;
PF2 = new ConsumesPriceReferenceETH_CL();
//initiate simple tax structure
taxableThresholds[0] = [3000, 0, 3, 0, 0, 0];
taxableThresholds[1] = [5000, 1, 3, 0, 0, 0];
taxableThresholds[2] = [6000, 1, 3, 0, 0, 0];
taxableThresholds[3] = [7000, 1, 3, 0, 0, 0];
taxableThresholds[4] = [800000000, 1, 3, 0, 0, 0];
taxableThresholds[5] = [0, 2, 6, 0, 0, 0];
}
function getContractOwner() public returns (address) {
return DAO_address;
}
function isContractOwner(address potentialOwner) public returns (bool) {
return potentialOwner == DAO_address;
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function getCurrentPrePurchaseTargetMarketCap() public view returns (uint256) {
return prePurchaseTargetMarketCap_;
}
function setCurrentPrePurchaseTargetMarketCap(uint256 newTargetMC) public returns (uint256) {
prePurchaseTargetMarketCap_ = newTargetMC;
return prePurchaseTargetMarketCap_;
}
function balanceOf(address tokenOwner) public view returns (uint) {
return balances[tokenOwner];
}
function transferTaxFree(address receiver, uint numTokens) public returns (bool) {
require(isContractOwner(msg.sender));
require(numTokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(numTokens);
balances[receiver] = balances[receiver].add(numTokens);
emit Transfer(msg.sender, receiver, numTokens);
return true;
}
function transfer(address receiver, uint256 numTokens) public returns (bool) {
require(numTokens <= balances[msg.sender]);
//where taxValues[0] is the primary transfer balance and taxValues[1] is the tax
uint256[] memory taxValues = determineTax(numTokens);
//primary transfer
balances[msg.sender] = balances[msg.sender].sub(taxValues[0]);
balances[receiver] = balances[receiver].add(taxValues[0]);
emit Transfer(msg.sender, receiver, taxValues[0]);
//tax transfer DAO
balances[msg.sender] = balances[msg.sender].sub(taxValues[1]);
balances[DAO_address] = balances[DAO_address].add(taxValues[1]);
emit Transfer(msg.sender, DAO_address, taxValues[1]);
//tax transfer Burn
balances[msg.sender] = balances[msg.sender].sub(taxValues[2]);
balances[BURN_address] = balances[BURN_address].add(taxValues[2]);
emit Transfer(msg.sender, DAO_address, taxValues[2]);
return true;
}
// this allows people to approve third parties to manage a percentage of their funds.
// The DAO (for example) could assign a portion of it's funds to a third party for management
function approve(address delegate, uint numTokens) public returns (bool) {
require(isContractOwner(msg.sender));
allowed[msg.sender][delegate] = numTokens;
emit Approval(msg.sender, delegate, numTokens);
return true;
}
// this returns the amount of your funds you allowed someone to delegate
function allowance(address owner, address delegate) public view returns (uint) {
return allowed[owner][delegate];
}
//this is transferFunction which is from a delegate and does not include a tax
function transferFrom(address owner, address buyer, uint256 numTokens) public returns (bool) {
require(numTokens <= balances[owner]);
require(numTokens <= allowed[owner][msg.sender]);
balances[owner] = balances[owner].sub(numTokens);
allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens);
balances[buyer] = balances[buyer].add(numTokens);
emit Transfer(owner, buyer, numTokens);
return true;
}
function getTaxFee(uint256 amount, uint256 tax) public pure returns (uint256) {
return amount.mul(tax.div(10**2));
}
function determineTax(uint256 basis) public view returns (uint256[] memory){
uint256[] memory results = new uint256[](4);
if (basis < taxableThresholds[0][0]){
// no tax for our friends who are broke
results[1] = 0;
if (taxableThresholds[0][5] == 1) {
// fixed fee
results[2] = taxableThresholds[0][4];
} else {
// dynamic fee
results[2] = getTaxFee(taxableThresholds[0][2], basis);
}
results[0] = basis.sub(results[2]);
return results;
}
if (basis < taxableThresholds[1][0]){
if (taxableThresholds[1][5] == 1) {
// fixed fee
results[1] = taxableThresholds[1][3];
results[2] = taxableThresholds[1][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[1][1], basis);
results[2] = getTaxFee(taxableThresholds[1][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
if (basis < taxableThresholds[2][0]){
if (taxableThresholds[2][5] == 1) {
// fixed fee
results[1] = taxableThresholds[2][3];
results[2] = taxableThresholds[2][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[2][1], basis);
results[2] = getTaxFee(taxableThresholds[2][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
if (basis < taxableThresholds[3][0]){
if (taxableThresholds[3][5] == 1) {
// fixed fee
results[1] = taxableThresholds[3][3];
results[2] = taxableThresholds[3][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[3][1], basis);
results[2] = getTaxFee(taxableThresholds[3][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
if (basis < taxableThresholds[4][0]){
if (taxableThresholds[4][5] == 1) {
// fixed fee
results[1] = taxableThresholds[4][3];
results[2] = taxableThresholds[4][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[4][1], basis);
results[2] = getTaxFee(taxableThresholds[4][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
// catches everything above the conditions above
if (taxableThresholds[5][5] == 1) {
// fixed fee
results[1] = taxableThresholds[5][3];
results[2] = taxableThresholds[5][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[5][1], basis);
results[2] = getTaxFee(taxableThresholds[5][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
function updateTaxableThresholdsAtIndex(uint256 indexToMod, uint256 thresHoldFixed, uint256 taxPerc, uint256 burnPerc, uint256 taxFixed, uint256 burnFixed, uint256 isFixed) public payable returns(bool){
if(isContractOwner(msg.sender)){
taxableThresholds[indexToMod] = [thresHoldFixed, taxPerc, burnPerc, taxFixed, burnFixed, isFixed];
return true;
}
}
function getPriceOfETH() public view returns (uint256) {
return uint256(PF2.getLatestPrice());
}
function getNumberOfWeiInDollar() public view returns (uint256) {
uint256 weiBase = 1000000000000000000;
return weiBase.div(getPriceOfETH().div(100000000));
}
function getUserEthBalance() public payable returns (uint256) {
return msg.sender.balance;
}
function prepurchaseEthNetwork(address receiver, uint256 numTokens) public payable returns (bool) {
require(numTokens <= msg.sender.balance);
uint256 numWeiInDollar = getNumberOfWeiInDollar();
// minimum purchase is 5 dollars
require(numTokens <= numWeiInDollar.mul(5));
uint256 pricePerToken = totalSupply_.div(prePurchaseTargetMarketCap_);
uint256 pricePerWei = msg.value.div(numWeiInDollar);
uint256 awardedTokens = pricePerWei.mul(pricePerToken);
payable(owner).transfer(msg.value);
//where taxValues[0] is the primary transfer balance and taxValues[1] is the tax
uint256[] memory taxValues = determineTax(numTokens);
//primary transfer
balances[msg.sender] = balances[msg.sender].sub(taxValues[0]);
balances[receiver] = balances[receiver].add(taxValues[0]);
emit Transfer(msg.sender, receiver, taxValues[0]);
//tax transfer DAO
balances[msg.sender] = balances[msg.sender].sub(taxValues[1]);
balances[DAO_address] = balances[DAO_address].add(taxValues[1]);
emit Transfer(msg.sender, DAO_address, taxValues[1]);
//tax transfer Burn
balances[msg.sender] = balances[msg.sender].sub(taxValues[2]);
balances[BURN_address] = balances[BURN_address].add(taxValues[2]);
emit Transfer(msg.sender, DAO_address, taxValues[2]);
return true;
}
}
library SafeMath2 {
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;
}
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) {
uint256 c = a / b;
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.7;
import "./ConsumesPriceReferenceETH_CL.sol";
contract PrePurchaseMooney {
address liquidityGenAddress;
uint256 prePurchaseTargetMarketCap_;
uint256 totalSupply_;
mapping(address => uint256) prePurchaseBalances;
using SafeMath2 for uint256;
event Recieved(address indexed sender, uint256 msgVal, address indexed liquidityGenAddress);
//emit Recieved(msg.sender, msg.value, owner, numWeiInDollar, pricePerToken, pricePerWei, awardedTokens);
ConsumesPriceReferenceETH_CL public PF2;
//Constructur takes arguement of total tokens
constructor(uint256 startingBalance, address chainLinkAggregatorAddress) public {
totalSupply_ = startingBalance;
prePurchaseTargetMarketCap_ = 350000000;
//should be liquidityGenAddress -> 0xD8bD4C443B0b96f4d7aE6035a247f200AF34FdA6
liquidityGenAddress = msg.sender;
PF2 = new ConsumesPriceReferenceETH_CL(chainLinkAggregatorAddress);
}
function getContractOwner() public view returns (address) {
return liquidityGenAddress;
}
function isContractOwner(address potentialOwner) public view returns (bool) {
return potentialOwner == liquidityGenAddress;
}
function balanceOf(address tokenOwner) public view returns (uint) {
return prePurchaseBalances[tokenOwner];
}
function addPrePurchaseBalanceOf(address tokenOwner, uint256 numTokens) public returns (uint) {
require(isContractOwner(msg.sender));
prePurchaseBalances[tokenOwner] = prePurchaseBalances[msg.sender].add(numTokens);
return prePurchaseBalances[tokenOwner];
}
function subtractPrePurchaseBalanceOf(address tokenOwner, uint256 numTokens) public returns (uint) {
require(isContractOwner(msg.sender));
prePurchaseBalances[tokenOwner] = prePurchaseBalances[msg.sender].sub(numTokens);
return prePurchaseBalances[tokenOwner];
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function setTotalSupply(uint256 newTargetTS) public returns (uint256) {
require(isContractOwner(msg.sender));
totalSupply_ = newTargetTS;
return totalSupply_;
}
function getCurrentPrePurchaseTargetMarketCap() public view returns (uint256) {
return prePurchaseTargetMarketCap_;
}
function setCurrentPrePurchaseTargetMarketCap(uint256 newTargetMC) public returns (uint256) {
require(isContractOwner(msg.sender));
prePurchaseTargetMarketCap_ = newTargetMC;
return prePurchaseTargetMarketCap_;
}
function getUserEthBalance() public view returns (uint256) {
return msg.sender.balance;
}
function prePurchaseOnEthNetwork(address receiver, uint256 numTokens) public payable returns (uint256) {
require(numTokens <= msg.sender.balance);
require(prePurchaseTargetMarketCap_ != 0);
// minimum purchase is 5 dollars
//require(numTokens <= numWeiInDollar.mul(5));
uint256 awardedTokens = PF2.calculateTokensBack(msg.value, prePurchaseTargetMarketCap_, totalSupply_);
//this is the eth balance recieved...
payable(liquidityGenAddress).transfer(msg.value);
emit Recieved(msg.sender, msg.value, liquidityGenAddress);
prePurchaseBalances[msg.sender] = prePurchaseBalances[msg.sender].add(awardedTokens);
return awardedTokens;
}
}
library SafeMath2 {
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;
}
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) {
uint256 c = a / b;
return c;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.7;
import "@chainlink/contracts/src/v0.6/interfaces/AggregatorInterface.sol";
contract ConsumesPriceReferenceETH_CL {
AggregatorInterface internal priceFeed;
event Calculated(uint256 numWeiInDollar, uint256 pricePerToken, uint256 pricePerWei, uint256 Awardedtokens);
using SafeMath for uint256;
/**
* Network: Kovan
* Aggregator: ETH/USD
* Address: 0x9326BFA02ADD2366b30bacB125260Af641031331
*/
constructor(address AggregatorInterfaceAddress) public {
priceFeed = AggregatorInterface(AggregatorInterfaceAddress);
}
/**
* Returns the latest price
*/
function getLatestPrice() public view returns (int256) {
return priceFeed.latestAnswer();
}
/**
* Returns the timestamp of the latest price update
*/
function getLatestPriceTimestamp() public view returns (uint256) {
return priceFeed.latestTimestamp();
}
function getPriceOfETH() private view returns (uint256) {
return uint256(getLatestPrice());
}
function getNumberOfWeiInDollar() public view returns (uint256) {
uint256 weiBase = 1000000000000000000;
return weiBase.div(getPriceOfETH().div(100000000));
}
function calculateTokensBack(uint256 ethIn, uint256 prePurchaseTargetMarketCap,uint256 totalSupply) public returns (uint256) {
uint256 numWeiInDollar = getNumberOfWeiInDollar();
uint256 pricePerToken = totalSupply.div(prePurchaseTargetMarketCap);
uint256 pricePerWei = ethIn.div(numWeiInDollar);
uint256 awardedTokens = pricePerWei.mul(pricePerToken);
emit Calculated(numWeiInDollar, pricePerToken, pricePerWei, awardedTokens);
return awardedTokens;
}
}
library SafeMath {
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;
}
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) {
uint256 c = a / b;
return c;
}
}
pragma solidity ^0.6.7;
import "./ConsumesPriceReferenceETH_CL.sol";
contract Mooney {
string public constant name = "XXX";
string public constant symbol = "XXX";
uint8 public constant decimals = 18;
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
event Transfer(address indexed from, address indexed to, uint tokens);
event Recieved(address indexed sender, uint256 msgVal, address indexed DAO_address);
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
mapping(uint => uint256[]) taxableThresholds;
uint256 totalSupply_;
uint256 prePurchaseTargetMarketCap_;
bool defaultBurnOnTransaction_;
address DAO_address;
address BURN_address;
//this will likely just be a delegate, maybe add this to the constructor as a delegate of the DAO
address liquidityGenAddress;
using SafeMath2 for uint256;
ConsumesPriceReferenceETH_CL public PF2;
//Constructur takes arguement of total tokens
//bsc testnet should be 0x2514895c72f50D8bd4B4F9b1110F0D6bD2c97526
constructor(uint256 startingBalance, address chainLinkAggregatorAddress) public {
totalSupply_ = startingBalance;
prePurchaseTargetMarketCap_ = 500000000;
DAO_address = msg.sender;
BURN_address = 0x000000000000000000000000000000000000dEaD;
liquidityGenAddress = 0xD8bD4C443B0b96f4d7aE6035a247f200AF34FdA6;
defaultBurnOnTransaction_ = true;
//Assign initial token amount to the DAO
balances[msg.sender] = totalSupply_;
PF2 = new ConsumesPriceReferenceETH_CL(chainLinkAggregatorAddress);
//initiate simple tax structure
taxableThresholds[0] = [3000, 0, 3, 0, 0, 0];
taxableThresholds[1] = [5000, 1, 3, 0, 0, 0];
taxableThresholds[2] = [6000, 1, 3, 0, 0, 0];
taxableThresholds[3] = [7000, 1, 3, 0, 0, 0];
taxableThresholds[4] = [800000000, 1, 3, 0, 0, 0];
taxableThresholds[5] = [0, 2, 6, 0, 0, 0];
}
function getContractOwner() public returns (address) {
return DAO_address;
}
function isContractOwner(address potentialOwner) public returns (bool) {
return potentialOwner == DAO_address;
}
function isLiquidityContractOwner(address potentialOwner) public returns (bool) {
return potentialOwner == liquidityGenAddress;
}
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
function getCurrentPrePurchaseTargetMarketCap() public view returns (uint256) {
return prePurchaseTargetMarketCap_;
}
function setAmountToMint(uint256 amountToMint) public returns (uint256) {
require(isLiquidityContractOwner(msg.sender));
balances[liquidityGenAddress] = balances[liquidityGenAddress].add(amountToMint);
totalSupply_.add(amountToMint);
return balances[liquidityGenAddress];
}
function setAmountToBurn(uint256 amountToBurn) public returns (uint256) {
require(isLiquidityContractOwner(msg.sender));
balances[BURN_address] = balances[BURN_address].add(amountToBurn);
totalSupply_.sub(amountToBurn);
return balances[liquidityGenAddress];
}
function setDefaultBurnOnTransaction(bool toggleBool) public returns (bool) {
require(isLiquidityContractOwner(msg.sender));
defaultBurnOnTransaction_ = toggleBool;
}
function setCurrentPrePurchaseTargetMarketCap(uint256 newTargetMC) public returns (uint256) {
require(isContractOwner(msg.sender));
prePurchaseTargetMarketCap_ = newTargetMC;
return prePurchaseTargetMarketCap_;
}
function balanceOf(address tokenOwner) public view returns (uint) {
return balances[tokenOwner];
}
function transferTaxFree(address receiver, uint numTokens) public returns (bool) {
require(isContractOwner(msg.sender));
require(numTokens <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(numTokens);
balances[receiver] = balances[receiver].add(numTokens);
emit Transfer(msg.sender, receiver, numTokens);
return true;
}
function transfer(address receiver, uint256 numTokens) public returns (bool) {
require(numTokens <= balances[msg.sender]);
//where taxValues[0] is the primary transfer balance and taxValues[1] is the tax
uint256[] memory taxValues = determineTax(numTokens);
//primary transfer
balances[msg.sender] = balances[msg.sender].sub(taxValues[0]);
balances[receiver] = balances[receiver].add(taxValues[0]);
emit Transfer(msg.sender, receiver, taxValues[0]);
//tax transfer DAO
balances[msg.sender] = balances[msg.sender].sub(taxValues[1]);
balances[DAO_address] = balances[DAO_address].add(taxValues[1]);
emit Transfer(msg.sender, DAO_address, taxValues[1]);
//tax transfer Burn
address burnOrMint;
if(defaultBurnOnTransaction_){
address burnOrMint = BURN_address;
totalSupply_.sub(taxValues[2]);
} else {
address burnOrMint = liquidityGenAddress;
totalSupply_.add(taxValues[2]);
}
balances[msg.sender] = balances[msg.sender].sub(taxValues[2]);
balances[burnOrMint] = balances[burnOrMint].add(taxValues[2]);
emit Transfer(msg.sender, burnOrMint, taxValues[2]);
return true;
}
// this allows people to approve third parties to manage a percentage of their funds.
// The DAO (for example) could assign a portion of it's funds to a third party for management
function approve(address delegate, uint numTokens) public returns (bool) {
require(isContractOwner(msg.sender));
allowed[msg.sender][delegate] = numTokens;
emit Approval(msg.sender, delegate, numTokens);
return true;
}
// this returns the amount of your funds you allowed someone to delegate
function allowance(address owner, address delegate) public view returns (uint) {
return allowed[owner][delegate];
}
//this is transferFunction which is from a delegate and does not include a tax
function transferFrom(address owner, address buyer, uint256 numTokens) public returns (bool) {
require(numTokens <= balances[owner]);
require(numTokens <= allowed[owner][msg.sender]);
balances[owner] = balances[owner].sub(numTokens);
allowed[owner][msg.sender] = allowed[owner][msg.sender].sub(numTokens);
balances[buyer] = balances[buyer].add(numTokens);
emit Transfer(owner, buyer, numTokens);
return true;
}
function getTaxFee(uint256 amount, uint256 tax) public pure returns (uint256) {
return amount.mul(tax.div(10**2));
}
function determineTax(uint256 basis) public view returns (uint256[] memory){
uint256[] memory results = new uint256[](4);
if (basis < taxableThresholds[0][0]){
// no tax for our friends who are broke
results[1] = 0;
if (taxableThresholds[0][5] == 1) {
// fixed fee
results[2] = taxableThresholds[0][4];
} else {
// dynamic fee
results[2] = getTaxFee(taxableThresholds[0][2], basis);
}
results[0] = basis.sub(results[2]);
return results;
}
if (basis < taxableThresholds[1][0]){
if (taxableThresholds[1][5] == 1) {
// fixed fee
results[1] = taxableThresholds[1][3];
results[2] = taxableThresholds[1][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[1][1], basis);
results[2] = getTaxFee(taxableThresholds[1][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
if (basis < taxableThresholds[2][0]){
if (taxableThresholds[2][5] == 1) {
// fixed fee
results[1] = taxableThresholds[2][3];
results[2] = taxableThresholds[2][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[2][1], basis);
results[2] = getTaxFee(taxableThresholds[2][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
if (basis < taxableThresholds[3][0]){
if (taxableThresholds[3][5] == 1) {
// fixed fee
results[1] = taxableThresholds[3][3];
results[2] = taxableThresholds[3][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[3][1], basis);
results[2] = getTaxFee(taxableThresholds[3][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
if (basis < taxableThresholds[4][0]){
if (taxableThresholds[4][5] == 1) {
// fixed fee
results[1] = taxableThresholds[4][3];
results[2] = taxableThresholds[4][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[4][1], basis);
results[2] = getTaxFee(taxableThresholds[4][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
// catches everything above the conditions above
if (taxableThresholds[5][5] == 1) {
// fixed fee
results[1] = taxableThresholds[5][3];
results[2] = taxableThresholds[5][4];
} else {
// dynamic fee
results[1] = getTaxFee(taxableThresholds[5][1], basis);
results[2] = getTaxFee(taxableThresholds[5][2], basis);
}
results[0] = basis.sub(results[2]).sub(results[1]);
return results;
}
function updateTaxableThresholdsAtIndex(uint256 indexToMod, uint256 thresHoldFixed, uint256 taxPerc, uint256 burnPerc, uint256 taxFixed, uint256 burnFixed, uint256 isFixed) public payable returns(bool){
if(isContractOwner(msg.sender)){
taxableThresholds[indexToMod] = [thresHoldFixed, taxPerc, burnPerc, taxFixed, burnFixed, isFixed];
return true;
}
}
function getPriceOfETH() public view returns (uint256) {
return uint256(PF2.getLatestPrice());
}
function getNumberOfWeiInDollar() public view returns (uint256) {
uint256 weiBase = 1000000000000000000;
return weiBase.div(getPriceOfETH().div(100000000));
}
function getUserEthBalance() public payable returns (uint256) {
return msg.sender.balance;
}
function prePurchaseOnEthNetwork(address receiver, uint256 numTokens) public payable returns (uint256) {
require(numTokens <= msg.sender.balance);
require(prePurchaseTargetMarketCap_ != 0);
// minimum purchase is 5 dollars
//require(numTokens <= numWeiInDollar.mul(5));
uint256 awardedTokens = PF2.calculateTokensBack(msg.value, prePurchaseTargetMarketCap_, totalSupply_);
payable(liquidityGenAddress).transfer(msg.value);
balances[msg.sender] = balances[msg.sender].add(awardedTokens);
totalSupply_ = totalSupply_ + awardedTokens;
emit Recieved(msg.sender, msg.value, DAO_address);
//prePurchaseBalances[msg.sender] = prePurchaseBalances[msg.sender].add(awardedTokens);
return awardedTokens;
}
}
library SafeMath2 {
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;
}
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) {
uint256 c = a / b;
return c;
}
}
| where taxValues[0] is the primary transfer balance and taxValues[1] is the taxprimary transfertax transfer DAOtax transfer Burn | function transfer(address receiver, uint256 numTokens) public returns (bool) {
require(numTokens <= balances[msg.sender]);
uint256[] memory taxValues = determineTax(numTokens);
balances[msg.sender] = balances[msg.sender].sub(taxValues[0]);
balances[receiver] = balances[receiver].add(taxValues[0]);
emit Transfer(msg.sender, receiver, taxValues[0]);
balances[msg.sender] = balances[msg.sender].sub(taxValues[1]);
balances[DAO_address] = balances[DAO_address].add(taxValues[1]);
emit Transfer(msg.sender, DAO_address, taxValues[1]);
address burnOrMint;
if(defaultBurnOnTransaction_){
address burnOrMint = BURN_address;
totalSupply_.sub(taxValues[2]);
address burnOrMint = liquidityGenAddress;
totalSupply_.add(taxValues[2]);
}
balances[msg.sender] = balances[msg.sender].sub(taxValues[2]);
balances[burnOrMint] = balances[burnOrMint].add(taxValues[2]);
emit Transfer(msg.sender, burnOrMint, taxValues[2]);
return true;
}
| 5,425,881 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/utils/math/SafeMath.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../erc20/ERC20Entangled.sol";
import "../locking/ILockedAmount.sol";
import "./IIDO.sol";
struct Vesting {
address beneficiary;
uint256 amount;
uint256 timestamp;
bool claimed;
}
struct IPFSMultihash {
bytes32 digest;
uint8 hashFunction;
uint8 size;
}
struct Range {
uint256 start;
uint256 end;
}
struct Multiplier {
uint32 multiplier;
uint32 divider;
}
struct IDOParams {
bool approved;
ERC20Entangled token;
Multiplier multiplier;
IPFSMultihash ipfs;
Range open;
uint256 minimumLockedAmount;
uint256 baseAmount;
uint256 maxAmountPerAddress;
uint256 totalBought;
}
struct IDO {
IDOParams params;
address owner;
uint256 paidToOwner;
}
uint256 constant MAX_VESTING_OCURRENCES = 16;
function _isValidMultiplier(Multiplier memory multiplier) pure returns (bool) {
return multiplier.multiplier > 0 && multiplier.divider > 0;
}
contract SeaweedIDO is Ownable {
IDO[] private idos;
mapping(uint256 => mapping(address => uint256)) bought;
mapping(uint256 => mapping(address => bool)) _beenPaid;
Vesting[MAX_VESTING_OCURRENCES][] _vesting;
ILockedAmount private _lockingContract;
constructor() {}
function idosLength() public view returns (uint256) {
return idos.length;
}
function getId(uint256 id) internal view returns (IDO storage ido) {
require(idos.length > id, "IDO id non-existant");
return idos[id];
}
function publish(
string memory tokenName,
string memory tokenSymbol,
IDOParams memory params,
Vesting[MAX_VESTING_OCURRENCES] calldata vesting
) public {
require(block.timestamp < params.open.end, "would already ended");
require(
params.open.start < params.open.end,
"start time should be before end time"
);
require(
_isValidMultiplier(params.multiplier),
"Multiplier isn't valid"
);
ERC20Entangled token = new ERC20Entangled(tokenName, tokenSymbol);
uint256 id = idos.length;
idos.push(IDO(params, msg.sender, 0));
IDO storage ido = idos[id];
ido.params.token = token;
if (ido.params.ipfs.digest == 0) {
ido.params.ipfs = IPFSMultihash(
0x65b57eb7111c51b539ee694a5dd5f893e3f1ae4f7d47b6c31fb5903c9c8e7141,
18,
32
);
}
ido.params.totalBought = 0;
Vesting[MAX_VESTING_OCURRENCES] storage vest = _vesting.push();
for (uint256 i = 0; i < MAX_VESTING_OCURRENCES; i++) {
require(
vest[i].beneficiary == address(0) ||
vest[i].timestamp >= ido.params.open.end,
"Tokens must be vested after the IDO ends"
);
vest[i] = vesting[i];
}
emit IDOPublished(id, ido);
}
function information(uint256 id) public view returns (IDO memory) {
return idos[id];
}
function vestingFor(uint256 id)
public
view
returns (Vesting[MAX_VESTING_OCURRENCES] memory vesting)
{
return _vesting[id];
}
function claimVesting(uint256 id, uint256 index) external {
Vesting storage vesting = _vesting[id][index];
IDO storage ido = getId(id);
require(!vesting.claimed, "Already claimed");
require(vesting.timestamp >= block.timestamp);
require(ido.owner == msg.sender, "Not IDO Owner");
ido.params.token.mint(vesting.beneficiary, vesting.amount);
vesting.claimed = true;
}
/**
* @dev Change IPFS hash
*/
function setIPFS(uint256 id, IPFSMultihash calldata ipfs) external {
IDO storage ido = getId(id);
require(ido.owner == msg.sender, "must be owner");
require(
block.timestamp <= ido.params.open.start,
"IDO not on pre-sale"
);
ido.params.ipfs = ipfs;
emit IPFSChange(id, ipfs);
}
/**
* @dev Change IPFS hash
*/
function setLockingAddress(address where) public onlyOwner {
_lockingContract = ILockedAmount(where);
}
/**
* @dev Change IPFS hash
*/
function lockingContract() public view returns (address) {
return address(_lockingContract);
}
/**
* @dev Returns if the selected address is whitelisted via locking.
*/
function whitelisted(uint256 id, address account)
public
view
returns (bool status)
{
if (_lockingContract == ILockedAmount(address(0))) return true;
IDO storage ido = idos[id];
if (ido.params.minimumLockedAmount == 0) return true;
return (_lockingContract.lockedAmount(account) >=
ido.params.minimumLockedAmount);
}
/**
* @dev Returns if the selected address can buy.
*/
function canBuy(uint256 id, address account)
private
view
returns (bool status)
{
IDO storage ido = idos[id];
return
(block.timestamp >= ido.params.open.start) &&
(block.timestamp < ido.params.open.end) &&
whitelisted(id, account);
}
function _availableToBuy(IDO storage ido)
private
view
returns (uint256 quantity)
{
return ido.params.baseAmount - ido.params.totalBought;
}
/**
* @dev Buys the base amount in wei, Fails on unsuccessful tx.
*/
function buy(uint256 id, uint256 amount) public payable {
IDO storage ido = getId(id);
require(msg.value == amount, "Non matching wei");
require(canBuy(id, msg.sender), "Can't buy");
require(amount <= _availableToBuy(ido), "Not enough available to buy");
require(
bought[id][msg.sender] + amount <= ido.params.maxAmountPerAddress,
"Exceding max amount"
);
bought[id][msg.sender] += amount;
ido.params.totalBought += amount;
emit Bought(id, msg.sender, amount, ido.params.totalBought);
}
/**
* @dev Withdraws the amount, Fails on unsuccessful tx.
*/
function withdraw(uint256 id, uint256 amount) public {
IDO storage ido = getId(id);
require(bought[id][msg.sender] >= amount, "Not enough bought");
bought[id][msg.sender] -= amount;
ido.params.totalBought -= amount;
payable(msg.sender).transfer(amount);
emit Withdrawn(id, msg.sender, amount, ido.params.totalBought);
}
/**
* @dev Get's the payout, Fails on unsuccessful tx.
*/
function getPayout(uint256 id) public {
getPayoutOn(id, msg.sender);
}
/**
* @dev Get's the payout, but in a specific address.
*/
function getPayoutOn(uint256 id, address otherAddress) public {
IDO storage ido = getId(id);
uint256 amount = bought[id][msg.sender];
require(amount > 0, "Nothing to pay");
require(!_beenPaid[id][msg.sender], "Already paid");
require(block.timestamp >= ido.params.open.end, "Crowdsale still open");
ido.params.token.mint(
otherAddress,
(amount * ido.params.multiplier.multiplier) /
ido.params.multiplier.divider
);
_beenPaid[id][msg.sender] = true;
}
/**
* @dev Get's the payout, but in a specific address.
*/
function beenPaid(uint256 id, address account)
public
view
returns (bool paid)
{
return _beenPaid[id][account];
}
/**
* @dev Empties the contract wei and sends it to the owner
*/
function getRaised(uint256 id) public {
IDO storage ido = getId(id);
require(ido.owner == msg.sender, "must be owner");
require(ido.params.open.end <= block.timestamp, "ido must be ended");
uint256 payout = ido.params.totalBought - ido.paidToOwner;
payable(msg.sender).transfer(payout);
ido.paidToOwner = ido.params.totalBought;
}
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function boughtAmount(uint256 id, address account)
public
view
returns (uint256)
{
return bought[id][account];
}
/**
* @dev Emitted when an IDO is published.
*/
event IDOPublished(uint256 id, IDO ido);
/**
* @dev Emitted when an IDO changes his description.
*/
event IPFSChange(uint256 id, IPFSMultihash ipfs);
/**
* @dev Emitted when a user buys
*/
event Bought(
uint256 id,
address owner,
uint256 quantity,
uint256 totalBought
);
/**
* @dev Emitted when a user withdraws
*/
event Withdrawn(
uint256 id,
address owner,
uint256 quantity,
uint256 totalBought
);
}
| Returns the amount of tokens owned by `account`./ | function boughtAmount(uint256 id, address account)
public
view
returns (uint256)
{
return bought[id][account];
}
uint256 id,
address owner,
uint256 quantity,
uint256 totalBought
);
uint256 id,
address owner,
uint256 quantity,
uint256 totalBought
);
| 1,080,064 |
/**
*Submitted for verification at Etherscan.io on 2021-09-23
*/
// File: contracts/Dependencies/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this;
// silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// File: contracts/proxy/Dependencies/Ownable.sol
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
// File: contracts/Dependencies/ReentrancyGuard.sol
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor () internal {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File: contracts/Dependencies/SafeMath.sol
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: contracts/Dependencies/IERC20.sol
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: contracts/Dependencies/Address.sol
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {size := extcodesize(account)}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success,) = recipient.call{value : amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value : value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/Dependencies/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {// Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/Dependencies/IERC165.sol
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: contracts/Dependencies/IERC1155.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;
}
// File: contracts/Dependencies/HasCopyright.sol
interface HasCopyright {
struct Copyright {
address author;
uint feeRateNumerator;
}
function getCopyright(uint tokenId) external returns (Copyright memory);
function getFeeRateDenominator() external returns (uint);
}
// File: contracts/proxy/FixedPriceTrade1155.sol
contract FixedPriceTrade1155 is Ownable, ReentrancyGuard {
using SafeMath for uint;
using SafeERC20 for IERC20;
uint private _orderIdCounter;
bool private _onlyInitOnce;
// Target ERC1155 address that involves with copyright
address private _ERC1155AddressWithCopyright;
struct Order {
// Address of maker
address maker;
// Address of ERC1155 token to sell
address tokenAddress;
// Id of ERC1155 token to sell
uint id;
// Remaining amount of ERC1155 token in this order
uint remainingAmount;
// Address of ERC20 token to pay
address payTokenAddress;
// Fixed price of ERC20 token to pay
uint fixedPrice;
// Whether the order is available
bool isAvailable;
}
// Mapping from order id to Order info
mapping(uint => Order) private _orders;
// Payment whitelist for the address of ERC20
mapping(address => bool) private _paymentWhitelist;
event PaymentWhitelistChange(address erc20Addr, bool jurisdiction);
event ERC1155AddressWithCopyrightChanged(address previousAddress, address currentAddress);
event MakeOrder(uint orderId, address maker, address tokenAddress, uint id, uint remainingAmount,
address payTokenAddress, uint fixedPrice);
event UpdateOrder(uint orderId, address operator, uint newRemainingAmount, address newPayTokenAddress,
uint newFixedPrice);
event TakeOrder(uint orderId, address taker, address maker, address tokenAddress, uint id, uint amount,
address payTokenAddress, uint fixedPrice);
event CancelOrder(uint orderId, address operator);
event PayCopyrightFee(uint orderId, address taker, address author, uint copyrightFee);
modifier onlyPaymentWhitelist(address erc20Addr) {
require(_paymentWhitelist[erc20Addr],
"the pay token address isn't in the whitelist");
_;
}
function init(address ERC1155AddressWithCopyright, address newOwner) public {
require(!_onlyInitOnce, "already initialized");
_ERC1155AddressWithCopyright = ERC1155AddressWithCopyright;
emit ERC1155AddressWithCopyrightChanged(address(0), ERC1155AddressWithCopyright);
_transferOwnership(newOwner);
_onlyInitOnce = true;
}
/**
* @dev External function to set order by anyone.
* @param tokenAddress address Address of ERC1155 token contract
* @param id uint Id of ERC1155 token to sell
* @param amount uint Amount of target ERC1155 token to sell
* @param payTokenAddress address ERC20 address of token for payment
* @param fixedPrice uint Fixed price of total ERC1155 token
*/
function ask(
address tokenAddress,
uint id,
uint amount,
address payTokenAddress,
uint fixedPrice
)
external
nonReentrant
onlyPaymentWhitelist(payTokenAddress)
{
// 1. check the validity of params
_checkOrderParams(msg.sender, tokenAddress, id, amount, fixedPrice);
// 2. build order
Order memory order = Order({
maker : msg.sender,
tokenAddress : tokenAddress,
id : id,
remainingAmount : amount,
payTokenAddress : payTokenAddress,
fixedPrice : fixedPrice,
isAvailable : true
});
// 3. store order
uint currentOrderId = _orderIdCounter;
_orderIdCounter = _orderIdCounter.add(1);
_orders[currentOrderId] = order;
emit MakeOrder(currentOrderId, order.maker, order.tokenAddress, order.id, order.remainingAmount,
order.payTokenAddress, order.fixedPrice);
}
/**
* @dev External function to update the existing order by its setter.
* @param newAmount uint New amount of target ERC1155 token to sell
* @param newPayTokenAddress address New ERC20 address of token for payment
* @param newFixedPrice uint New fixed price of each ERC1155 token
*/
function updateOrder(
uint orderId,
uint newAmount,
address newPayTokenAddress,
uint newFixedPrice
)
external
nonReentrant
onlyPaymentWhitelist(newPayTokenAddress)
{
Order memory order = getOrder(orderId);
require(
order.isAvailable,
"the order has been closed"
);
require(
order.maker == msg.sender,
"the order can only be updated by its setter"
);
// 2. check the validity of params to update
_checkOrderParams(msg.sender, order.tokenAddress, order.id, newAmount, newFixedPrice);
// 3. update order
_orders[orderId].remainingAmount = newAmount;
_orders[orderId].payTokenAddress = newPayTokenAddress;
_orders[orderId].fixedPrice = newFixedPrice;
emit UpdateOrder(orderId, msg.sender, newAmount, newPayTokenAddress, newFixedPrice);
}
/**
* @dev External function to cancel the existing order by its setter.
* @param orderId uint The target id of order to be cancelled
*/
function cancelOrder(uint orderId) external {
Order memory order = getOrder(orderId);
require(
order.isAvailable,
"the order has been closed"
);
require(
order.maker == msg.sender,
"the order can only be updated by its setter"
);
_orders[orderId].isAvailable = false;
emit CancelOrder(orderId, msg.sender);
}
/**
* @dev External function to bid the existing order by anyone who can afford it.
* @param orderId uint The target id of order to buy ERC1155 tokens
* @param amount uint The amount of the tokens in the order to buy
*/
function bid(uint orderId, uint amount) external nonReentrant {
Order memory order = getOrder(orderId);
require(
order.isAvailable,
"the order has been closed"
);
require(
order.maker != msg.sender,
"the maker can't bid for its own order"
);
require(
amount > 0,
"amount must be > 0"
);
require(
order.remainingAmount >= amount,
"insufficient remaining tokens in the order"
);
uint newRemainingAmount = order.remainingAmount.sub(amount);
_orders[orderId].remainingAmount = newRemainingAmount;
// Check && pay copyright fee
(uint transferAmount, uint copyrightFee,address author) = _getTransferAndCopyrightFeeAndAuthor(order, amount);
IERC20 tokenToPay = IERC20(order.payTokenAddress);
if (copyrightFee != 0) {
// Pay the copyright fee to author
tokenToPay.safeTransferFrom(msg.sender, author, copyrightFee);
emit PayCopyrightFee(orderId, msg.sender, author, copyrightFee);
}
// Trade
tokenToPay.safeTransferFrom(msg.sender, order.maker, transferAmount);
IERC1155(order.tokenAddress).safeTransferFrom(order.maker, msg.sender, order.id, amount, "");
if (newRemainingAmount == 0) {
// Close the order
_orders[orderId].isAvailable = false;
}
emit TakeOrder(orderId, msg.sender, order.maker, order.tokenAddress, order.id, amount, order.payTokenAddress,
order.fixedPrice);
}
/**
* @dev Public function to change target ERC1155 address that involves with copyright only by the owner.
* @param newERC1155AddressWithCopyright address Target address of ERC1155 contract with copyright
*/
function setERC1155AddressWithCopyright(address newERC1155AddressWithCopyright) public onlyOwner {
address previousAddress = _ERC1155AddressWithCopyright;
_ERC1155AddressWithCopyright = newERC1155AddressWithCopyright;
emit ERC1155AddressWithCopyrightChanged(previousAddress, newERC1155AddressWithCopyright);
}
/**
* @dev Public function to set the payment whitelist only by the owner.
* @param erc20Addr address Address of erc20 for paying
* @param jurisdiction bool In or out of the whitelist
*/
function setPaymentWhitelist(address erc20Addr, bool jurisdiction) public onlyOwner {
_paymentWhitelist[erc20Addr] = jurisdiction;
emit PaymentWhitelistChange(erc20Addr, jurisdiction);
}
/**
* @dev Public function to query whether the target erc20 address is in the payment whitelist.
* @param erc20Addr address Target address of erc20 to query about
*/
function getPaymentWhitelist(address erc20Addr) public view returns (bool){
return _paymentWhitelist[erc20Addr];
}
/**
* @dev Public function to get the target ERC1155 address involved with copyright.
*/
function getERC1155AddressWithCopyright() public view returns (address){
return _ERC1155AddressWithCopyright;
}
/**
* @dev Public function to query the order by order Id.
* @param orderId uint Target id of order to query about
*/
function getOrder(uint orderId) public view returns (Order memory order){
order = _orders[orderId];
require(order.maker != address(0), "the target order doesn't exist");
}
function _getTransferAndCopyrightFeeAndAuthor(
Order memory order,
uint amount
)
private
returns
(
uint transferAmount,
uint copyrightFee,
address author
)
{
transferAmount = order.fixedPrice.mul(amount);
if (order.tokenAddress != _ERC1155AddressWithCopyright) {
// not the official address of ERC1155 token
return (transferAmount, copyrightFee, author);
}
HasCopyright ERC1155WithCopyrightCached = HasCopyright(order.tokenAddress);
HasCopyright.Copyright memory copyright = ERC1155WithCopyrightCached.getCopyright(order.id);
uint feeRateDenominator = ERC1155WithCopyrightCached.getFeeRateDenominator();
if (copyright.author == address(0) || copyright.feeRateNumerator == 0 || copyright.feeRateNumerator > feeRateDenominator) {
// the official ERC1155 token has an invalid copyright info for copyright fee
return (transferAmount, copyrightFee, author);
}
author = copyright.author;
copyrightFee = transferAmount.mul(copyright.feeRateNumerator).div(feeRateDenominator);
transferAmount = transferAmount.sub(copyrightFee);
}
function _checkOrderParams(
address orderSetter,
address tokenAddress,
uint id,
uint amount,
uint fixedPrice
)
private
view
{
// check whether the order setter has the target tokens && approval
IERC1155 tokenAddressCached = IERC1155(tokenAddress);
require(
tokenAddressCached.balanceOf(orderSetter, id) >= amount,
"insufficient amount of ERC1155"
);
require(
tokenAddressCached.isApprovedForAll(orderSetter, address(this)),
"the contract hasn't been approved for ERC1155 transferring"
);
require(amount > 0, "the amount must be > 0");
require(fixedPrice > 0, "the fixed price must be > 0");
}
} | External function to cancel the existing order by its setter. orderId uint The target id of order to be cancelled/ | function cancelOrder(uint orderId) external {
Order memory order = getOrder(orderId);
require(
order.isAvailable,
"the order has been closed"
);
require(
order.maker == msg.sender,
"the order can only be updated by its setter"
);
_orders[orderId].isAvailable = false;
emit CancelOrder(orderId, msg.sender);
}
| 15,272,389 |
./full_match/5/0xf28024650aB3e92e6a227aE4264113182fdc8456/sources/project_/contracts/smart-contracts-dev/staticStorage/MentaportDynamic.sol | ---------------------------------------------------------------------------- External Only ADMIN, MINTER ROLES CONTRACT_ROLE reveals URI for contract - Emits a {Reveal} event./ | function reveal() override external whenNotPaused() onlyContractAdmin {
require(!useDynamicRules, "Failed using dynamic rules, use revealDynamic");
revealed = true;
emit Reveal(msg.sender);
}
| 1,913,847 |
// SPDX-License-Identifier: Apache-2.0
// Copyright 2017 Loopring Technology Limited.
pragma solidity ^0.7.0;
/// @title Utility Functions for uint
/// @author Daniel Wang - <[email protected]>
library MathUint
{
using MathUint for uint;
function mul(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a * b;
require(a == 0 || c / a == b, "MUL_OVERFLOW");
}
function sub(
uint a,
uint b
)
internal
pure
returns (uint)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
function add(
uint a,
uint b
)
internal
pure
returns (uint c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
function add64(
uint64 a,
uint64 b
)
internal
pure
returns (uint64 c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title Ownable
/// @author Brecht Devos - <[email protected]>
/// @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.
constructor()
{
owner = msg.sender;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner()
{
require(msg.sender == owner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to transfer control of the contract to a
/// new owner.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
virtual
onlyOwner
{
require(newOwner != address(0), "ZERO_ADDRESS");
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
function renounceOwnership()
public
onlyOwner
{
emit OwnershipTransferred(owner, address(0));
owner = address(0);
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title Claimable
/// @author Brecht Devos - <[email protected]>
/// @dev Extension for the Ownable contract, where the ownership needs
/// to be claimed. This allows the new owner to accept the transfer.
contract Claimable is Ownable
{
address public pendingOwner;
/// @dev Modifier throws if called by any account other than the pendingOwner.
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner, "UNAUTHORIZED");
_;
}
/// @dev Allows the current owner to set the pendingOwner address.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(
address newOwner
)
public
override
onlyOwner
{
require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS");
pendingOwner = newOwner;
}
/// @dev Allows the pendingOwner address to finalize the transfer.
function claimOwnership()
public
onlyPendingOwner
{
emit OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = address(0);
}
}
//Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol
library BytesUtil {
function concat(
bytes memory _preBytes,
bytes memory _postBytes
)
internal
pure
returns (bytes memory)
{
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)
// Store the length of the first bytes array at the beginning of
// the memory for tempBytes.
let length := mload(_preBytes)
mstore(tempBytes, length)
// Maintain a memory counter for the current write location in the
// temp bytes array by adding the 32 bytes for the array length to
// the starting location.
let mc := add(tempBytes, 0x20)
// Stop copying when the memory counter reaches the length of the
// first bytes array.
let end := add(mc, length)
for {
// Initialize a copy counter to the start of the _preBytes data,
// 32 bytes into its memory.
let cc := add(_preBytes, 0x20)
} lt(mc, end) {
// Increase both counters by 32 bytes each iteration.
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
// Write the _preBytes data into the tempBytes memory 32 bytes
// at a time.
mstore(mc, mload(cc))
}
// Add the length of _postBytes to the current length of tempBytes
// and store it as the new length in the first 32 bytes of the
// tempBytes memory.
length := mload(_postBytes)
mstore(tempBytes, add(length, mload(tempBytes)))
// Move the memory counter back from a multiple of 0x20 to the
// actual end of the _preBytes data.
mc := end
// Stop copying when the memory counter reaches the new combined
// length of the arrays.
end := add(mc, length)
for {
let cc := add(_postBytes, 0x20)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
// Update the free-memory pointer by padding our last write location
// to 32 bytes: add 31 bytes to the end of tempBytes to move to the
// next 32 byte block, then round down to the nearest multiple of
// 32. If the sum of the length of the two arrays is zero then add
// one before rounding down to leave a blank 32 bytes (the length block with 0).
mstore(0x40, and(
add(add(end, iszero(add(length, mload(_preBytes)))), 31),
not(31) // Round down to the nearest 32 bytes.
))
}
return tempBytes;
}
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length));
bytes memory tempBytes;
assembly {
switch iszero(_length)
case 0 {
// Get a location of some free memory and store it in tempBytes as
// Solidity does for memory variables.
tempBytes := mload(0x40)
// The first word of the slice result is potentially a partial
// word read from the original array. To read it, we calculate
// the length of that partial word and start copying that many
// bytes into the array. The first word we copy will start with
// data we don't care about, but the last `lengthmod` bytes will
// land at the beginning of the contents of the new array. When
// we're done copying, we overwrite the full first word with
// the actual length of the slice.
let lengthmod := and(_length, 31)
// The multiplication in the next line is necessary
// because when slicing multiples of 32 bytes (lengthmod == 0)
// the following copy loop was copying the origin's length
// and then ending prematurely not copying everything it should.
let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod)))
let end := add(mc, _length)
for {
// The multiplication in the next line has the same exact purpose
// as the one above.
let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start)
} lt(mc, end) {
mc := add(mc, 0x20)
cc := add(cc, 0x20)
} {
mstore(mc, mload(cc))
}
mstore(tempBytes, _length)
//update free-memory pointer
//allocating the array padded to 32 bytes like the compiler does now
mstore(0x40, and(add(mc, 31), not(31)))
}
//if we want a zero-length slice let's just return a zero-length array
default {
tempBytes := mload(0x40)
mstore(0x40, add(tempBytes, 0x20))
}
}
return tempBytes;
}
function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) {
require(_bytes.length >= (_start + 20));
address tempAddress;
assembly {
tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000)
}
return tempAddress;
}
function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) {
require(_bytes.length >= (_start + 1));
uint8 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x1), _start))
}
return tempUint;
}
function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) {
require(_bytes.length >= (_start + 2));
uint16 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x2), _start))
}
return tempUint;
}
function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) {
require(_bytes.length >= (_start + 3));
uint24 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x3), _start))
}
return tempUint;
}
function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) {
require(_bytes.length >= (_start + 4));
uint32 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x4), _start))
}
return tempUint;
}
function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) {
require(_bytes.length >= (_start + 8));
uint64 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x8), _start))
}
return tempUint;
}
function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) {
require(_bytes.length >= (_start + 12));
uint96 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0xc), _start))
}
return tempUint;
}
function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) {
require(_bytes.length >= (_start + 16));
uint128 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x10), _start))
}
return tempUint;
}
function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) {
require(_bytes.length >= (_start + 32));
uint256 tempUint;
assembly {
tempUint := mload(add(add(_bytes, 0x20), _start))
}
return tempUint;
}
function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) {
require(_bytes.length >= (_start + 4));
bytes4 tempBytes4;
assembly {
tempBytes4 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes4;
}
function toBytes20(bytes memory _bytes, uint _start) internal pure returns (bytes20) {
require(_bytes.length >= (_start + 20));
bytes20 tempBytes20;
assembly {
tempBytes20 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes20;
}
function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) {
require(_bytes.length >= (_start + 32));
bytes32 tempBytes32;
assembly {
tempBytes32 := mload(add(add(_bytes, 0x20), _start))
}
return tempBytes32;
}
function fastSHA256(
bytes memory data
)
internal
view
returns (bytes32)
{
bytes32[] memory result = new bytes32[](1);
bool success;
assembly {
let ptr := add(data, 32)
success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32)
}
require(success, "SHA256_FAILED");
return result[0];
}
}
// Copyright 2017 Loopring Technology Limited.
pragma experimental ABIEncoderV2;
library EIP712
{
struct Domain {
string name;
string version;
address verifyingContract;
}
bytes32 constant internal EIP712_DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
string constant internal EIP191_HEADER = "\x19\x01";
function hash(Domain memory domain)
internal
pure
returns (bytes32)
{
uint _chainid;
assembly { _chainid := chainid() }
return keccak256(
abi.encode(
EIP712_DOMAIN_TYPEHASH,
keccak256(bytes(domain.name)),
keccak256(bytes(domain.version)),
_chainid,
domain.verifyingContract
)
);
}
function hashPacked(
bytes32 domainHash,
bytes32 dataHash
)
internal
pure
returns (bytes32)
{
return keccak256(
abi.encodePacked(
EIP191_HEADER,
domainHash,
dataHash
)
);
}
}
// Copyright 2017 Loopring Technology Limited.
// Copyright 2017 Loopring Technology Limited.
interface IAgent{}
interface IAgentRegistry
{
/// @dev Returns whether an agent address is an agent of an account owner
/// @param owner The account owner.
/// @param agent The agent address
/// @return True if the agent address is an agent for the account owner, else false
function isAgent(
address owner,
address agent
)
external
view
returns (bool);
/// @dev Returns whether an agent address is an agent of all account owners
/// @param owners The account owners.
/// @param agent The agent address
/// @return True if the agent address is an agent for the account owner, else false
function isAgent(
address[] calldata owners,
address agent
)
external
view
returns (bool);
}
// Copyright 2017 Loopring Technology Limited.
/// @title IBlockVerifier
/// @author Brecht Devos - <[email protected]>
abstract contract IBlockVerifier is Claimable
{
// -- Events --
event CircuitRegistered(
uint8 indexed blockType,
uint16 blockSize,
uint8 blockVersion
);
event CircuitDisabled(
uint8 indexed blockType,
uint16 blockSize,
uint8 blockVersion
);
// -- Public functions --
/// @dev Sets the verifying key for the specified circuit.
/// Every block permutation needs its own circuit and thus its own set of
/// verification keys. Only a limited number of block sizes per block
/// type are supported.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @param vk The verification key
function registerCircuit(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion,
uint[18] calldata vk
)
external
virtual;
/// @dev Disables the use of the specified circuit.
/// This will stop NEW blocks from using the given circuit, blocks that were already committed
/// can still be verified.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
function disableCircuit(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual;
/// @dev Verifies blocks with the given public data and proofs.
/// Verifying a block makes sure all requests handled in the block
/// are correctly handled by the operator.
/// @param blockType The type of block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @param publicInputs The hash of all the public data of the blocks
/// @param proofs The ZK proofs proving that the blocks are correct
/// @return True if the block is valid, false otherwise
function verifyProofs(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion,
uint[] calldata publicInputs,
uint[] calldata proofs
)
external
virtual
view
returns (bool);
/// @dev Checks if a circuit with the specified parameters is registered.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @return True if the circuit is registered, false otherwise
function isCircuitRegistered(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual
view
returns (bool);
/// @dev Checks if a circuit can still be used to commit new blocks.
/// @param blockType The type of the block
/// @param blockSize The number of requests handled in the block
/// @param blockVersion The block version (i.e. which circuit version needs to be used)
/// @return True if the circuit is enabled, false otherwise
function isCircuitEnabled(
uint8 blockType,
uint16 blockSize,
uint8 blockVersion
)
external
virtual
view
returns (bool);
}
// Copyright 2017 Loopring Technology Limited.
/// @title IDepositContract.
/// @dev Contract storing and transferring funds for an exchange.
///
/// ERC1155 tokens can be supported by registering pseudo token addresses calculated
/// as `address(keccak256(real_token_address, token_params))`. Then the custom
/// deposit contract can look up the real token address and paramsters with the
/// pseudo token address before doing the transfers.
/// @author Brecht Devos - <[email protected]>
interface IDepositContract
{
/// @dev Returns if a token is suppoprted by this contract.
function isTokenSupported(address token)
external
view
returns (bool);
/// @dev Transfers tokens from a user to the exchange. This function will
/// be called when a user deposits funds to the exchange.
/// In a simple implementation the funds are simply stored inside the
/// deposit contract directly. More advanced implementations may store the funds
/// in some DeFi application to earn interest, so this function could directly
/// call the necessary functions to store the funds there.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address of the account that sends the tokens.
/// @param token The address of the token to transfer (`0x0` for ETH).
/// @param amount The amount of tokens to transfer.
/// @param extraData Opaque data that can be used by the contract to handle the deposit
/// @return amountReceived The amount to deposit to the user's account in the Merkle tree
function deposit(
address from,
address token,
uint96 amount,
bytes calldata extraData
)
external
payable
returns (uint96 amountReceived);
/// @dev Transfers tokens from the exchange to a user. This function will
/// be called when a withdrawal is done for a user on the exchange.
/// In the simplest implementation the funds are simply stored inside the
/// deposit contract directly so this simply transfers the requested tokens back
/// to the user. More advanced implementations may store the funds
/// in some DeFi application to earn interest so the function would
/// need to get those tokens back from the DeFi application first before they
/// can be transferred to the user.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address from which 'amount' tokens are transferred.
/// @param to The address to which 'amount' tokens are transferred.
/// @param token The address of the token to transfer (`0x0` for ETH).
/// @param amount The amount of tokens transferred.
/// @param extraData Opaque data that can be used by the contract to handle the withdrawal
function withdraw(
address from,
address to,
address token,
uint amount,
bytes calldata extraData
)
external
payable;
/// @dev Transfers tokens (ETH not supported) for a user using the allowance set
/// for the exchange. This way the approval can be used for all functionality (and
/// extended functionality) of the exchange.
/// Should NOT be used to deposit/withdraw user funds, `deposit`/`withdraw`
/// should be used for that as they will contain specialised logic for those operations.
/// This function can be called by the exchange to transfer onchain funds of users
/// necessary for Agent functionality.
///
/// This function needs to throw when an error occurred!
///
/// This function can only be called by the exchange.
///
/// @param from The address of the account that sends the tokens.
/// @param to The address to which 'amount' tokens are transferred.
/// @param token The address of the token to transfer (ETH is and cannot be suppported).
/// @param amount The amount of tokens transferred.
function transfer(
address from,
address to,
address token,
uint amount
)
external
payable;
/// @dev Checks if the given address is used for depositing ETH or not.
/// Is used while depositing to send the correct ETH amount to the deposit contract.
///
/// Note that 0x0 is always registered for deposting ETH when the exchange is created!
/// This function allows additional addresses to be used for depositing ETH, the deposit
/// contract can implement different behaviour based on the address value.
///
/// @param addr The address to check
/// @return True if the address is used for depositing ETH, else false.
function isETH(address addr)
external
view
returns (bool);
}
// Copyright 2017 Loopring Technology Limited.
/// @title ILoopringV3
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
abstract contract ILoopringV3 is Claimable
{
// == Events ==
event ExchangeStakeDeposited(address exchangeAddr, uint amount);
event ExchangeStakeWithdrawn(address exchangeAddr, uint amount);
event ExchangeStakeBurned(address exchangeAddr, uint amount);
event SettingsUpdated(uint time);
// == Public Variables ==
mapping (address => uint) internal exchangeStake;
address public lrcAddress;
uint public totalStake;
address public blockVerifierAddress;
uint public forcedWithdrawalFee;
uint public tokenRegistrationFeeLRCBase;
uint public tokenRegistrationFeeLRCDelta;
uint8 public protocolTakerFeeBips;
uint8 public protocolMakerFeeBips;
address payable public protocolFeeVault;
// == Public Functions ==
/// @dev Updates the global exchange settings.
/// This function can only be called by the owner of this contract.
///
/// Warning: these new values will be used by existing and
/// new Loopring exchanges.
function updateSettings(
address payable _protocolFeeVault, // address(0) not allowed
address _blockVerifierAddress, // address(0) not allowed
uint _forcedWithdrawalFee
)
external
virtual;
/// @dev Updates the global protocol fee settings.
/// This function can only be called by the owner of this contract.
///
/// Warning: these new values will be used by existing and
/// new Loopring exchanges.
function updateProtocolFeeSettings(
uint8 _protocolTakerFeeBips,
uint8 _protocolMakerFeeBips
)
external
virtual;
/// @dev Gets the amount of staked LRC for an exchange.
/// @param exchangeAddr The address of the exchange
/// @return stakedLRC The amount of LRC
function getExchangeStake(
address exchangeAddr
)
public
virtual
view
returns (uint stakedLRC);
/// @dev Burns a certain amount of staked LRC for a specific exchange.
/// This function is meant to be called only from exchange contracts.
/// @return burnedLRC The amount of LRC burned. If the amount is greater than
/// the staked amount, all staked LRC will be burned.
function burnExchangeStake(
uint amount
)
external
virtual
returns (uint burnedLRC);
/// @dev Stakes more LRC for an exchange.
/// @param exchangeAddr The address of the exchange
/// @param amountLRC The amount of LRC to stake
/// @return stakedLRC The total amount of LRC staked for the exchange
function depositExchangeStake(
address exchangeAddr,
uint amountLRC
)
external
virtual
returns (uint stakedLRC);
/// @dev Withdraws a certain amount of staked LRC for an exchange to the given address.
/// This function is meant to be called only from within exchange contracts.
/// @param recipient The address to receive LRC
/// @param requestedAmount The amount of LRC to withdraw
/// @return amountLRC The amount of LRC withdrawn
function withdrawExchangeStake(
address recipient,
uint requestedAmount
)
external
virtual
returns (uint amountLRC);
/// @dev Gets the protocol fee values for an exchange.
/// @return takerFeeBips The protocol taker fee
/// @return makerFeeBips The protocol maker fee
function getProtocolFeeValues(
)
public
virtual
view
returns (
uint8 takerFeeBips,
uint8 makerFeeBips
);
}
/// @title ExchangeData
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library ExchangeData
{
// -- Enums --
enum TransactionType
{
NOOP,
DEPOSIT,
WITHDRAWAL,
TRANSFER,
SPOT_TRADE,
ACCOUNT_UPDATE,
AMM_UPDATE
}
// -- Structs --
struct Token
{
address token;
}
struct ProtocolFeeData
{
uint32 syncedAt; // only valid before 2105 (85 years to go)
uint8 takerFeeBips;
uint8 makerFeeBips;
uint8 previousTakerFeeBips;
uint8 previousMakerFeeBips;
}
// General auxiliary data for each conditional transaction
struct AuxiliaryData
{
uint txIndex;
bytes data;
}
// This is the (virtual) block the owner needs to submit onchain to maintain the
// per-exchange (virtual) blockchain.
struct Block
{
uint8 blockType;
uint16 blockSize;
uint8 blockVersion;
bytes data;
uint256[8] proof;
// Whether we should store the @BlockInfo for this block on-chain.
bool storeBlockInfoOnchain;
// Block specific data that is only used to help process the block on-chain.
// It is not used as input for the circuits and it is not necessary for data-availability.
AuxiliaryData[] auxiliaryData;
// Arbitrary data, mainly for off-chain data-availability, i.e.,
// the multihash of the IPFS file that contains the block data.
bytes offchainData;
}
struct BlockInfo
{
// The time the block was submitted on-chain.
uint32 timestamp;
// The public data hash of the block (the 28 most significant bytes).
bytes28 blockDataHash;
}
// Represents an onchain deposit request.
struct Deposit
{
uint96 amount;
uint64 timestamp;
}
// A forced withdrawal request.
// If the actual owner of the account initiated the request (we don't know who the owner is
// at the time the request is being made) the full balance will be withdrawn.
struct ForcedWithdrawal
{
address owner;
uint64 timestamp;
}
struct Constants
{
uint SNARK_SCALAR_FIELD;
uint MAX_OPEN_FORCED_REQUESTS;
uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE;
uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS;
uint MAX_NUM_ACCOUNTS;
uint MAX_NUM_TOKENS;
uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED;
uint MIN_TIME_IN_SHUTDOWN;
uint TX_DATA_AVAILABILITY_SIZE;
uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND;
}
function SNARK_SCALAR_FIELD() internal pure returns (uint) {
// This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196.
return 21888242871839275222246405745257275088548364400416034343698204186575808495617;
}
function MAX_OPEN_FORCED_REQUESTS() internal pure returns (uint16) { return 4096; }
function MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE() internal pure returns (uint32) { return 15 days; }
function TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS() internal pure returns (uint32) { return 7 days; }
function MAX_NUM_ACCOUNTS() internal pure returns (uint) { return 2 ** 32; }
function MAX_NUM_TOKENS() internal pure returns (uint) { return 2 ** 16; }
function MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED() internal pure returns (uint32) { return 7 days; }
function MIN_TIME_IN_SHUTDOWN() internal pure returns (uint32) { return 30 days; }
// The amount of bytes each rollup transaction uses in the block data for data-availability.
// This is the maximum amount of bytes of all different transaction types.
function TX_DATA_AVAILABILITY_SIZE() internal pure returns (uint32) { return 68; }
function MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND() internal pure returns (uint32) { return 15 days; }
function ACCOUNTID_PROTOCOLFEE() internal pure returns (uint32) { return 0; }
function TX_DATA_AVAILABILITY_SIZE_PART_1() internal pure returns (uint32) { return 29; }
function TX_DATA_AVAILABILITY_SIZE_PART_2() internal pure returns (uint32) { return 39; }
struct AccountLeaf
{
uint32 accountID;
address owner;
uint pubKeyX;
uint pubKeyY;
uint32 nonce;
uint feeBipsAMM;
}
struct BalanceLeaf
{
uint16 tokenID;
uint96 balance;
uint96 weightAMM;
uint storageRoot;
}
struct MerkleProof
{
ExchangeData.AccountLeaf accountLeaf;
ExchangeData.BalanceLeaf balanceLeaf;
uint[48] accountMerkleProof;
uint[24] balanceMerkleProof;
}
struct BlockContext
{
bytes32 DOMAIN_SEPARATOR;
uint32 timestamp;
}
// Represents the entire exchange state except the owner of the exchange.
struct State
{
uint32 maxAgeDepositUntilWithdrawable;
bytes32 DOMAIN_SEPARATOR;
ILoopringV3 loopring;
IBlockVerifier blockVerifier;
IAgentRegistry agentRegistry;
IDepositContract depositContract;
// The merkle root of the offchain data stored in a Merkle tree. The Merkle tree
// stores balances for users using an account model.
bytes32 merkleRoot;
// List of all blocks
mapping(uint => BlockInfo) blocks;
uint numBlocks;
// List of all tokens
Token[] tokens;
// A map from a token to its tokenID + 1
mapping (address => uint16) tokenToTokenId;
// A map from an accountID to a tokenID to if the balance is withdrawn
mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode;
// A map from an account to a token to the amount withdrawable for that account.
// This is only used when the automatic distribution of the withdrawal failed.
mapping (address => mapping (uint16 => uint)) amountWithdrawable;
// A map from an account to a token to the forced withdrawal (always full balance)
mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals;
// A map from an address to a token to a deposit
mapping (address => mapping (uint16 => Deposit)) pendingDeposits;
// A map from an account owner to an approved transaction hash to if the transaction is approved or not
mapping (address => mapping (bytes32 => bool)) approvedTx;
// A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address
mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient;
// Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner
uint32 numPendingForcedTransactions;
// Cached data for the protocol fee
ProtocolFeeData protocolFeeData;
// Time when the exchange was shutdown
uint shutdownModeStartTime;
// Time when the exchange has entered withdrawal mode
uint withdrawalModeStartTime;
// Last time the protocol fee was withdrawn for a specific token
mapping (address => uint) protocolFeeLastWithdrawnTime;
}
}
// Copyright 2017 Loopring Technology Limited.
abstract contract ERC1271 {
// bytes4(keccak256("isValidSignature(bytes32,bytes)")
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function isValidSignature(
bytes32 _hash,
bytes memory _signature)
public
view
virtual
returns (bytes4 magicValueB32);
}
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for addresses
/// @author Daniel Wang - <[email protected]>
/// @author Brecht Devos - <[email protected]>
library AddressUtil
{
using AddressUtil for *;
function isContract(
address addr
)
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;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(addr) }
return (codehash != 0x0 &&
codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470);
}
function toPayable(
address addr
)
internal
pure
returns (address payable)
{
return payable(addr);
}
// Works like address.send but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETH(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
if (amount == 0) {
return true;
}
address payable recipient = to.toPayable();
/* solium-disable-next-line */
(success, ) = recipient.call{value: amount, gas: gasLimit}("");
}
// Works like address.transfer but with a customizable gas limit
// Make sure your code is safe for reentrancy when using this function!
function sendETHAndVerify(
address to,
uint amount,
uint gasLimit
)
internal
returns (bool success)
{
success = to.sendETH(amount, gasLimit);
require(success, "TRANSFER_FAILURE");
}
// Works like call but is slightly more efficient when data
// needs to be copied from memory to do the call.
function fastCall(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bool success, bytes memory returnData)
{
if (to != address(0)) {
assembly {
// Do the call
success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0)
// Copy the return data
let size := returndatasize()
returnData := mload(0x40)
mstore(returnData, size)
returndatacopy(add(returnData, 32), 0, size)
// Update free memory pointer
mstore(0x40, add(returnData, add(32, size)))
}
}
}
// Like fastCall, but throws when the call is unsuccessful.
function fastCallAndVerify(
address to,
uint gasLimit,
uint value,
bytes memory data
)
internal
returns (bytes memory returnData)
{
bool success;
(success, returnData) = fastCall(to, gasLimit, value, data);
if (!success) {
assembly {
revert(add(returnData, 32), mload(returnData))
}
}
}
}
// Copyright 2017 Loopring Technology Limited.
interface IAmmSharedConfig
{
function maxForcedExitAge() external view returns (uint);
function maxForcedExitCount() external view returns (uint);
function forcedExitFee() external view returns (uint);
}
// Copyright 2017 Loopring Technology Limited.
/// @title SignatureUtil
/// @author Daniel Wang - <[email protected]>
/// @dev This method supports multihash standard. Each signature's last byte indicates
/// the signature's type.
library SignatureUtil
{
using BytesUtil for bytes;
using MathUint for uint;
using AddressUtil for address;
enum SignatureType {
ILLEGAL,
INVALID,
EIP_712,
ETH_SIGN,
WALLET // deprecated
}
bytes4 constant internal ERC1271_MAGICVALUE = 0x1626ba7e;
function verifySignatures(
bytes32 signHash,
address[] memory signers,
bytes[] memory signatures
)
internal
view
returns (bool)
{
require(signers.length == signatures.length, "BAD_SIGNATURE_DATA");
address lastSigner;
for (uint i = 0; i < signers.length; i++) {
require(signers[i] > lastSigner, "INVALID_SIGNERS_ORDER");
lastSigner = signers[i];
if (!verifySignature(signHash, signers[i], signatures[i])) {
return false;
}
}
return true;
}
function verifySignature(
bytes32 signHash,
address signer,
bytes memory signature
)
internal
view
returns (bool)
{
if (signer == address(0)) {
return false;
}
return signer.isContract()?
verifyERC1271Signature(signHash, signer, signature):
verifyEOASignature(signHash, signer, signature);
}
function recoverECDSASigner(
bytes32 signHash,
bytes memory signature
)
internal
pure
returns (address)
{
if (signature.length != 65) {
return address(0);
}
bytes32 r;
bytes32 s;
uint8 v;
// we jump 32 (0x20) as the first slot of bytes contains the length
// we jump 65 (0x41) per signature
// for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask
assembly {
r := mload(add(signature, 0x20))
s := mload(add(signature, 0x40))
v := and(mload(add(signature, 0x41)), 0xff)
}
// See https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/cryptography/ECDSA.sol
if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) {
return address(0);
}
if (v == 27 || v == 28) {
return ecrecover(signHash, v, r, s);
} else {
return address(0);
}
}
function verifyEOASignature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
pure
returns (bool success)
{
if (signer == address(0)) {
return false;
}
uint signatureTypeOffset = signature.length.sub(1);
SignatureType signatureType = SignatureType(signature.toUint8(signatureTypeOffset));
// Strip off the last byte of the signature by updating the length
assembly {
mstore(signature, signatureTypeOffset)
}
if (signatureType == SignatureType.EIP_712) {
success = (signer == recoverECDSASigner(signHash, signature));
} else if (signatureType == SignatureType.ETH_SIGN) {
bytes32 hash = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", signHash)
);
success = (signer == recoverECDSASigner(hash, signature));
} else {
success = false;
}
// Restore the signature length
assembly {
mstore(signature, add(signatureTypeOffset, 1))
}
return success;
}
function verifyERC1271Signature(
bytes32 signHash,
address signer,
bytes memory signature
)
private
view
returns (bool)
{
bytes memory callData = abi.encodeWithSelector(
ERC1271.isValidSignature.selector,
signHash,
signature
);
(bool success, bytes memory result) = signer.staticcall(callData);
return (
success &&
result.length == 32 &&
result.toBytes4(0) == ERC1271_MAGICVALUE
);
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title Utility Functions for uint
/// @author Daniel Wang - <[email protected]>
library MathUint96
{
function add(
uint96 a,
uint96 b
)
internal
pure
returns (uint96 c)
{
c = a + b;
require(c >= a, "ADD_OVERFLOW");
}
function sub(
uint96 a,
uint96 b
)
internal
pure
returns (uint96 c)
{
require(b <= a, "SUB_UNDERFLOW");
return a - b;
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title ERC20 Token Interface
/// @dev see https://github.com/ethereum/EIPs/issues/20
/// @author Daniel Wang - <[email protected]>
abstract contract ERC20
{
function totalSupply()
public
virtual
view
returns (uint);
function balanceOf(
address who
)
public
virtual
view
returns (uint);
function allowance(
address owner,
address spender
)
public
virtual
view
returns (uint);
function transfer(
address to,
uint value
)
public
virtual
returns (bool);
function transferFrom(
address from,
address to,
uint value
)
public
virtual
returns (bool);
function approve(
address spender,
uint value
)
public
virtual
returns (bool);
}
// Copyright 2017 Loopring Technology Limited.
/// @title IExchangeV3
/// @dev Note that Claimable and RentrancyGuard are inherited here to
/// ensure all data members are declared on IExchangeV3 to make it
/// easy to support upgradability through proxies.
///
/// Subclasses of this contract must NOT define constructor to
/// initialize data.
///
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
abstract contract IExchangeV3 is Claimable
{
// -- Events --
event ExchangeCloned(
address exchangeAddress,
address owner,
bytes32 genesisMerkleRoot
);
event TokenRegistered(
address token,
uint16 tokenId
);
event Shutdown(
uint timestamp
);
event WithdrawalModeActivated(
uint timestamp
);
event BlockSubmitted(
uint indexed blockIdx,
bytes32 merkleRoot,
bytes32 publicDataHash
);
event DepositRequested(
address from,
address to,
address token,
uint16 tokenId,
uint96 amount
);
event ForcedWithdrawalRequested(
address owner,
address token,
uint32 accountID
);
event WithdrawalCompleted(
uint8 category,
address from,
address to,
address token,
uint amount
);
event WithdrawalFailed(
uint8 category,
address from,
address to,
address token,
uint amount
);
event ProtocolFeesUpdated(
uint8 takerFeeBips,
uint8 makerFeeBips,
uint8 previousTakerFeeBips,
uint8 previousMakerFeeBips
);
event TransactionApproved(
address owner,
bytes32 transactionHash
);
// events from libraries
/*event DepositProcessed(
address to,
uint32 toAccountId,
uint16 token,
uint amount
);*/
/*event ForcedWithdrawalProcessed(
uint32 fromAccountID,
uint16 tokenID,
uint amount
);*/
/*event ConditionalTransferProcessed(
address from,
address to,
uint16 token,
uint amount
);*/
/*event AccountUpdated(
uint32 owner,
uint publicKey
);*/
// -- Initialization --
/// @dev Initializes this exchange. This method can only be called once.
/// @param loopring The LoopringV3 contract address.
/// @param owner The owner of this exchange.
/// @param genesisMerkleRoot The initial Merkle tree state.
function initialize(
address loopring,
address owner,
bytes32 genesisMerkleRoot
)
virtual
external;
/// @dev Initialized the agent registry contract used by the exchange.
/// Can only be called by the exchange owner once.
/// @param agentRegistry The agent registry contract to be used
function setAgentRegistry(address agentRegistry)
external
virtual;
/// @dev Gets the agent registry contract used by the exchange.
/// @return the agent registry contract
function getAgentRegistry()
external
virtual
view
returns (IAgentRegistry);
/// Can only be called by the exchange owner once.
/// @param depositContract The deposit contract to be used
function setDepositContract(address depositContract)
external
virtual;
/// @dev Gets the deposit contract used by the exchange.
/// @return the deposit contract
function getDepositContract()
external
virtual
view
returns (IDepositContract);
// @dev Exchange owner withdraws fees from the exchange.
// @param token Fee token address
// @param feeRecipient Fee recipient address
function withdrawExchangeFees(
address token,
address feeRecipient
)
external
virtual;
// -- Constants --
/// @dev Returns a list of constants used by the exchange.
/// @return constants The list of constants.
function getConstants()
external
virtual
pure
returns(ExchangeData.Constants memory);
// -- Mode --
/// @dev Returns hether the exchange is in withdrawal mode.
/// @return Returns true if the exchange is in withdrawal mode, else false.
function isInWithdrawalMode()
external
virtual
view
returns (bool);
/// @dev Returns whether the exchange is shutdown.
/// @return Returns true if the exchange is shutdown, else false.
function isShutdown()
external
virtual
view
returns (bool);
// -- Tokens --
/// @dev Registers an ERC20 token for a token id. Note that different exchanges may have
/// different ids for the same ERC20 token.
///
/// Please note that 1 is reserved for Ether (ETH), 2 is reserved for Wrapped Ether (ETH),
/// and 3 is reserved for Loopring Token (LRC).
///
/// This function is only callable by the exchange owner.
///
/// @param tokenAddress The token's address
/// @return tokenID The token's ID in this exchanges.
function registerToken(
address tokenAddress
)
external
virtual
returns (uint16 tokenID);
/// @dev Returns the id of a registered token.
/// @param tokenAddress The token's address
/// @return tokenID The token's ID in this exchanges.
function getTokenID(
address tokenAddress
)
external
virtual
view
returns (uint16 tokenID);
/// @dev Returns the address of a registered token.
/// @param tokenID The token's ID in this exchanges.
/// @return tokenAddress The token's address
function getTokenAddress(
uint16 tokenID
)
external
virtual
view
returns (address tokenAddress);
// -- Stakes --
/// @dev Gets the amount of LRC the owner has staked onchain for this exchange.
/// The stake will be burned if the exchange does not fulfill its duty by
/// processing user requests in time. Please note that order matching may potentially
/// performed by another party and is not part of the exchange's duty.
///
/// @return The amount of LRC staked
function getExchangeStake()
external
virtual
view
returns (uint);
/// @dev Withdraws the amount staked for this exchange.
/// This can only be done if the exchange has been correctly shutdown:
/// - The exchange owner has shutdown the exchange
/// - All deposit requests are processed
/// - All funds are returned to the users (merkle root is reset to initial state)
///
/// Can only be called by the exchange owner.
///
/// @return amountLRC The amount of LRC withdrawn
function withdrawExchangeStake(
address recipient
)
external
virtual
returns (uint amountLRC);
/// @dev Can by called by anyone to burn the stake of the exchange when certain
/// conditions are fulfilled.
///
/// Currently this will only burn the stake of the exchange if
/// the exchange is in withdrawal mode.
function burnExchangeStake()
external
virtual;
// -- Blocks --
/// @dev Gets the current Merkle root of this exchange's virtual blockchain.
/// @return The current Merkle root.
function getMerkleRoot()
external
virtual
view
returns (bytes32);
/// @dev Gets the height of this exchange's virtual blockchain. The block height for a
/// new exchange is 1.
/// @return The virtual blockchain height which is the index of the last block.
function getBlockHeight()
external
virtual
view
returns (uint);
/// @dev Gets some minimal info of a previously submitted block that's kept onchain.
/// A DEX can use this function to implement a payment receipt verification
/// contract with a challange-response scheme.
/// @param blockIdx The block index.
function getBlockInfo(uint blockIdx)
external
virtual
view
returns (ExchangeData.BlockInfo memory);
/// @dev Sumbits new blocks to the rollup blockchain.
///
/// This function can only be called by the exchange operator.
///
/// @param blocks The blocks being submitted
/// - blockType: The type of the new block
/// - blockSize: The number of onchain or offchain requests/settlements
/// that have been processed in this block
/// - blockVersion: The circuit version to use for verifying the block
/// - storeBlockInfoOnchain: If the block info for this block needs to be stored on-chain
/// - data: The data for this block
/// - offchainData: Arbitrary data, mainly for off-chain data-availability, i.e.,
/// the multihash of the IPFS file that contains the block data.
function submitBlocks(ExchangeData.Block[] calldata blocks)
external
virtual;
/// @dev Gets the number of available forced request slots.
/// @return The number of available slots.
function getNumAvailableForcedSlots()
external
virtual
view
returns (uint);
// -- Deposits --
/// @dev Deposits Ether or ERC20 tokens to the specified account.
///
/// This function is only callable by an agent of 'from'.
///
/// A fee to the owner is paid in ETH to process the deposit.
/// The operator is not forced to do the deposit and the user can send
/// any fee amount.
///
/// @param from The address that deposits the funds to the exchange
/// @param to The account owner's address receiving the funds
/// @param tokenAddress The address of the token, use `0x0` for Ether.
/// @param amount The amount of tokens to deposit
/// @param auxiliaryData Optional extra data used by the deposit contract
function deposit(
address from,
address to,
address tokenAddress,
uint96 amount,
bytes calldata auxiliaryData
)
external
virtual
payable;
/// @dev Gets the amount of tokens that may be added to the owner's account.
/// @param owner The destination address for the amount deposited.
/// @param tokenAddress The address of the token, use `0x0` for Ether.
/// @return The amount of tokens pending.
function getPendingDepositAmount(
address owner,
address tokenAddress
)
external
virtual
view
returns (uint96);
// -- Withdrawals --
/// @dev Submits an onchain request to force withdraw Ether or ERC20 tokens.
/// This request always withdraws the full balance.
///
/// This function is only callable by an agent of the account.
///
/// The total fee in ETH that the user needs to pay is 'withdrawalFee'.
/// If the user sends too much ETH the surplus is sent back immediately.
///
/// Note that after such an operation, it will take the owner some
/// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request
/// and create the deposit to the offchain account.
///
/// @param owner The expected owner of the account
/// @param tokenAddress The address of the token, use `0x0` for Ether.
/// @param accountID The address the account in the Merkle tree.
function forceWithdraw(
address owner,
address tokenAddress,
uint32 accountID
)
external
virtual
payable;
/// @dev Checks if a forced withdrawal is pending for an account balance.
/// @param accountID The accountID of the account to check.
/// @param token The token address
/// @return True if a request is pending, false otherwise
function isForcedWithdrawalPending(
uint32 accountID,
address token
)
external
virtual
view
returns (bool);
/// @dev Submits an onchain request to withdraw Ether or ERC20 tokens from the
/// protocol fees account. The complete balance is always withdrawn.
///
/// Anyone can request a withdrawal of the protocol fees.
///
/// Note that after such an operation, it will take the owner some
/// time (no more than MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE) to process the request
/// and create the deposit to the offchain account.
///
/// @param tokenAddress The address of the token, use `0x0` for Ether.
function withdrawProtocolFees(
address tokenAddress
)
external
virtual
payable;
/// @dev Gets the time the protocol fee for a token was last withdrawn.
/// @param tokenAddress The address of the token, use `0x0` for Ether.
/// @return The time the protocol fee was last withdrawn.
function getProtocolFeeLastWithdrawnTime(
address tokenAddress
)
external
virtual
view
returns (uint);
/// @dev Allows anyone to withdraw funds for a specified user using the balances stored
/// in the Merkle tree. The funds will be sent to the owner of the acount.
///
/// Can only be used in withdrawal mode (i.e. when the owner has stopped
/// committing blocks and is not able to commit any more blocks).
///
/// This will NOT modify the onchain merkle root! The merkle root stored
/// onchain will remain the same after the withdrawal. We store if the user
/// has withdrawn the balance in State.withdrawnInWithdrawMode.
///
/// @param merkleProof The Merkle inclusion proof
function withdrawFromMerkleTree(
ExchangeData.MerkleProof calldata merkleProof
)
external
virtual;
/// @dev Checks if the balance for the account was withdrawn with `withdrawFromMerkleTree`.
/// @param accountID The accountID of the balance to check.
/// @param token The token address
/// @return True if it was already withdrawn, false otherwise
function isWithdrawnInWithdrawalMode(
uint32 accountID,
address token
)
external
virtual
view
returns (bool);
/// @dev Allows withdrawing funds deposited to the contract in a deposit request when
/// it was never processed by the owner within the maximum time allowed.
///
/// Can be called by anyone. The deposited tokens will be sent back to
/// the owner of the account they were deposited in.
///
/// @param owner The address of the account the withdrawal was done for.
/// @param token The token address
function withdrawFromDepositRequest(
address owner,
address token
)
external
virtual;
/// @dev Allows withdrawing funds after a withdrawal request (either onchain
/// or offchain) was submitted in a block by the operator.
///
/// Can be called by anyone. The withdrawn tokens will be sent to
/// the owner of the account they were withdrawn out.
///
/// Normally it is should not be needed for users to call this manually.
/// Funds from withdrawal requests will be sent to the account owner
/// immediately by the owner when the block is submitted.
/// The user will however need to call this manually if the transfer failed.
///
/// Tokens and owners must have the same size.
///
/// @param owners The addresses of the account the withdrawal was done for.
/// @param tokens The token addresses
function withdrawFromApprovedWithdrawals(
address[] calldata owners,
address[] calldata tokens
)
external
virtual;
/// @dev Gets the amount that can be withdrawn immediately with `withdrawFromApprovedWithdrawals`.
/// @param owner The address of the account the withdrawal was done for.
/// @param token The token address
/// @return The amount withdrawable
function getAmountWithdrawable(
address owner,
address token
)
external
virtual
view
returns (uint);
/// @dev Notifies the exchange that the owner did not process a forced request.
/// If this is indeed the case, the exchange will enter withdrawal mode.
///
/// Can be called by anyone.
///
/// @param accountID The accountID the forced request was made for
/// @param token The token address of the the forced request
function notifyForcedRequestTooOld(
uint32 accountID,
address token
)
external
virtual;
/// @dev Allows a withdrawal to be done to an adddresss that is different
/// than initialy specified in the withdrawal request. This can be used to
/// implement functionality like fast withdrawals.
///
/// This function can only be called by an agent.
///
/// @param from The address of the account that does the withdrawal.
/// @param to The address to which 'amount' tokens were going to be withdrawn.
/// @param token The address of the token that is withdrawn ('0x0' for ETH).
/// @param amount The amount of tokens that are going to be withdrawn.
/// @param storageID The storageID of the withdrawal request.
/// @param newRecipient The new recipient address of the withdrawal.
function setWithdrawalRecipient(
address from,
address to,
address token,
uint96 amount,
uint32 storageID,
address newRecipient
)
external
virtual;
/// @dev Gets the withdrawal recipient.
///
/// @param from The address of the account that does the withdrawal.
/// @param to The address to which 'amount' tokens were going to be withdrawn.
/// @param token The address of the token that is withdrawn ('0x0' for ETH).
/// @param amount The amount of tokens that are going to be withdrawn.
/// @param storageID The storageID of the withdrawal request.
function getWithdrawalRecipient(
address from,
address to,
address token,
uint96 amount,
uint32 storageID
)
external
virtual
view
returns (address);
/// @dev Allows an agent to transfer ERC-20 tokens for a user using the allowance
/// the user has set for the exchange. This way the user only needs to approve a single exchange contract
/// for all exchange/agent features, which allows for a more seamless user experience.
///
/// This function can only be called by an agent.
///
/// @param from The address of the account that sends the tokens.
/// @param to The address to which 'amount' tokens are transferred.
/// @param token The address of the token to transfer (ETH is and cannot be suppported).
/// @param amount The amount of tokens transferred.
function onchainTransferFrom(
address from,
address to,
address token,
uint amount
)
external
virtual;
/// @dev Allows an agent to approve a rollup tx.
///
/// This function can only be called by an agent.
///
/// @param owner The owner of the account
/// @param txHash The hash of the transaction
function approveTransaction(
address owner,
bytes32 txHash
)
external
virtual;
/// @dev Allows an agent to approve multiple rollup txs.
///
/// This function can only be called by an agent.
///
/// @param owners The account owners
/// @param txHashes The hashes of the transactions
function approveTransactions(
address[] calldata owners,
bytes32[] calldata txHashes
)
external
virtual;
/// @dev Checks if a rollup tx is approved using the tx's hash.
///
/// @param owner The owner of the account that needs to authorize the tx
/// @param txHash The hash of the transaction
/// @return True if the tx is approved, else false
function isTransactionApproved(
address owner,
bytes32 txHash
)
external
virtual
view
returns (bool);
// -- Admins --
/// @dev Sets the max time deposits have to wait before becoming withdrawable.
/// @param newValue The new value.
/// @return The old value.
function setMaxAgeDepositUntilWithdrawable(
uint32 newValue
)
external
virtual
returns (uint32);
/// @dev Returns the max time deposits have to wait before becoming withdrawable.
/// @return The value.
function getMaxAgeDepositUntilWithdrawable()
external
virtual
view
returns (uint32);
/// @dev Shuts down the exchange.
/// Once the exchange is shutdown all onchain requests are permanently disabled.
/// When all requirements are fulfilled the exchange owner can withdraw
/// the exchange stake with withdrawStake.
///
/// Note that the exchange can still enter the withdrawal mode after this function
/// has been invoked successfully. To prevent entering the withdrawal mode before the
/// the echange stake can be withdrawn, all withdrawal requests still need to be handled
/// for at least MIN_TIME_IN_SHUTDOWN seconds.
///
/// Can only be called by the exchange owner.
///
/// @return success True if the exchange is shutdown, else False
function shutdown()
external
virtual
returns (bool success);
/// @dev Gets the protocol fees for this exchange.
/// @return syncedAt The timestamp the protocol fees were last updated
/// @return takerFeeBips The protocol taker fee
/// @return makerFeeBips The protocol maker fee
/// @return previousTakerFeeBips The previous protocol taker fee
/// @return previousMakerFeeBips The previous protocol maker fee
function getProtocolFeeValues()
external
virtual
view
returns (
uint32 syncedAt,
uint8 takerFeeBips,
uint8 makerFeeBips,
uint8 previousTakerFeeBips,
uint8 previousMakerFeeBips
);
/// @dev Gets the domain separator used in this exchange.
function getDomainSeparator()
external
virtual
view
returns (bytes32);
}
// Copyright 2017 Loopring Technology Limited.
/// @title AmmData
library AmmData
{
function POOL_TOKEN_BASE() internal pure returns (uint) { return 100 * (10 ** 8); }
function POOL_TOKEN_MINTED_SUPPLY() internal pure returns (uint) { return uint96(-1); }
enum PoolTxType
{
NOOP,
JOIN,
EXIT
}
struct PoolConfig
{
address sharedConfig;
address exchange;
string poolName;
uint32 accountID;
address[] tokens;
uint96[] weights;
uint8 feeBips;
string tokenSymbol;
}
struct PoolJoin
{
address owner;
uint96[] joinAmounts;
uint32[] joinStorageIDs;
uint96 mintMinAmount;
uint32 validUntil;
}
struct PoolExit
{
address owner;
uint96 burnAmount;
uint32 burnStorageID; // for pool token withdrawal from user to the pool
uint96[] exitMinAmounts; // the amount to receive BEFORE paying the fee.
uint96 fee;
uint32 validUntil;
}
struct PoolTx
{
PoolTxType txType;
bytes data;
bytes signature;
}
struct Token
{
address addr;
uint96 weight;
uint16 tokenID;
}
struct Context
{
// functional parameters
uint txIdx;
// Exchange state variables
IExchangeV3 exchange;
bytes32 exchangeDomainSeparator;
// AMM pool state variables
bytes32 domainSeparator;
uint32 accountID;
uint16 poolTokenID;
uint totalSupply;
Token[] tokens;
uint96[] tokenBalancesL2;
TransactionBuffer transactionBuffer;
}
struct TransactionBuffer
{
uint size;
address[] owners;
bytes32[] txHashes;
}
struct State {
// Pool token state variables
string poolName;
string symbol;
uint _totalSupply;
mapping(address => uint) balanceOf;
mapping(address => mapping(address => uint)) allowance;
mapping(address => uint) nonces;
// AMM pool state variables
IAmmSharedConfig sharedConfig;
Token[] tokens;
// The order of the following variables important to minimize loads
bytes32 exchangeDomainSeparator;
bytes32 domainSeparator;
IExchangeV3 exchange;
uint32 accountID;
uint16 poolTokenID;
uint8 feeBips;
address exchangeOwner;
uint64 shutdownTimestamp;
uint16 forcedExitCount;
// A map from a user to the forced exit.
mapping (address => PoolExit) forcedExit;
mapping (bytes32 => bool) approvedTx;
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title AmmPoolToken
library AmmPoolToken
{
using MathUint for uint;
using MathUint96 for uint96;
using SignatureUtil for bytes32;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
function totalSupply(
AmmData.State storage S
)
internal
view
returns (uint)
{
return S._totalSupply;
}
function approve(
AmmData.State storage S,
address spender,
uint value
)
internal
returns (bool)
{
_approve(S, msg.sender, spender, value);
return true;
}
function transfer(
AmmData.State storage S,
address to,
uint value
)
internal
returns (bool)
{
_transfer(S, msg.sender, to, value);
return true;
}
function transferFrom(
AmmData.State storage S,
address from,
address to,
uint value
)
internal
returns (bool)
{
if (msg.sender != address(this) &&
S.allowance[from][msg.sender] != uint(-1)) {
S.allowance[from][msg.sender] = S.allowance[from][msg.sender].sub(value);
}
_transfer(S, from, to, value);
return true;
}
function permit(
AmmData.State storage S,
address owner,
address spender,
uint256 value,
uint256 deadline,
bytes calldata signature
)
internal
{
require(deadline >= block.timestamp, 'EXPIRED');
bytes32 hash = EIP712.hashPacked(
S.domainSeparator,
keccak256(
abi.encode(
PERMIT_TYPEHASH,
owner,
spender,
value,
S.nonces[owner]++,
deadline
)
)
);
require(hash.verifySignature(owner, signature), 'INVALID_SIGNATURE');
_approve(S, owner, spender, value);
}
function _approve(
AmmData.State storage S,
address owner,
address spender,
uint value
)
private
{
if (spender != address(this)) {
S.allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
}
function _transfer(
AmmData.State storage S,
address from,
address to,
uint value
)
private
{
S.balanceOf[from] = S.balanceOf[from].sub(value);
S.balanceOf[to] = S.balanceOf[to].add(value);
emit Transfer(from, to, value);
}
}
// Copyright 2017 Loopring Technology Limited.
// Copyright 2017 Loopring Technology Limited.
/// @title AmmStatus
library AmmStatus
{
using AmmPoolToken for AmmData.State;
using MathUint for uint;
using MathUint96 for uint96;
using SignatureUtil for bytes32;
event Shutdown(uint timestamp);
function isOnline(AmmData.State storage S)
internal
view
returns (bool)
{
return S.shutdownTimestamp == 0;
}
function setupPool(
AmmData.State storage S,
AmmData.PoolConfig calldata config
)
public
{
require(
bytes(config.poolName).length > 0 && bytes(config.tokenSymbol).length > 0,
"INVALID_NAME_OR_SYMBOL"
);
require(config.sharedConfig != address(0), "INVALID_SHARED_CONFIG");
require(config.tokens.length == config.weights.length, "INVALID_DATA");
require(config.tokens.length >= 2, "INVALID_DATA");
require(config.exchange != address(0), "INVALID_EXCHANGE");
require(config.accountID != 0, "INVALID_ACCOUNT_ID");
require(S.tokens.length == 0, "ALREADY_INITIALIZED");
S.sharedConfig = IAmmSharedConfig(config.sharedConfig);
IExchangeV3 exchange = IExchangeV3(config.exchange);
S.exchange = exchange;
S.exchangeOwner = exchange.owner();
S.exchangeDomainSeparator = exchange.getDomainSeparator();
S.accountID = config.accountID;
S.poolTokenID = exchange.getTokenID(address(this));
S.feeBips = config.feeBips;
S.domainSeparator = EIP712.hash(EIP712.Domain(config.poolName, "1.0.0", address(this)));
S.poolName = config.poolName;
S.symbol = config.tokenSymbol;
for (uint i = 0; i < config.tokens.length; i++) {
require(config.weights[i] > 0, "INVALID_TOKEN_WEIGHT");
address token = config.tokens[i];
S.tokens.push(AmmData.Token({
addr: token,
tokenID: exchange.getTokenID(token),
weight: config.weights[i]
}));
}
// Mint all liquidity tokens to the pool account on L2
S.balanceOf[address(this)] = AmmData.POOL_TOKEN_MINTED_SUPPLY();
S.allowance[address(this)][address(exchange.getDepositContract())] = uint(-1);
exchange.deposit(
address(this), // from
address(this), // to
address(this), // token
uint96(AmmData.POOL_TOKEN_MINTED_SUPPLY()),
new bytes(0)
);
}
// Anyone is able to shut down the pool when requests aren't being processed any more.
function shutdown(
AmmData.State storage S,
address exitOwner
)
public
{
// If the exchange is in withdrawal mode allow the pool to be shutdown immediately
if (!S.exchange.isInWithdrawalMode()) {
uint64 validUntil = S.forcedExit[exitOwner].validUntil;
require(validUntil > 0 && validUntil < block.timestamp, "INVALID_CHALLENGE");
uint size = S.tokens.length;
for (uint i = 0; i < size; i++) {
S.exchange.forceWithdraw{value: msg.value / size}(
address(this),
S.tokens[i].addr,
S.accountID
);
}
}
S.shutdownTimestamp = uint64(block.timestamp);
emit Shutdown(block.timestamp);
}
// Anyone is able to update the cached exchange owner to the current owner.
function updateExchangeOwner(AmmData.State storage S)
public
{
S.exchangeOwner = S.exchange.owner();
}
}
// Copyright 2017 Loopring Technology Limited.
// Copyright 2017 Loopring Technology Limited.
// Copyright 2017 Loopring Technology Limited.
// Taken from https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/SafeCast.sol
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such 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.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value < 2**96, "SafeCast: value doesn\'t fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint40 from uint256, reverting on
* overflow (when the input is greater than largest uint40).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 40 bits
*/
function toUint40(uint256 value) internal pure returns (uint40) {
require(value < 2**40, "SafeCast: value doesn\'t fit in 40 bits");
return uint40(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
require(value < 2**255, "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
/// @title Utility Functions for floats
/// @author Brecht Devos - <[email protected]>
library FloatUtil
{
using MathUint for uint;
using SafeCast for uint;
// Decodes a decimal float value that is encoded like `exponent | mantissa`.
// Both exponent and mantissa are in base 10.
// Decoding to an integer is as simple as `mantissa * (10 ** exponent)`
// Will throw when the decoded value overflows an uint96
/// @param f The float value with 5 bits for the exponent
/// @param numBits The total number of bits (numBitsMantissa := numBits - numBitsExponent)
/// @return value The decoded integer value.
function decodeFloat(
uint f,
uint numBits
)
internal
pure
returns (uint96 value)
{
uint numBitsMantissa = numBits.sub(5);
uint exponent = f >> numBitsMantissa;
// log2(10**77) = 255.79 < 256
require(exponent <= 77, "EXPONENT_TOO_LARGE");
uint mantissa = f & ((1 << numBitsMantissa) - 1);
value = mantissa.mul(10 ** exponent).toUint96();
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title ExchangeSignatures.
/// @dev All methods in this lib are internal, therefore, there is no need
/// to deploy this library independently.
/// @author Brecht Devos - <[email protected]>
/// @author Daniel Wang - <[email protected]>
library ExchangeSignatures
{
using SignatureUtil for bytes32;
function requireAuthorizedTx(
ExchangeData.State storage S,
address signer,
bytes memory signature,
bytes32 txHash
)
internal // inline call
{
require(signer != address(0), "INVALID_SIGNER");
// Verify the signature if one is provided, otherwise fall back to an approved tx
if (signature.length > 0) {
require(txHash.verifySignature(signer, signature), "INVALID_SIGNATURE");
} else {
require(S.approvedTx[signer][txHash], "TX_NOT_APPROVED");
delete S.approvedTx[signer][txHash];
}
}
}
/// @title TransferTransaction
/// @author Brecht Devos - <[email protected]>
library TransferTransaction
{
using BytesUtil for bytes;
using FloatUtil for uint;
using MathUint for uint;
using ExchangeSignatures for ExchangeData.State;
bytes32 constant public TRANSFER_TYPEHASH = keccak256(
"Transfer(address from,address to,uint16 tokenID,uint96 amount,uint16 feeTokenID,uint96 maxFee,uint32 validUntil,uint32 storageID)"
);
struct Transfer
{
uint32 fromAccountID;
uint32 toAccountID;
address from;
address to;
uint16 tokenID;
uint96 amount;
uint16 feeTokenID;
uint96 maxFee;
uint96 fee;
uint32 validUntil;
uint32 storageID;
}
// Auxiliary data for each transfer
struct TransferAuxiliaryData
{
bytes signature;
uint96 maxFee;
uint32 validUntil;
}
/*event ConditionalTransferProcessed(
address from,
address to,
uint16 token,
uint amount
);*/
function process(
ExchangeData.State storage S,
ExchangeData.BlockContext memory ctx,
bytes memory data,
uint offset,
bytes memory auxiliaryData
)
internal
{
// Read the transfer
Transfer memory transfer = readTx(data, offset);
TransferAuxiliaryData memory auxData = abi.decode(auxiliaryData, (TransferAuxiliaryData));
// Fill in withdrawal data missing from DA
transfer.validUntil = auxData.validUntil;
transfer.maxFee = auxData.maxFee == 0 ? transfer.fee : auxData.maxFee;
// Validate
require(ctx.timestamp < transfer.validUntil, "TRANSFER_EXPIRED");
require(transfer.fee <= transfer.maxFee, "TRANSFER_FEE_TOO_HIGH");
// Calculate the tx hash
bytes32 txHash = hashTx(ctx.DOMAIN_SEPARATOR, transfer);
// Check the on-chain authorization
S.requireAuthorizedTx(transfer.from, auxData.signature, txHash);
//emit ConditionalTransferProcessed(from, to, tokenID, amount);
}
function readTx(
bytes memory data,
uint offset
)
internal
pure
returns (Transfer memory transfer)
{
uint _offset = offset;
// Check that this is a conditional transfer
require(data.toUint8(_offset) == 1, "INVALID_AUXILIARYDATA_DATA");
_offset += 1;
// Extract the transfer data
// We don't use abi.decode for this because of the large amount of zero-padding
// bytes the circuit would also have to hash.
transfer.fromAccountID = data.toUint32(_offset);
_offset += 4;
transfer.toAccountID = data.toUint32(_offset);
_offset += 4;
transfer.tokenID = data.toUint16(_offset);
_offset += 2;
transfer.amount = uint(data.toUint24(_offset)).decodeFloat(24);
_offset += 3;
transfer.feeTokenID = data.toUint16(_offset);
_offset += 2;
transfer.fee = uint(data.toUint16(_offset)).decodeFloat(16);
_offset += 2;
transfer.storageID = data.toUint32(_offset);
_offset += 4;
transfer.to = data.toAddress(_offset);
_offset += 20;
transfer.from = data.toAddress(_offset);
_offset += 20;
}
function hashTx(
bytes32 DOMAIN_SEPARATOR,
Transfer memory transfer
)
internal
pure
returns (bytes32)
{
return EIP712.hashPacked(
DOMAIN_SEPARATOR,
keccak256(
abi.encode(
TRANSFER_TYPEHASH,
transfer.from,
transfer.to,
transfer.tokenID,
transfer.amount,
transfer.feeTokenID,
transfer.maxFee,
transfer.validUntil,
transfer.storageID
)
)
);
}
}
// Copyright 2017 Loopring Technology Limited.
/// @title ERC20 safe transfer
/// @dev see https://github.com/sec-bit/badERC20Fix
/// @author Brecht Devos - <[email protected]>
library ERC20SafeTransfer
{
function safeTransferAndVerify(
address token,
address to,
uint value
)
internal
{
safeTransferWithGasLimitAndVerify(
token,
to,
value,
gasleft()
);
}
function safeTransfer(
address token,
address to,
uint value
)
internal
returns (bool)
{
return safeTransferWithGasLimit(
token,
to,
value,
gasleft()
);
}
function safeTransferWithGasLimitAndVerify(
address token,
address to,
uint value,
uint gasLimit
)
internal
{
require(
safeTransferWithGasLimit(token, to, value, gasLimit),
"TRANSFER_FAILURE"
);
}
function safeTransferWithGasLimit(
address token,
address to,
uint value,
uint gasLimit
)
internal
returns (bool)
{
// A transfer is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
// bytes4(keccak256("transfer(address,uint256)")) = 0xa9059cbb
bytes memory callData = abi.encodeWithSelector(
bytes4(0xa9059cbb),
to,
value
);
(bool success, ) = token.call{gas: gasLimit}(callData);
return checkReturnValue(success);
}
function safeTransferFromAndVerify(
address token,
address from,
address to,
uint value
)
internal
{
safeTransferFromWithGasLimitAndVerify(
token,
from,
to,
value,
gasleft()
);
}
function safeTransferFrom(
address token,
address from,
address to,
uint value
)
internal
returns (bool)
{
return safeTransferFromWithGasLimit(
token,
from,
to,
value,
gasleft()
);
}
function safeTransferFromWithGasLimitAndVerify(
address token,
address from,
address to,
uint value,
uint gasLimit
)
internal
{
bool result = safeTransferFromWithGasLimit(
token,
from,
to,
value,
gasLimit
);
require(result, "TRANSFER_FAILURE");
}
function safeTransferFromWithGasLimit(
address token,
address from,
address to,
uint value,
uint gasLimit
)
internal
returns (bool)
{
// A transferFrom is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
// bytes4(keccak256("transferFrom(address,address,uint256)")) = 0x23b872dd
bytes memory callData = abi.encodeWithSelector(
bytes4(0x23b872dd),
from,
to,
value
);
(bool success, ) = token.call{gas: gasLimit}(callData);
return checkReturnValue(success);
}
function checkReturnValue(
bool success
)
internal
pure
returns (bool)
{
// A transfer/transferFrom is successful when 'call' is successful and depending on the token:
// - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false)
// - A single boolean is returned: this boolean needs to be true (non-zero)
if (success) {
assembly {
switch returndatasize()
// Non-standard ERC20: nothing is returned so if 'call' was successful we assume the transfer succeeded
case 0 {
success := 1
}
// Standard ERC20: a single boolean value is returned which needs to be true
case 32 {
returndatacopy(0, 0, 32)
success := mload(0)
}
// None of the above: not successful
default {
success := 0
}
}
}
return success;
}
}
/// @title AmmUtil
library AmmUtil
{
using AddressUtil for address;
using ERC20SafeTransfer for address;
using MathUint for uint;
function approveTransfer(
AmmData.Context memory ctx,
TransferTransaction.Transfer memory transfer
)
internal
pure
{
transfer.validUntil = 0xffffffff;
transfer.maxFee = transfer.fee;
bytes32 hash = TransferTransaction.hashTx(ctx.exchangeDomainSeparator, transfer);
approveExchangeTransaction(ctx.transactionBuffer, transfer.from, hash);
}
function approveExchangeTransaction(
AmmData.TransactionBuffer memory buffer,
address owner,
bytes32 txHash
)
internal
pure
{
buffer.owners[buffer.size] = owner;
buffer.txHashes[buffer.size] = txHash;
buffer.size++;
}
function isAlmostEqualAmount(
uint96 amount,
uint96 targetAmount
)
internal
pure
returns (bool)
{
if (targetAmount == 0) {
return amount == 0;
} else {
// Max rounding error for a float24 is 2/100000
uint ratio = (amount * 100000) / targetAmount;
return (100000 - 2) <= ratio && ratio <= (100000 + 2);
}
}
function isAlmostEqualFee(
uint96 amount,
uint96 targetAmount
)
internal
pure
returns (bool)
{
if (targetAmount == 0) {
return amount == 0;
} else {
// Max rounding error for a float16 is 5/1000
uint ratio = (amount * 1000) / targetAmount;
return (1000 - 5) <= ratio && ratio <= (1000 + 5);
}
}
function transferIn(
address token,
uint amount
)
internal
{
if (token == address(0)) {
require(msg.value == amount, "INVALID_ETH_VALUE");
} else if (amount > 0) {
token.safeTransferFromAndVerify(msg.sender, address(this), amount);
}
}
function transferOut(
address token,
uint amount,
address to
)
internal
{
if (token == address(0)) {
to.sendETHAndVerify(amount, gasleft());
} else {
token.safeTransferAndVerify(to, amount);
}
}
}
/// @title AmmWithdrawal
library AmmWithdrawal
{
using AmmPoolToken for AmmData.State;
using AmmStatus for AmmData.State;
using MathUint for uint;
function withdrawWhenOffline(
AmmData.State storage S
)
public
{
_checkWithdrawalConditionInShutdown(S);
// Burn the full balance
uint poolAmount = S.balanceOf[msg.sender];
if (poolAmount > 0) {
S.transfer(address(this), poolAmount);
}
// Burn any additional pool tokens stuck in forced exits
AmmData.PoolExit storage exit = S.forcedExit[msg.sender];
if (exit.burnAmount > 0) {
poolAmount = poolAmount.add(exit.burnAmount);
delete S.forcedExit[msg.sender];
}
require(poolAmount > 0, "ZERO_POOL_AMOUNT");
// Withdraw the part owned of the pool
uint totalSupply = S.totalSupply();
for (uint i = 0; i < S.tokens.length; i++) {
address token = S.tokens[i].addr;
uint balance = token == address(0) ?
address(this).balance :
ERC20(token).balanceOf(address(this));
uint amount = balance.mul(poolAmount) / totalSupply;
AmmUtil.transferOut(token, amount, msg.sender);
}
S._totalSupply = S._totalSupply.sub(poolAmount);
}
function _checkWithdrawalConditionInShutdown(
AmmData.State storage S
)
private
view
{
IExchangeV3 exchange = S.exchange;
bool withdrawalMode = exchange.isInWithdrawalMode();
for (uint i = 0; i < S.tokens.length; i++) {
address token = S.tokens[i].addr;
require(
withdrawalMode && exchange.isWithdrawnInWithdrawalMode(S.accountID, token) ||
!withdrawalMode && !exchange.isForcedWithdrawalPending(S.accountID, token),
"PENDING_WITHDRAWAL"
);
// Check that nothing is withdrawable anymore.
require(
exchange.getAmountWithdrawable(address(this), token) == 0,
"MORE_TO_WITHDRAW"
);
}
}
} | Check that this is a conditional transfer Extract the transfer data We don't use abi.decode for this because of the large amount of zero-padding bytes the circuit would also have to hash. | function readTx(
bytes memory data,
uint offset
)
internal
pure
returns (Transfer memory transfer)
{
uint _offset = offset;
require(data.toUint8(_offset) == 1, "INVALID_AUXILIARYDATA_DATA");
_offset += 1;
transfer.fromAccountID = data.toUint32(_offset);
_offset += 4;
transfer.toAccountID = data.toUint32(_offset);
_offset += 4;
transfer.tokenID = data.toUint16(_offset);
_offset += 2;
transfer.amount = uint(data.toUint24(_offset)).decodeFloat(24);
_offset += 3;
transfer.feeTokenID = data.toUint16(_offset);
_offset += 2;
transfer.fee = uint(data.toUint16(_offset)).decodeFloat(16);
_offset += 2;
transfer.storageID = data.toUint32(_offset);
_offset += 4;
transfer.to = data.toAddress(_offset);
_offset += 20;
transfer.from = data.toAddress(_offset);
_offset += 20;
}
| 615,561 |
/*
Copyright 2017 Loopring Project Ltd (Loopring Foundation).
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.4.19;
/// @title Utility Functions for uint8
/// @author Kongliang Zhong - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ddb6b2b3bab1b4bcb3ba9db1b2b2adafb4b3baf3b2afba">[email protected]</a>>,
/// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="5430353a3d313814383b3b24263d3a337a3b2633">[email protected]</a>>.
library MathUint8 {
function xorReduce(
uint8[] arr,
uint len
)
internal
pure
returns (uint8 res)
{
res = arr[0];
for (uint i = 1; i < len; i++) {
res ^= arr[i];
}
}
}
/*
Copyright 2017 Loopring Project Ltd (Loopring Foundation).
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 Utility Functions for uint
/// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="264247484f434a664a494956544f484108495441">[email protected]</a>>
library MathUint {
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function sub(uint a, uint b) internal pure returns (uint) {
require(b <= a);
return a - b;
}
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function tolerantSub(uint a, uint b) internal pure returns (uint c) {
return (a >= b) ? a - b : 0;
}
/// @dev calculate the square of Coefficient of Variation (CV)
/// https://en.wikipedia.org/wiki/Coefficient_of_variation
function cvsquare(
uint[] arr,
uint scale
)
internal
pure
returns (uint)
{
uint len = arr.length;
require(len > 1);
require(scale > 0);
uint avg = 0;
for (uint i = 0; i < len; i++) {
avg += arr[i];
}
avg = avg / len;
if (avg == 0) {
return 0;
}
uint cvs = 0;
uint s;
uint item;
for (i = 0; i < len; i++) {
item = arr[i];
s = item > avg ? item - avg : avg - item;
cvs += mul(s, s);
}
return ((mul(mul(cvs, scale), scale) / avg) / avg) / (len - 1);
}
}
/*
Copyright 2017 Loopring Project Ltd (Loopring Foundation).
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 Utility Functions for byte32
/// @author Kongliang Zhong - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="83e8ecede4efeae2ede4c3efececf3f1eaede4adecf1e4">[email protected]</a>>,
/// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="573336393e323b173b383827253e393079382530">[email protected]</a>>.
library MathBytes32 {
function xorReduce(
bytes32[] arr,
uint len
)
internal
pure
returns (bytes32 res)
{
res = arr[0];
for (uint i = 1; i < len; i++) {
res ^= arr[i];
}
}
}
/*
Copyright 2017 Loopring Project Ltd (Loopring Foundation).
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.
*/
/*
Copyright 2017 Loopring Project Ltd (Loopring Foundation).
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 ERC20 Token Interface
/// @dev see https://github.com/ethereum/EIPs/issues/20
/// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="593d3837303c3519353636292b30373e77362b3e">[email protected]</a>>
contract ERC20 {
uint public totalSupply;
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function balanceOf(address who) view public returns (uint256);
function allowance(address owner, address spender) view public returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
}
/*
Copyright 2017 Loopring Project Ltd (Loopring Foundation).
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 Loopring Token Exchange Protocol Contract Interface
/// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="afcbcec1c6cac3efc3c0c0dfddc6c1c881c0ddc8">[email protected]</a>>
/// @author Kongliang Zhong - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="cca7a3a2aba0a5ada2ab8ca0a3a3bcbea5a2abe2a3beab">[email protected]</a>>
contract LoopringProtocol {
////////////////////////////////////////////////////////////////////////////
/// Constants ///
////////////////////////////////////////////////////////////////////////////
uint8 public constant MARGIN_SPLIT_PERCENTAGE_BASE = 100;
////////////////////////////////////////////////////////////////////////////
/// Events ///
////////////////////////////////////////////////////////////////////////////
/// @dev Event to emit if a ring is successfully mined.
/// _amountsList is an array of:
/// [_amountS, _amountB, _lrcReward, _lrcFee, splitS, splitB].
event RingMined(
uint _ringIndex,
bytes32 indexed _ringHash,
address _miner,
address _feeRecipient,
bytes32[] _orderHashList,
uint[6][] _amountsList
);
event OrderCancelled(
bytes32 indexed _orderHash,
uint _amountCancelled
);
event AllOrdersCancelled(
address indexed _address,
uint _cutoff
);
event OrdersCancelled(
address indexed _address,
address _token1,
address _token2,
uint _cutoff
);
////////////////////////////////////////////////////////////////////////////
/// Functions ///
////////////////////////////////////////////////////////////////////////////
/// @dev Cancel a order. cancel amount(amountS or amountB) can be specified
/// in orderValues.
/// @param addresses owner, tokenS, tokenB, authAddr
/// @param orderValues amountS, amountB, validSince (second),
/// validUntil (second), lrcFee, walletId, and
/// cancelAmount.
/// @param buyNoMoreThanAmountB -
/// This indicates when a order should be considered
/// as 'completely filled'.
/// @param marginSplitPercentage -
/// Percentage of margin split to share with miner.
/// @param v Order ECDSA signature parameter v.
/// @param r Order ECDSA signature parameters r.
/// @param s Order ECDSA signature parameters s.
function cancelOrder(
address[4] addresses,
uint[7] orderValues,
bool buyNoMoreThanAmountB,
uint8 marginSplitPercentage,
uint8 v,
bytes32 r,
bytes32 s
) external;
/// @dev Set a cutoff timestamp to invalidate all orders whose timestamp
/// is smaller than or equal to the new value of the address's cutoff
/// timestamp, for a specific trading pair.
/// @param cutoff The cutoff timestamp, will default to `block.timestamp`
/// if it is 0.
function cancelAllOrdersByTradingPair(
address token1,
address token2,
uint cutoff
) external;
/// @dev Set a cutoff timestamp to invalidate all orders whose timestamp
/// is smaller than or equal to the new value of the address's cutoff
/// timestamp.
/// @param cutoff The cutoff timestamp, will default to `block.timestamp`
/// if it is 0.
function cancelAllOrders(uint cutoff) external;
/// @dev Submit a order-ring for validation and settlement.
/// @param addressList List of each order's owner, tokenS, and authAddr.
/// Note that next order's `tokenS` equals this order's
/// `tokenB`.
/// @param uintArgsList List of uint-type arguments in this order:
/// amountS, amountB, validSince (second),
/// validUntil (second), lrcFee, rateAmountS, and walletId.
/// @param uint8ArgsList -
/// List of unit8-type arguments, in this order:
/// marginSplitPercentageList.
/// @param buyNoMoreThanAmountBList -
/// This indicates when a order should be considered
/// @param vList List of v for each order. This list is 1-larger than
/// the previous lists, with the last element being the
/// v value of the ring signature.
/// @param rList List of r for each order. This list is 1-larger than
/// the previous lists, with the last element being the
/// r value of the ring signature.
/// @param sList List of s for each order. This list is 1-larger than
/// the previous lists, with the last element being the
/// s value of the ring signature.
/// @param minerId The address pair that miner registered in NameRegistry.
/// The address pair contains a signer address and a fee
/// recipient address.
/// The signer address is used for sign this tx.
/// The Recipient address for fee collection. If this is
/// '0x0', all fees will be paid to the address who had
/// signed this transaction, not `msg.sender`. Noted if
/// LRC need to be paid back to order owner as the result
/// of fee selection model, LRC will also be sent from
/// this address.
/// @param feeSelections -
/// Bits to indicate fee selections. `1` represents margin
/// split and `0` represents LRC as fee.
function submitRing(
address[3][] addressList,
uint[7][] uintArgsList,
uint8[1][] uint8ArgsList,
bool[] buyNoMoreThanAmountBList,
uint8[] vList,
bytes32[] rList,
bytes32[] sList,
uint minerId,
uint16 feeSelections
) public;
}
/*
Copyright 2017 Loopring Project Ltd (Loopring Foundation).
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 Ethereum Address Register Contract
/// @dev This contract maintains a name service for addresses and miner.
/// @author Kongliang Zhong - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b2d9dddcd5dedbd3dcd5f2deddddc2c0dbdcd59cddc0d5">[email protected]</a>>,
/// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6400050a0d010824080b0b14160d0a034a0b1603">[email protected]</a>>,
contract NameRegistry {
uint public nextId = 0;
mapping (uint => Participant) public participantMap;
mapping (address => NameInfo) public nameInfoMap;
mapping (bytes12 => address) public ownerMap;
mapping (address => string) public nameMap;
struct NameInfo {
bytes12 name;
uint[] participantIds;
}
struct Participant {
address feeRecipient;
address signer;
bytes12 name;
address owner;
}
event NameRegistered (
string name,
address indexed owner
);
event NameUnregistered (
string name,
address indexed owner
);
event OwnershipTransfered (
bytes12 name,
address oldOwner,
address newOwner
);
event ParticipantRegistered (
bytes12 name,
address indexed owner,
uint indexed participantId,
address singer,
address feeRecipient
);
event ParticipantUnregistered (
uint participantId,
address owner
);
function registerName(string name)
external
{
require(isNameValid(name));
bytes12 nameBytes = stringToBytes12(name);
require(ownerMap[nameBytes] == 0x0);
require(stringToBytes12(nameMap[msg.sender]) == bytes12(0x0));
nameInfoMap[msg.sender] = NameInfo(nameBytes, new uint[](0));
ownerMap[nameBytes] = msg.sender;
nameMap[msg.sender] = name;
NameRegistered(name, msg.sender);
}
function unregisterName(string name)
external
{
NameInfo storage nameInfo = nameInfoMap[msg.sender];
uint[] storage participantIds = nameInfo.participantIds;
bytes12 nameBytes = stringToBytes12(name);
require(nameInfo.name == nameBytes);
for (uint i = participantIds.length - 1; i >= 0; i--) {
delete participantMap[participantIds[i]];
}
delete nameInfoMap[msg.sender];
delete nameMap[msg.sender];
delete ownerMap[nameBytes];
NameUnregistered(name, msg.sender);
}
function transferOwnership(address newOwner)
external
{
require(newOwner != 0x0);
require(nameInfoMap[newOwner].name.length == 0);
NameInfo storage nameInfo = nameInfoMap[msg.sender];
string storage name = nameMap[msg.sender];
uint[] memory participantIds = nameInfo.participantIds;
for (uint i = 0; i < participantIds.length; i ++) {
Participant storage p = participantMap[participantIds[i]];
p.owner = newOwner;
}
delete nameInfoMap[msg.sender];
delete nameMap[msg.sender];
nameInfoMap[newOwner] = nameInfo;
nameMap[newOwner] = name;
OwnershipTransfered(nameInfo.name, msg.sender, newOwner);
}
/* function addParticipant(address feeRecipient) */
/* external */
/* returns (uint) */
/* { */
/* return addParticipant(feeRecipient, feeRecipient); */
/* } */
function addParticipant(
address feeRecipient,
address singer
)
external
returns (uint)
{
require(feeRecipient != 0x0 && singer != 0x0);
NameInfo storage nameInfo = nameInfoMap[msg.sender];
bytes12 name = nameInfo.name;
require(name.length > 0);
Participant memory participant = Participant(
feeRecipient,
singer,
name,
msg.sender
);
uint participantId = ++nextId;
participantMap[participantId] = participant;
nameInfo.participantIds.push(participantId);
ParticipantRegistered(
name,
msg.sender,
participantId,
singer,
feeRecipient
);
return participantId;
}
function removeParticipant(uint participantId)
external
{
require(msg.sender == participantMap[participantId].owner);
NameInfo storage nameInfo = nameInfoMap[msg.sender];
uint[] storage participantIds = nameInfo.participantIds;
delete participantMap[participantId];
uint len = participantIds.length;
for (uint i = 0; i < len; i ++) {
if (participantId == participantIds[i]) {
participantIds[i] = participantIds[len - 1];
participantIds.length -= 1;
}
}
ParticipantUnregistered(participantId, msg.sender);
}
function getParticipantById(uint id)
external
view
returns (address feeRecipient, address signer)
{
Participant storage addressSet = participantMap[id];
feeRecipient = addressSet.feeRecipient;
signer = addressSet.signer;
}
function getParticipantIds(string name, uint start, uint count)
external
view
returns (uint[] idList)
{
bytes12 nameBytes = stringToBytes12(name);
address owner = ownerMap[nameBytes];
require(owner != 0x0);
NameInfo storage nameInfo = nameInfoMap[owner];
uint[] storage pIds = nameInfo.participantIds;
uint len = pIds.length;
if (start >= len) {
return;
}
uint end = start + count;
if (end > len) {
end = len;
}
if (start == end) {
return;
}
idList = new uint[](end - start);
for (uint i = start; i < end; i ++) {
idList[i - start] = pIds[i];
}
}
function getOwner(string name)
external
view
returns (address)
{
bytes12 nameBytes = stringToBytes12(name);
return ownerMap[nameBytes];
}
function isNameValid(string name)
internal
pure
returns (bool)
{
bytes memory temp = bytes(name);
return temp.length >= 6 && temp.length <= 12;
}
function stringToBytes12(string str)
internal
pure
returns (bytes12 result)
{
assembly {
result := mload(add(str, 12))
}
}
}
/*
Copyright 2017 Loopring Project Ltd (Loopring Foundation).
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.
*/
/*
Copyright 2017 Loopring Project Ltd (Loopring Foundation).
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.
*/
/*
Copyright 2017 Loopring Project Ltd (Loopring Foundation).
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 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.
function Ownable() public {
owner = msg.sender;
}
/// @dev Throws if called by any account other than the owner.
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/// @dev Allows the current owner to transfer control of the contract to a
/// newOwner.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != 0x0);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/// @title Claimable
/// @dev Extension for the Ownable contract, where the ownership needs
/// to be claimed. This allows the new owner to accept the transfer.
contract Claimable is Ownable {
address public pendingOwner;
/// @dev Modifier throws if called by any account other than the pendingOwner.
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/// @dev Allows the current owner to set the pendingOwner address.
/// @param newOwner The address to transfer ownership to.
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != 0x0 && newOwner != owner);
pendingOwner = newOwner;
}
/// @dev Allows the pendingOwner address to finalize the transfer.
function claimOwnership() onlyPendingOwner public {
OwnershipTransferred(owner, pendingOwner);
owner = pendingOwner;
pendingOwner = 0x0;
}
}
/// @title Token Register Contract
/// @dev This contract maintains a list of tokens the Protocol supports.
/// @author Kongliang Zhong - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="72191d1c151e1b131c15321e1d1d02001b1c155c1d0015">[email protected]</a>>,
/// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="7014111e19151c301c1f1f0002191e175e1f0217">[email protected]</a>>.
contract TokenRegistry is Claimable {
address[] public addresses;
mapping (address => TokenInfo) addressMap;
mapping (string => address) symbolMap;
////////////////////////////////////////////////////////////////////////////
/// Structs ///
////////////////////////////////////////////////////////////////////////////
struct TokenInfo {
uint pos; // 0 mens unregistered; if > 0, pos + 1 is the
// token's position in `addresses`.
string symbol; // Symbol of the token
}
////////////////////////////////////////////////////////////////////////////
/// Events ///
////////////////////////////////////////////////////////////////////////////
event TokenRegistered(address addr, string symbol);
event TokenUnregistered(address addr, string symbol);
////////////////////////////////////////////////////////////////////////////
/// Public Functions ///
////////////////////////////////////////////////////////////////////////////
/// @dev Disable default function.
function () payable public {
revert();
}
function registerToken(
address addr,
string symbol
)
external
onlyOwner
{
require(0x0 != addr);
require(bytes(symbol).length > 0);
require(0x0 == symbolMap[symbol]);
require(0 == addressMap[addr].pos);
addresses.push(addr);
symbolMap[symbol] = addr;
addressMap[addr] = TokenInfo(addresses.length, symbol);
TokenRegistered(addr, symbol);
}
function unregisterToken(
address addr,
string symbol
)
external
onlyOwner
{
require(addr != 0x0);
require(symbolMap[symbol] == addr);
delete symbolMap[symbol];
uint pos = addressMap[addr].pos;
require(pos != 0);
delete addressMap[addr];
// We will replace the token we need to unregister with the last token
// Only the pos of the last token will need to be updated
address lastToken = addresses[addresses.length - 1];
// Don't do anything if the last token is the one we want to delete
if (addr != lastToken) {
// Swap with the last token and update the pos
addresses[pos - 1] = lastToken;
addressMap[lastToken].pos = pos;
}
addresses.length--;
TokenUnregistered(addr, symbol);
}
function areAllTokensRegistered(address[] addressList)
external
view
returns (bool)
{
for (uint i = 0; i < addressList.length; i++) {
if (addressMap[addressList[i]].pos == 0) {
return false;
}
}
return true;
}
function getAddressBySymbol(string symbol)
external
view
returns (address)
{
return symbolMap[symbol];
}
function isTokenRegisteredBySymbol(string symbol)
public
view
returns (bool)
{
return symbolMap[symbol] != 0x0;
}
function isTokenRegistered(address addr)
public
view
returns (bool)
{
return addressMap[addr].pos != 0;
}
function getTokens(
uint start,
uint count
)
public
view
returns (address[] addressList)
{
uint num = addresses.length;
if (start >= num) {
return;
}
uint end = start + count;
if (end > num) {
end = num;
}
if (start == num) {
return;
}
addressList = new address[](end - start);
for (uint i = start; i < end; i++) {
addressList[i - start] = addresses[i];
}
}
}
/*
Copyright 2017 Loopring Project Ltd (Loopring Foundation).
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 TokenTransferDelegate
/// @dev Acts as a middle man to transfer ERC20 tokens on behalf of different
/// versions of Loopring protocol to avoid ERC20 re-authorization.
/// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="eb8f8a85828e87ab8784849b9982858cc584998c">[email protected]</a>>.
contract TokenTransferDelegate is Claimable {
using MathUint for uint;
////////////////////////////////////////////////////////////////////////////
/// Variables ///
////////////////////////////////////////////////////////////////////////////
mapping(address => AddressInfo) private addressInfos;
address public latestAddress;
////////////////////////////////////////////////////////////////////////////
/// Structs ///
////////////////////////////////////////////////////////////////////////////
struct AddressInfo {
address previous;
uint32 index;
bool authorized;
}
////////////////////////////////////////////////////////////////////////////
/// Modifiers ///
////////////////////////////////////////////////////////////////////////////
modifier onlyAuthorized() {
require(addressInfos[msg.sender].authorized);
_;
}
////////////////////////////////////////////////////////////////////////////
/// Events ///
////////////////////////////////////////////////////////////////////////////
event AddressAuthorized(address indexed addr, uint32 number);
event AddressDeauthorized(address indexed addr, uint32 number);
////////////////////////////////////////////////////////////////////////////
/// Public Functions ///
////////////////////////////////////////////////////////////////////////////
/// @dev Disable default function.
function () payable public {
revert();
}
/// @dev Add a Loopring protocol address.
/// @param addr A loopring protocol address.
function authorizeAddress(address addr)
onlyOwner
external
{
AddressInfo storage addrInfo = addressInfos[addr];
if (addrInfo.index != 0) { // existing
if (addrInfo.authorized == false) { // re-authorize
addrInfo.authorized = true;
AddressAuthorized(addr, addrInfo.index);
}
} else {
address prev = latestAddress;
if (prev == 0x0) {
addrInfo.index = 1;
addrInfo.authorized = true;
} else {
addrInfo.previous = prev;
addrInfo.index = addressInfos[prev].index + 1;
}
addrInfo.authorized = true;
latestAddress = addr;
AddressAuthorized(addr, addrInfo.index);
}
}
/// @dev Remove a Loopring protocol address.
/// @param addr A loopring protocol address.
function deauthorizeAddress(address addr)
onlyOwner
external
{
uint32 index = addressInfos[addr].index;
if (index != 0) {
addressInfos[addr].authorized = false;
AddressDeauthorized(addr, index);
}
}
function getLatestAuthorizedAddresses(uint max)
external
view
returns (address[] addresses)
{
addresses = new address[](max);
address addr = latestAddress;
AddressInfo memory addrInfo;
uint count = 0;
while (addr != 0x0 && count < max) {
addrInfo = addressInfos[addr];
if (addrInfo.index == 0) {
break;
}
addresses[count++] = addr;
addr = addrInfo.previous;
}
}
/// @dev Invoke ERC20 transferFrom method.
/// @param token Address of token to transfer.
/// @param from Address to transfer token from.
/// @param to Address to transfer token to.
/// @param value Amount of token to transfer.
function transferToken(
address token,
address from,
address to,
uint value)
onlyAuthorized
external
{
if (value > 0 && from != to && to != 0x0) {
require(
ERC20(token).transferFrom(from, to, value)
);
}
}
function batchTransferToken(
address lrcTokenAddress,
address feeRecipient,
bytes32[] batch)
onlyAuthorized
external
{
uint len = batch.length;
require(len % 6 == 0);
ERC20 lrc = ERC20(lrcTokenAddress);
for (uint i = 0; i < len; i += 6) {
address owner = address(batch[i]);
address prevOwner = address(batch[(i + len - 6) % len]);
// Pay token to previous order, or to miner as previous order's
// margin split or/and this order's margin split.
ERC20 token = ERC20(address(batch[i + 1]));
// Here batch[i+2] has been checked not to be 0.
if (owner != prevOwner) {
require(
token.transferFrom(owner, prevOwner, uint(batch[i + 2]))
);
}
if (feeRecipient != 0x0 && owner != feeRecipient) {
bytes32 item = batch[i + 3];
if (item != 0) {
require(
token.transferFrom(owner, feeRecipient, uint(item))
);
}
item = batch[i + 4];
if (item != 0) {
require(
lrc.transferFrom(feeRecipient, owner, uint(item))
);
}
item = batch[i + 5];
if (item != 0) {
require(
lrc.transferFrom(owner, feeRecipient, uint(item))
);
}
}
}
}
function isAddressAuthorized(address addr)
public
view
returns (bool)
{
return addressInfos[addr].authorized;
}
}
/// @title Loopring Token Exchange Protocol Implementation Contract
/// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="385c5956515d5478545757484a51565f16574a5f">[email protected]</a>>,
/// @author Kongliang Zhong - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d7bcb8b9b0bbbeb6b9b097bbb8b8a7a5beb9b0f9b8a5b0">[email protected]</a>>
///
/// Recognized contributing developers from the community:
/// https://github.com/Brechtpd
/// https://github.com/rainydio
/// https://github.com/BenjaminPrice
/// https://github.com/jonasshen
contract LoopringProtocolImpl is LoopringProtocol {
using MathBytes32 for bytes32[];
using MathUint for uint;
using MathUint8 for uint8[];
////////////////////////////////////////////////////////////////////////////
/// Variables ///
////////////////////////////////////////////////////////////////////////////
/* address public lrcTokenAddress = 0x0; */
/* address public tokenRegistryAddress = 0x0; */
/* address public delegateAddress = 0x0; */
/* address public nameRegistryAddress = 0x0; */
uint64 public ringIndex = 0;
/* uint8 public walletSplitPercentage = 0; */
// Exchange rate (rate) is the amount to sell or sold divided by the amount
// to buy or bought.
//
// Rate ratio is the ratio between executed rate and an order's original
// rate.
//
// To require all orders' rate ratios to have coefficient ofvariation (CV)
// smaller than 2.5%, for an example , rateRatioCVSThreshold should be:
// `(0.025 * RATE_RATIO_SCALE)^2` or 62500.
/* uint public rateRatioCVSThreshold = 0; */
uint public constant MAX_RING_SIZE = 16;
uint public constant RATE_RATIO_SCALE = 10000;
uint64 public constant ENTERED_MASK = 1 << 63;
// The following map is used to keep trace of order fill and cancellation
// history.
mapping (bytes32 => uint) public cancelledOrFilled;
// This map is used to keep trace of order's cancellation history.
mapping (bytes32 => uint) public cancelled;
// A map from address to its cutoff timestamp.
mapping (address => uint) public cutoffs;
// A map from address to its trading-pair cutoff timestamp.
mapping (address => mapping (bytes20 => uint)) public tradingPairCutoffs;
////////////////////////////////////////////////////////////////////////////
/// Structs ///
////////////////////////////////////////////////////////////////////////////
struct Rate {
uint amountS;
uint amountB;
}
/// @param tokenS Token to sell.
/// @param tokenB Token to buy.
/// @param amountS Maximum amount of tokenS to sell.
/// @param amountB Minimum amount of tokenB to buy if all amountS sold.
/// @param authAddr An address to verify miner has access to the order's
/// auth private-key.
/// @param validSince Indicating when this order should be treated as
/// valid for trading, in second.
/// @param validUntil Indicating when this order should be treated as
/// expired, in second.
/// @param lrcFee Max amount of LRC to pay for miner. The real amount
/// to pay is proportional to fill amount.
/// @param buyNoMoreThanAmountB -
/// If true, this order does not accept buying more
/// than `amountB`.
/// @param walletId The id of the wallet that generated this order.
/// @param marginSplitPercentage -
/// The percentage of margin paid to miner.
/// @param v ECDSA signature parameter v.
/// @param r ECDSA signature parameters r.
/// @param s ECDSA signature parameters s.
struct Order {
address owner;
address tokenS;
address tokenB;
address authAddr;
uint validSince;
uint validUntil;
uint amountS;
uint amountB;
uint lrcFee;
bool buyNoMoreThanAmountB;
uint walletId;
uint8 marginSplitPercentage;
}
/// @param order The original order
/// @param orderHash The order's hash
/// @param feeSelection -
/// A miner-supplied value indicating if LRC (value = 0)
/// or margin split is choosen by the miner (value = 1).
/// We may support more fee model in the future.
/// @param rate Exchange rate provided by miner.
/// @param fillAmountS Amount of tokenS to sell, calculated by protocol.
/// @param lrcReward The amount of LRC paid by miner to order owner in
/// exchange for margin split.
/// @param lrcFee The amount of LR paid by order owner to miner.
/// @param splitS TokenS paid to miner.
/// @param splitB TokenB paid to miner.
struct OrderState {
Order order;
bytes32 orderHash;
bool marginSplitAsFee;
Rate rate;
uint fillAmountS;
uint lrcReward;
uint lrcFee;
uint splitS;
uint splitB;
}
/// @dev A struct to capture parameters passed to submitRing method and
/// various of other variables used across the submitRing core logics.
struct RingParams {
address[3][] addressList;
uint[7][] uintArgsList;
uint8[1][] uint8ArgsList;
bool[] buyNoMoreThanAmountBList;
uint8[] vList;
bytes32[] rList;
bytes32[] sList;
uint minerId;
uint ringSize; // computed
uint16 feeSelections;
address ringMiner; // queried
address feeRecipient; // queried
bytes32 ringHash; // computed
}
////////////////////////////////////////////////////////////////////////////
/// Public Functions ///
////////////////////////////////////////////////////////////////////////////
/// @dev Disable default function.
function () payable public {
revert();
}
function cancelOrder(
address[4] addresses,
uint[7] orderValues,
bool buyNoMoreThanAmountB,
uint8 marginSplitPercentage,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
uint cancelAmount = orderValues[6];
require(cancelAmount > 0); // "amount to cancel is zero");
Order memory order = Order(
addresses[0],
addresses[1],
addresses[2],
addresses[3],
orderValues[2],
orderValues[3],
orderValues[0],
orderValues[1],
orderValues[4],
buyNoMoreThanAmountB,
orderValues[5],
marginSplitPercentage
);
require(msg.sender == order.owner); // "cancelOrder not submitted by order owner");
bytes32 orderHash = calculateOrderHash(order);
verifySignature(
order.owner,
orderHash,
v,
r,
s
);
cancelled[orderHash] = cancelled[orderHash].add(cancelAmount);
cancelledOrFilled[orderHash] = cancelledOrFilled[orderHash].add(cancelAmount);
OrderCancelled(orderHash, cancelAmount);
}
function cancelAllOrdersByTradingPair(
address token1,
address token2,
uint cutoff
)
external
{
uint t = (cutoff == 0 || cutoff >= block.timestamp) ? block.timestamp : cutoff;
bytes20 tokenPair = bytes20(token1) ^ bytes20(token2);
require(tradingPairCutoffs[msg.sender][tokenPair] < t); // "attempted to set cutoff to a smaller value"
tradingPairCutoffs[msg.sender][tokenPair] = t;
OrdersCancelled(
msg.sender,
token1,
token2,
t
);
}
function cancelAllOrders(uint cutoff)
external
{
uint t = (cutoff == 0 || cutoff >= block.timestamp) ? block.timestamp : cutoff;
require(cutoffs[msg.sender] < t); // "attempted to set cutoff to a smaller value"
cutoffs[msg.sender] = t;
AllOrdersCancelled(msg.sender, t);
}
function submitRing(
address[3][] addressList,
uint[7][] uintArgsList,
uint8[1][] uint8ArgsList,
bool[] buyNoMoreThanAmountBList,
uint8[] vList,
bytes32[] rList,
bytes32[] sList,
uint minerId,
uint16 feeSelections
)
public
{
// Check if the highest bit of ringIndex is '1'.
require(ringIndex & ENTERED_MASK != ENTERED_MASK); // "attempted to re-ent submitRing function");
// Set the highest bit of ringIndex to '1'.
ringIndex |= ENTERED_MASK;
RingParams memory params = RingParams(
addressList,
uintArgsList,
uint8ArgsList,
buyNoMoreThanAmountBList,
vList,
rList,
sList,
minerId,
addressList.length,
feeSelections,
0x0, // ringMiner
0x0, // feeRecipient
0x0 // ringHash
);
verifyInputDataIntegrity(params);
updateFeeRecipient(params);
// Assemble input data into structs so we can pass them to other functions.
// This method also calculates ringHash, therefore it must be called before
// calling `verifyRingSignatures`.
OrderState[] memory orders = assembleOrders(params);
verifyRingSignatures(params);
verifyTokensRegistered(params);
handleRing(params, orders);
ringIndex = (ringIndex ^ ENTERED_MASK) + 1;
}
////////////////////////////////////////////////////////////////////////////
/// Internal & Private Functions ///
////////////////////////////////////////////////////////////////////////////
/// @dev Validate a ring.
function verifyRingHasNoSubRing(
uint ringSize,
OrderState[] orders
)
private
pure
{
// Check the ring has no sub-ring.
for (uint i = 0; i < ringSize - 1; i++) {
address tokenS = orders[i].order.tokenS;
for (uint j = i + 1; j < ringSize; j++) {
require(tokenS != orders[j].order.tokenS); // "found sub-ring");
}
}
}
/// @dev Verify the ringHash has been signed with each order's auth private
/// keys as well as the miner's private key.
function verifyRingSignatures(RingParams params)
private
pure
{
uint j;
for (uint i = 0; i < params.ringSize; i++) {
j = i + params.ringSize;
verifySignature(
params.addressList[i][2], // authAddr
params.ringHash,
params.vList[j],
params.rList[j],
params.sList[j]
);
}
if (params.ringMiner != 0x0) {
j++;
verifySignature(
params.ringMiner,
params.ringHash,
params.vList[j],
params.rList[j],
params.sList[j]
);
}
}
function verifyTokensRegistered(RingParams params)
private
view
{
// Extract the token addresses
address[] memory tokens = new address[](params.ringSize);
for (uint i = 0; i < params.ringSize; i++) {
tokens[i] = params.addressList[i][1];
}
// Test all token addresses at once
require(
TokenRegistry(0xa21c1f2AE7f721aE77b1204A4f0811c642638da9).areAllTokensRegistered(tokens)
); // "token not registered");
}
function updateFeeRecipient(RingParams params)
private
view
{
if (params.minerId == 0) {
params.feeRecipient = msg.sender;
} else {
(params.feeRecipient, params.ringMiner) = NameRegistry(
0x0f3Dce8560a6010DE119396af005552B7983b7e7
).getParticipantById(
params.minerId
);
if (params.feeRecipient == 0x0) {
params.feeRecipient = msg.sender;
}
}
uint sigSize = params.ringSize * 2;
if (params.ringMiner != 0x0) {
sigSize += 1;
}
require(sigSize == params.vList.length); // "ring data is inconsistent - vList");
require(sigSize == params.rList.length); // "ring data is inconsistent - rList");
require(sigSize == params.sList.length); // "ring data is inconsistent - sList");
}
function handleRing(
RingParams params,
OrderState[] orders
)
private
{
uint64 _ringIndex = ringIndex ^ ENTERED_MASK;
TokenTransferDelegate delegate = TokenTransferDelegate(0xc787aE8D6560FB77B82F42CED8eD39f94961e304);
// Do the hard work.
verifyRingHasNoSubRing(params.ringSize, orders);
// Exchange rates calculation are performed by ring-miners as solidity
// cannot get power-of-1/n operation, therefore we have to verify
// these rates are correct.
verifyMinerSuppliedFillRates(params.ringSize, orders);
// Scale down each order independently by substracting amount-filled and
// amount-cancelled. Order owner's current balance and allowance are
// not taken into consideration in these operations.
scaleRingBasedOnHistoricalRecords(delegate, params.ringSize, orders);
// Based on the already verified exchange rate provided by ring-miners,
// we can furthur scale down orders based on token balance and allowance,
// then find the smallest order of the ring, then calculate each order's
// `fillAmountS`.
calculateRingFillAmount(params.ringSize, orders);
// Calculate each order's `lrcFee` and `lrcRewrard` and splict how much
// of `fillAmountS` shall be paid to matching order or miner as margin
// split.
calculateRingFees(
delegate,
params.ringSize,
orders,
params.feeRecipient
);
/// Make transfers.
var (orderHashList, amountsList) = settleRing(
delegate,
params.ringSize,
orders,
params.feeRecipient
);
RingMined(
_ringIndex,
params.ringHash,
params.ringMiner,
params.feeRecipient,
orderHashList,
amountsList
);
}
function settleRing(
TokenTransferDelegate delegate,
uint ringSize,
OrderState[] orders,
address feeRecipient
)
private
returns(
bytes32[] memory orderHashList,
uint[6][] memory amountsList)
{
bytes32[] memory batch = new bytes32[](ringSize * 6); // ringSize * (owner + tokenS + 4 amounts)
orderHashList = new bytes32[](ringSize);
amountsList = new uint[6][](ringSize);
uint p = 0;
for (uint i = 0; i < ringSize; i++) {
OrderState memory state = orders[i];
Order memory order = state.order;
uint prevSplitB = orders[(i + ringSize - 1) % ringSize].splitB;
uint nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS;
// Store owner and tokenS of every order
batch[p] = bytes32(order.owner);
batch[p + 1] = bytes32(order.tokenS);
// Store all amounts
batch[p + 2] = bytes32(state.fillAmountS - prevSplitB);
batch[p + 3] = bytes32(prevSplitB + state.splitS);
batch[p + 4] = bytes32(state.lrcReward);
batch[p + 5] = bytes32(state.lrcFee);
p += 6;
// Update fill records
if (order.buyNoMoreThanAmountB) {
cancelledOrFilled[state.orderHash] += nextFillAmountS;
} else {
cancelledOrFilled[state.orderHash] += state.fillAmountS;
}
orderHashList[i] = state.orderHash;
amountsList[i][0] = state.fillAmountS + state.splitS;
amountsList[i][1] = nextFillAmountS - state.splitB;
amountsList[i][2] = state.lrcReward;
amountsList[i][3] = state.lrcFee;
amountsList[i][4] = state.splitS;
amountsList[i][5] = state.splitB;
}
// Do all transactions
delegate.batchTransferToken(0xEF68e7C694F40c8202821eDF525dE3782458639f, feeRecipient, batch);
}
/// @dev Verify miner has calculte the rates correctly.
function verifyMinerSuppliedFillRates(
uint ringSize,
OrderState[] orders
)
private
pure
{
uint[] memory rateRatios = new uint[](ringSize);
uint _rateRatioScale = RATE_RATIO_SCALE;
for (uint i = 0; i < ringSize; i++) {
uint s1b0 = orders[i].rate.amountS.mul(orders[i].order.amountB);
uint s0b1 = orders[i].order.amountS.mul(orders[i].rate.amountB);
require(s1b0 <= s0b1); // "miner supplied exchange rate provides invalid discount");
rateRatios[i] = _rateRatioScale.mul(s1b0) / s0b1;
}
uint cvs = MathUint.cvsquare(rateRatios, _rateRatioScale);
require(cvs <= 62500); // "miner supplied exchange rate is not evenly discounted");
}
/// @dev Calculate each order's fee or LRC reward.
function calculateRingFees(
TokenTransferDelegate delegate,
uint ringSize,
OrderState[] orders,
address feeRecipient
)
private
view
{
bool checkedMinerLrcSpendable = false;
uint minerLrcSpendable = 0;
uint8 _marginSplitPercentageBase = MARGIN_SPLIT_PERCENTAGE_BASE;
uint nextFillAmountS;
for (uint i = 0; i < ringSize; i++) {
OrderState memory state = orders[i];
uint lrcReceiable = 0;
if (state.lrcFee == 0) {
// When an order's LRC fee is 0 or smaller than the specified fee,
// we help miner automatically select margin-split.
state.marginSplitAsFee = true;
state.order.marginSplitPercentage = _marginSplitPercentageBase;
} else {
uint lrcSpendable = getSpendable(
delegate,
0xEF68e7C694F40c8202821eDF525dE3782458639f,
state.order.owner
);
// If the order is selling LRC, we need to calculate how much LRC
// is left that can be used as fee.
if (state.order.tokenS == 0xEF68e7C694F40c8202821eDF525dE3782458639f) {
lrcSpendable -= state.fillAmountS;
}
// If the order is buyign LRC, it will has more to pay as fee.
if (state.order.tokenB == 0xEF68e7C694F40c8202821eDF525dE3782458639f) {
nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS;
lrcReceiable = nextFillAmountS;
}
uint lrcTotal = lrcSpendable + lrcReceiable;
// If order doesn't have enough LRC, set margin split to 100%.
if (lrcTotal < state.lrcFee) {
state.lrcFee = lrcTotal;
state.order.marginSplitPercentage = _marginSplitPercentageBase;
}
if (state.lrcFee == 0) {
state.marginSplitAsFee = true;
}
}
if (!state.marginSplitAsFee) {
if (lrcReceiable > 0) {
if (lrcReceiable >= state.lrcFee) {
state.splitB = state.lrcFee;
state.lrcFee = 0;
} else {
state.splitB = lrcReceiable;
state.lrcFee -= lrcReceiable;
}
}
} else {
// Only check the available miner balance when absolutely needed
if (!checkedMinerLrcSpendable && minerLrcSpendable < state.lrcFee) {
checkedMinerLrcSpendable = true;
minerLrcSpendable = getSpendable(delegate, 0xEF68e7C694F40c8202821eDF525dE3782458639f, feeRecipient);
}
// Only calculate split when miner has enough LRC;
// otherwise all splits are 0.
if (minerLrcSpendable >= state.lrcFee) {
nextFillAmountS = orders[(i + 1) % ringSize].fillAmountS;
uint split;
if (state.order.buyNoMoreThanAmountB) {
split = (nextFillAmountS.mul(
state.order.amountS
) / state.order.amountB).sub(
state.fillAmountS
);
} else {
split = nextFillAmountS.sub(
state.fillAmountS.mul(
state.order.amountB
) / state.order.amountS
);
}
if (state.order.marginSplitPercentage != _marginSplitPercentageBase) {
split = split.mul(
state.order.marginSplitPercentage
) / _marginSplitPercentageBase;
}
if (state.order.buyNoMoreThanAmountB) {
state.splitS = split;
} else {
state.splitB = split;
}
// This implicits order with smaller index in the ring will
// be paid LRC reward first, so the orders in the ring does
// mater.
if (split > 0) {
minerLrcSpendable -= state.lrcFee;
state.lrcReward = state.lrcFee;
}
}
state.lrcFee = 0;
}
}
}
/// @dev Calculate each order's fill amount.
function calculateRingFillAmount(
uint ringSize,
OrderState[] orders
)
private
pure
{
uint smallestIdx = 0;
uint i;
uint j;
for (i = 0; i < ringSize; i++) {
j = (i + 1) % ringSize;
smallestIdx = calculateOrderFillAmount(
orders[i],
orders[j],
i,
j,
smallestIdx
);
}
for (i = 0; i < smallestIdx; i++) {
calculateOrderFillAmount(
orders[i],
orders[(i + 1) % ringSize],
0, // Not needed
0, // Not needed
0 // Not needed
);
}
}
/// @return The smallest order's index.
function calculateOrderFillAmount(
OrderState state,
OrderState next,
uint i,
uint j,
uint smallestIdx
)
private
pure
returns (uint newSmallestIdx)
{
// Default to the same smallest index
newSmallestIdx = smallestIdx;
uint fillAmountB = state.fillAmountS.mul(
state.rate.amountB
) / state.rate.amountS;
if (state.order.buyNoMoreThanAmountB) {
if (fillAmountB > state.order.amountB) {
fillAmountB = state.order.amountB;
state.fillAmountS = fillAmountB.mul(
state.rate.amountS
) / state.rate.amountB;
newSmallestIdx = i;
}
state.lrcFee = state.order.lrcFee.mul(
fillAmountB
) / state.order.amountB;
} else {
state.lrcFee = state.order.lrcFee.mul(
state.fillAmountS
) / state.order.amountS;
}
if (fillAmountB <= next.fillAmountS) {
next.fillAmountS = fillAmountB;
} else {
newSmallestIdx = j;
}
}
/// @dev Scale down all orders based on historical fill or cancellation
/// stats but key the order's original exchange rate.
function scaleRingBasedOnHistoricalRecords(
TokenTransferDelegate delegate,
uint ringSize,
OrderState[] orders
)
private
view
{
for (uint i = 0; i < ringSize; i++) {
OrderState memory state = orders[i];
Order memory order = state.order;
uint amount;
if (order.buyNoMoreThanAmountB) {
amount = order.amountB.tolerantSub(
cancelledOrFilled[state.orderHash]
);
order.amountS = amount.mul(order.amountS) / order.amountB;
order.lrcFee = amount.mul(order.lrcFee) / order.amountB;
order.amountB = amount;
} else {
amount = order.amountS.tolerantSub(
cancelledOrFilled[state.orderHash]
);
order.amountB = amount.mul(order.amountB) / order.amountS;
order.lrcFee = amount.mul(order.lrcFee) / order.amountS;
order.amountS = amount;
}
require(order.amountS > 0); // "amountS is zero");
require(order.amountB > 0); // "amountB is zero");
uint availableAmountS = getSpendable(delegate, order.tokenS, order.owner);
require(availableAmountS > 0); // "order spendable amountS is zero");
state.fillAmountS = (
order.amountS < availableAmountS ?
order.amountS : availableAmountS
);
}
}
/// @return Amount of ERC20 token that can be spent by this contract.
function getSpendable(
TokenTransferDelegate delegate,
address tokenAddress,
address tokenOwner
)
private
view
returns (uint)
{
ERC20 token = ERC20(tokenAddress);
uint allowance = token.allowance(
tokenOwner,
address(delegate)
);
uint balance = token.balanceOf(tokenOwner);
return (allowance < balance ? allowance : balance);
}
/// @dev verify input data's basic integrity.
function verifyInputDataIntegrity(RingParams params)
private
pure
{
require(params.ringSize == params.addressList.length); // "ring data is inconsistent - addressList");
require(params.ringSize == params.uintArgsList.length); // "ring data is inconsistent - uintArgsList");
require(params.ringSize == params.uint8ArgsList.length); // "ring data is inconsistent - uint8ArgsList");
require(params.ringSize == params.buyNoMoreThanAmountBList.length); // "ring data is inconsistent - buyNoMoreThanAmountBList");
// Validate ring-mining related arguments.
for (uint i = 0; i < params.ringSize; i++) {
require(params.uintArgsList[i][5] > 0); // "order rateAmountS is zero");
}
//Check ring size
require(params.ringSize > 1 && params.ringSize <= MAX_RING_SIZE); // "invalid ring size");
}
/// @dev assmble order parameters into Order struct.
/// @return A list of orders.
function assembleOrders(RingParams params)
private
view
returns (OrderState[] memory orders)
{
orders = new OrderState[](params.ringSize);
for (uint i = 0; i < params.ringSize; i++) {
Order memory order = Order(
params.addressList[i][0],
params.addressList[i][1],
params.addressList[(i + 1) % params.ringSize][1],
params.addressList[i][2],
params.uintArgsList[i][2],
params.uintArgsList[i][3],
params.uintArgsList[i][0],
params.uintArgsList[i][1],
params.uintArgsList[i][4],
params.buyNoMoreThanAmountBList[i],
params.uintArgsList[i][6],
params.uint8ArgsList[i][0]
);
validateOrder(order);
bytes32 orderHash = calculateOrderHash(order);
verifySignature(
order.owner,
orderHash,
params.vList[i],
params.rList[i],
params.sList[i]
);
bool marginSplitAsFee = (params.feeSelections & (uint16(1) << i)) > 0;
orders[i] = OrderState(
order,
orderHash,
marginSplitAsFee,
Rate(params.uintArgsList[i][5], order.amountB),
0, // fillAmountS
0, // lrcReward
0, // lrcFee
0, // splitS
0 // splitB
);
params.ringHash ^= orderHash;
}
params.ringHash = keccak256(
params.ringHash,
params.minerId,
params.feeSelections
);
}
/// @dev validate order's parameters are OK.
function validateOrder(Order order)
private
view
{
require(order.owner != 0x0); // invalid order owner
require(order.tokenS != 0x0); // invalid order tokenS
require(order.tokenB != 0x0); // invalid order tokenB
require(order.amountS != 0); // invalid order amountS
require(order.amountB != 0); // invalid order amountB
require(order.marginSplitPercentage <= MARGIN_SPLIT_PERCENTAGE_BASE); // invalid order marginSplitPercentage
require(order.validSince <= block.timestamp); // order is too early to match
require(order.validUntil > block.timestamp); // order is expired
bytes20 tradingPair = bytes20(order.tokenS) ^ bytes20(order.tokenB);
require(order.validSince > tradingPairCutoffs[order.owner][tradingPair]); // order trading pair is cut off
require(order.validSince > cutoffs[order.owner]); // order is cut off
}
/// @dev Get the Keccak-256 hash of order with specified parameters.
function calculateOrderHash(Order order)
private
view
returns (bytes32)
{
return keccak256(
address(this),
order.owner,
order.tokenS,
order.tokenB,
order.authAddr,
order.amountS,
order.amountB,
order.validSince,
order.validUntil,
order.lrcFee,
order.buyNoMoreThanAmountB,
order.walletId,
order.marginSplitPercentage
);
}
/// @dev Verify signer's signature.
function verifySignature(
address signer,
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
)
private
pure
{
require(
signer == ecrecover(
keccak256("\x19Ethereum Signed Message:\n32", hash),
v,
r,
s
)
); // "invalid signature");
}
function getTradingPairCutoffs(address orderOwner, address token1, address token2)
public
view
returns (uint)
{
bytes20 tokenPair = bytes20(token1) ^ bytes20(token2);
return tradingPairCutoffs[orderOwner][tokenPair];
}
} | Extract the token addresses | function verifyTokensRegistered(RingParams params)
private
view
{
address[] memory tokens = new address[](params.ringSize);
for (uint i = 0; i < params.ringSize; i++) {
tokens[i] = params.addressList[i][1];
}
TokenRegistry(0xa21c1f2AE7f721aE77b1204A4f0811c642638da9).areAllTokensRegistered(tokens)
}
| 15,330,145 |
./full_match/1/0xa35A4972D74d4B3e4486163066E5fFed6d62b213/sources/browser/flatgenlenderiron.sol | three situations1 currency is eth so no change.2 we use uniswap swap price3 we use external oracle | function _callCostToWant(uint256 callCost) internal view returns (uint256){
uint256 wantCallCost;
if(address(want) == weth){
wantCallCost = callCost;
wantCallCost = ethToWant(callCost);
wantCallCost = IWantToEth(wantToEthOracle).ethToWant(callCost);
}
return wantCallCost;
}
| 3,044,115 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ERC721.sol";
import "./Ownable.sol";
import "./ERC1155Burnable.sol";
contract WhiteRabbitOne is ERC721, Ownable {
using Address for address;
using Strings for uint256;
// metadata
bool public metadataLocked = false;
string public baseURI = "";
// supply and phases
uint256 public mintIndex;
uint256 public availSupply = 8765;
bool public presaleEnded = false;
bool public publicSaleEnded = false;
bool public mintPaused = true;
// price
uint256 public constant PRICE_PRESALE = 0.06 ether;
uint256 public constant PRICE_MAINSALE = 0.08 ether;
// limits
uint256 public constant MINTS_PER_PASS = 3;
uint256 public constant MAX_PER_TX_PUBLIC_SALE = 15;
uint256 public constant MAX_PER_WALLET_PUBLIC_SALE = 100;
// presale access
ERC1155Burnable public MintPass;
uint256 public MintPassTokenId;
// tracking per wallet
mapping(address => uint256) public mintedPublicSale;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection, and by setting supply caps, mint indexes, and reserves
*/
constructor()
ERC721("WhiteRabbitOne", "WR1")
{
MintPass = ERC1155Burnable(0x29e99baEfeaC4FE2b3dDDBBfC18A517fb7D6DDf8);
MintPassTokenId = 1;
}
/**
* ------------ METADATA ------------
*/
/**
* @dev Gets base metadata URI
*/
function _baseURI() internal view override returns (string memory) {
return baseURI;
}
/**
* @dev Sets base metadata URI, callable by owner
*/
function setBaseUri(string memory _uri) external onlyOwner {
require(metadataLocked == false);
baseURI = _uri;
}
/**
* @dev Lock metadata URI forever, callable by owner
*/
function lockMetadata() external onlyOwner {
require(metadataLocked == false);
metadataLocked = true;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory base = _baseURI();
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* ------------ SALE AND PRESALE ------------
*/
/**
* @dev Ends public sale forever, callable by owner
*/
function endSaleForever() external onlyOwner {
publicSaleEnded = true;
}
/**
* @dev Ends the presale, callable by owner
*/
function endPresale() external onlyOwner {
presaleEnded = true;
}
/**
* @dev Pause/unpause sale or presale
*/
function togglePauseMinting() external onlyOwner {
mintPaused = !mintPaused;
}
/**
* ------------ CONFIGURATION ------------
*/
/**
* @dev Set presale access token address
*/
function setMintPass(address addr, uint256 tokenId) external onlyOwner {
MintPass = ERC1155Burnable(addr);
MintPassTokenId = tokenId;
}
/**
* ------------ MINTING ------------
*/
/**
* @dev Mints `count` tokens to `to` address; internal
*/
function mintInternal(address to, uint256 count) internal {
for (uint256 i = 0; i < count; i++) {
_mint(to, mintIndex);
mintIndex++;
}
}
/**
* @dev Public minting during public sale or presale
*/
function mint(uint256 count) public payable{
require(count > 0, "Count can't be 0");
require(!mintPaused, "Minting is currently paused");
require(publicSaleEnded == false, "Sale ended");
require(mintIndex + count <= availSupply, "Supply exceeded");
if (!presaleEnded) {
// presale checks
uint256 mintPassBalance = MintPass.balanceOf(msg.sender, MintPassTokenId);
require(count <= mintPassBalance * MINTS_PER_PASS, "Count too high");
require(msg.value == count * PRICE_PRESALE, "Ether value incorrect");
uint256 valueToBurn = (count+MINTS_PER_PASS-1)/MINTS_PER_PASS;
MintPass.burn(msg.sender, MintPassTokenId, valueToBurn);
} else {
require(count <= MAX_PER_TX_PUBLIC_SALE, "Too many tokens");
require(msg.value == count * PRICE_MAINSALE, "Ether value incorrect");
require(mintedPublicSale[msg.sender] + count <= MAX_PER_WALLET_PUBLIC_SALE, "Count exceeded during public sale");
mintedPublicSale[msg.sender] += count;
}
mintInternal(msg.sender, count);
}
/**
* @dev Withdraw ether from this contract, callable by owner
*/
function withdraw() external onlyOwner {
uint256 balance = address(this).balance;
payable(msg.sender).transfer(balance);
}
} | See {IERC721Metadata-tokenURI}./ | function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token");
string memory base = _baseURI();
return string(abi.encodePacked(base, tokenId.toString()));
}
| 1,459,251 |
pragma solidity ^0.4.17;
contract ERC20 {
function totalSupply() public view returns (uint supply);
function balanceOf( address who ) public view returns (uint value);
function allowance( address owner, address spender ) public view returns (uint _allowance);
function transfer( address to, uint value) public returns (bool ok);
function transferFrom( address from, address to, uint value) public returns (bool ok);
function approve( address spender, uint value ) public returns (bool ok);
event Transfer( address indexed from, address indexed to, uint value);
event Approval( address indexed owner, address indexed spender, uint value);
}
contract DSAuthority {
function canCall(
address src, address dst, bytes4 sig
) public view returns (bool);
}
contract DSAuthEvents {
event LogSetAuthority (address indexed authority);
event LogSetOwner (address indexed owner);
}
contract DSAuth is DSAuthEvents {
DSAuthority public authority;
address public owner;
function DSAuth() public {
owner = msg.sender;
LogSetOwner(msg.sender);
}
function setOwner(address owner_)
public
auth
{
owner = owner_;
LogSetOwner(owner);
}
function setAuthority(DSAuthority authority_)
public
auth
{
authority = authority_;
LogSetAuthority(authority);
}
modifier auth {
require(isAuthorized(msg.sender, msg.sig));
_;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
if (src == address(this)) {
return true;
} else if (src == owner) {
return true;
} else if (authority == DSAuthority(0)) {
return false;
} else {
return authority.canCall(src, this, sig);
}
}
}
contract APMath {
function safeAdd(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x);
}
function safeSub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x);
}
function safeMul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x);
}
function safeMin(uint x, uint y) internal pure returns (uint z) {
return x <= y ? x : y;
}
function safeMax(uint x, uint y) internal pure returns (uint z) {
return x >= y ? x : y;
}
function safeMin(int x, int y) internal pure returns (int z) {
return x <= y ? x : y;
}
function safeMax(int x, int y) internal pure returns (int z) {
return x >= y ? x : y;
}
uint constant WAD = 10 ** 18;
uint constant RAY = 10 ** 27;
function safeWmul(uint x, uint y) internal pure returns (uint z) {
z = safeAdd(safeMul(x, y), WAD / 2) / WAD;
}
function safeRmul(uint x, uint y) internal pure returns (uint z) {
z = safeAdd(safeMul(x, y), RAY / 2) / RAY;
}
function safeWdiv(uint x, uint y) internal pure returns (uint z) {
z = safeAdd(safeMul(x, WAD), y / 2) / y;
}
function safeRdiv(uint x, uint y) internal pure returns (uint z) {
z = safeAdd(safeMul(x, RAY), y / 2) / y;
}
// This famous algorithm is called "exponentiation by squaring"
// and calculates x^n with x as fixed-point and n as regular unsigned.
//
// It's O(log n), instead of O(n) for naive repeated multiplication.
//
// These facts are why it works:
//
// If n is even, then x^n = (x^2)^(n/2).
// If n is odd, then x^n = x * x^(n-1),
// and applying the equation for even x gives
// x^n = x * (x^2)^((n-1) / 2).
//
// Also, EVM division is flooring and
// floor[(n-1) / 2] = floor[n / 2].
//
function rpow(uint x, uint n) internal pure returns (uint z) {
z = n % 2 != 0 ? x : RAY;
for (n /= 2; n != 0; n /= 2) {
x = safeRmul(x, x);
if (n % 2 != 0) {
z = safeRmul(z, x);
}
}
}
}
contract DrivezyPrivateCoinSharedStorage is DSAuth {
uint _totalSupply = 0;
// オーナー登録されているアドレス
mapping(address => bool) ownerAddresses;
// オーナーアドレスの LUT
address[] public ownerAddressLUT;
// 信頼できるコントラクトに登録されているアドレス
mapping(address => bool) trustedContractAddresses;
// 信頼できるコントラクトの LUT
address[] public trustedAddressLUT;
// ホワイトリスト (KYC確認済み) のアドレス
mapping(address => bool) approvedAddresses;
// ホワイトリストの LUT
address[] public approvedAddressLUT;
// 常に許可されている関数
mapping(bytes4 => bool) actionsAlwaysPermitted;
/**
* custom events
*/
/* addOwnerAddress したときに発生するイベント
* {address} senderAddress - 実行者のアドレス
* {address} userAddress - 許可されたユーザのアドレス
*/
event AddOwnerAddress(address indexed senderAddress, address indexed userAddress);
/* removeOwnerAddress したときに発生するイベント
* {address} senderAddress - 実行者のアドレス
* {address} userAddress - 許可を取り消されたユーザのアドレス
*/
event RemoveOwnerAddress(address indexed senderAddress, address indexed userAddress);
/* addTrustedContractAddress したときに発生するイベント
* {address} senderAddress - 実行者のアドレス
* {address} userAddress - 許可されたユーザのアドレス
*/
event AddTrustedContractAddress(address indexed senderAddress, address indexed userAddress);
/* removeTrustedContractAddress したときに発生するイベント
* {address} senderAddress - 実行者のアドレス
* {address} userAddress - 許可を取り消されたユーザのアドレス
*/
event RemoveTrustedContractAddress(address indexed senderAddress, address indexed userAddress);
/**
* 指定したアドレスをオーナー一覧に追加する
* @param addr (address) - オーナーに追加したいアドレス
* @return {bool} 追加に成功した場合は true を返す
*/
function addOwnerAddress(address addr) auth public returns (bool) {
ownerAddresses[addr] = true;
ownerAddressLUT.push(addr);
AddOwnerAddress(msg.sender, addr);
return true;
}
/**
* 指定したアドレスを信頼できるコントラクト一覧に追加する
* ここに追加されたコントラクトは、mint や burn などの管理者コマンドを実行できる (いわゆる sudo)
* @param addr (address) - 信頼できるコントラクト一覧に追加したいアドレス
* @return {bool} 追加に成功した場合は true を返す
*/
function addTrustedContractAddress(address addr) auth public returns (bool) {
trustedContractAddresses[addr] = true;
trustedAddressLUT.push(addr);
AddTrustedContractAddress(msg.sender, addr);
return true;
}
/**
* 指定したアドレスをKYC承認済みアドレス一覧に追加する
* ここに追加されたアドレスはトークンの購入ができる
* @param addr (address) - KYC承認済みアドレス一覧に追加したいアドレス
* @return {bool} 追加に成功した場合は true を返す
*/
function addApprovedAddress(address addr) auth public returns (bool) {
approvedAddresses[addr] = true;
approvedAddressLUT.push(addr);
return true;
}
/**
* 指定したアドレスをオーナー一覧から削除する
* @param addr (address) - オーナーから外したいアドレス
* @return {bool} 削除に成功した場合は true を返す
*/
function removeOwnerAddress(address addr) auth public returns (bool) {
ownerAddresses[addr] = false;
RemoveOwnerAddress(msg.sender, addr);
return true;
}
/**
* 指定したアドレスを信頼できるコントラクト一覧から削除する
* @param addr (address) - 信頼できるコントラクト一覧から外したいアドレス
* @return {bool} 削除に成功した場合は true を返す
*/
function removeTrustedContractAddress(address addr) auth public returns (bool) {
trustedContractAddresses[addr] = false;
RemoveTrustedContractAddress(msg.sender, addr);
return true;
}
/**
* 指定したアドレスをKYC承認済みアドレス一覧から削除する
* @param addr (address) - KYC承認済みアドレス一覧から外したいアドレス
* @return {bool} 削除に成功した場合は true を返す
*/
function removeApprovedAddress(address addr) auth public returns (bool) {
approvedAddresses[addr] = false;
return true;
}
/**
* 指定したアドレスがオーナーであるかを調べる
* @param addr (address) - オーナーであるか調べたいアドレス
* @return {bool} オーナーであった場合は true を返す
*/
function isOwnerAddress(address addr) public constant returns (bool) {
return ownerAddresses[addr];
}
/**
* 指定したアドレスがKYC承認済みであるかを調べる
* @param addr (address) - KYC承認済みであるか調べたいアドレス
* @return {bool} KYC承認済みであった場合は true を返す
*/
function isApprovedAddress(address addr) public constant returns (bool) {
return approvedAddresses[addr];
}
/**
* 指定したアドレスが信頼できるコントラクトであるかを調べる
* @param addr (address) - 信頼できるコントラクトであるか調べたいアドレス
* @return {bool} 信頼できるコントラクトであった場合は true を返す
*/
function isTrustedContractAddress(address addr) public constant returns (bool) {
return trustedContractAddresses[addr];
}
/**
* オーナーのアドレス一覧に登録しているアドレス数を調べる
* 同一アドレスについて、リストの追加と削除を繰り返した場合は重複してカウントされる
* @return {uint} 登録されているアドレスの数
*/
function ownerAddressSize() public constant returns (uint) {
return ownerAddressLUT.length;
}
/**
* n 番目に登録されたオーナーのアドレスを取得する (Look up table)
* @param index (uint) - n 番目を指定する
* @return {address} 登録されているアドレス
*/
function ownerAddressInLUT(uint index) public constant returns (address) {
return ownerAddressLUT[index];
}
/**
* 信頼できるコントラクト一覧に登録しているアドレス数を調べる
* 同一アドレスについて、リストの追加と削除を繰り返した場合は重複してカウントされる
* @return {uint} 登録されているアドレスの数
*/
function trustedAddressSize() public constant returns (uint) {
return trustedAddressLUT.length;
}
/**
* n 番目に登録された信頼できるコントラクトを取得する (Look up table)
* @param index (uint) - n 番目を指定する
* @return {address} 登録されているコントラクトのアドレス
*/
function trustedAddressInLUT(uint index) public constant returns (address) {
return trustedAddressLUT[index];
}
/**
* KYC承認済みアドレスの一覧に登録しているアドレス数を調べる
* 同一アドレスについて、リストの追加と削除を繰り返した場合は重複してカウントされる
* @return {uint} 登録されているアドレスの数
*/
function approvedAddressSize() public constant returns (uint) {
return approvedAddressLUT.length;
}
/**
* n 番目に登録されたKYC承認済みアドレスを取得する (Look up table)
* @param index (uint) - n 番目を指定する
* @return {address} 登録されているアドレス
*/
function approvedAddressInLUT(uint index) public constant returns (address) {
return approvedAddressLUT[index];
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
return src == address(this) || src == owner || isOwnerAddress(src) || isTrustedContractAddress(src) || actionsAlwaysPermitted[sig];
}
}
contract DrivezyPrivateCoinStorage is DSAuth {
uint _totalSupply = 0;
// 残高一覧
mapping(address => uint) coinBalances;
// 送金許可額の一覧
mapping(address => mapping (address => uint)) coinAllowances;
// 共通ストレージ
DrivezyPrivateCoinSharedStorage public sharedStorage;
// 常に許可されている関数
mapping(bytes4 => bool) actionsAlwaysPermitted;
// ユーザ間での送金ができるかどうか
bool public transferBetweenUsers;
function totalSupply() external constant returns (uint) {
return _totalSupply;
}
function setTotalSupply(uint amount) auth external returns (bool) {
_totalSupply = amount;
return true;
}
function coinBalanceOf(address addr) external constant returns (uint) {
return coinBalances[addr];
}
function coinAllowanceOf(address _owner, address spender) external constant returns (uint) {
return coinAllowances[_owner][spender];
}
function setCoinBalance(address addr, uint amount) auth external returns (bool) {
coinBalances[addr] = amount;
return true;
}
function setCoinAllowance(address _owner, address spender, uint value) auth external returns (bool) {
coinAllowances[_owner][spender] = value;
return true;
}
function setSharedStorage(address addr) auth public returns (bool) {
sharedStorage = DrivezyPrivateCoinSharedStorage(addr);
return true;
}
function allowTransferBetweenUsers() auth public returns (bool) {
transferBetweenUsers = true;
return true;
}
function disallowTransferBetweenUsers() auth public returns (bool) {
transferBetweenUsers = false;
return true;
}
function canTransferBetweenUsers() public view returns (bool) {
return transferBetweenUsers;
}
function isAuthorized(address src, bytes4 sig) internal view returns (bool) {
return actionsAlwaysPermitted[sig] || src == address(this) || src == owner || sharedStorage.isOwnerAddress(src) || sharedStorage.isTrustedContractAddress(src);
}
}
contract DrivezyPrivateCoinAcceptableContract {
function receiveToken(address addr, uint amount) public returns (bool);
function isDrivezyPrivateTokenAcceptable() public pure returns (bool);
}
contract DrivezyPrivateCoinImplementation is DSAuth, APMath {
DrivezyPrivateCoinStorage public coinStorage;
DrivezyPrivateCoinSharedStorage public sharedStorage;
DrivezyPrivateCoin public coin;
/**
* custom events
*/
/* storage を設定したときに発生するイベント
* {address} senderAddress - 実行者のアドレス
* {address} contractAddress - 設定した storage のコントラクトアドレス
*/
event SetStorage(address indexed senderAddress, address indexed contractAddress);
/* shared storage を設定したときに発生するイベント
* {address} senderAddress - 実行者のアドレス
* {address} contractAddress - 設定した shared storage のコントラクトアドレス
*/
event SetSharedStorage(address indexed senderAddress, address indexed contractAddress);
/* coin を設定したときに発生するイベント
* {address} senderAddress - 実行者のアドレス
* {address} contractAddress - 設定した coin のコントラクトアドレス
*/
event SetCoin(address indexed senderAddress, address indexed contractAddress);
/* mint したときに発生するイベント
* {address} senderAddress - 実行者のアドレス
* {address} receiverAddress - コインを受け取るユーザのアドレス
* {uint} amount - 発行高
*/
event Mint(address indexed senderAddress, address indexed receiverAddress, uint amount);
/* burn したときに発生するイベント
* {address} senderAddress - 実行者のアドレス
* {address} receiverAddress - コインを消却するユーザのアドレス
* {uint} amount - 消却高
*/
event Burn(address indexed senderAddress, address indexed receiverAddress, uint amount);
/* addApprovedAddress したときに発生するイベント
* {address} senderAddress - 実行者のアドレス
* {address} userAddress - 許可されたユーザのアドレス
*/
event AddApprovedAddress(address indexed senderAddress, address indexed userAddress);
/* removeApprovedAddress したときに発生するイベント
* {address} senderAddress - 実行者のアドレス
* {address} userAddress - 許可が取り消されたユーザのアドレス
*/
event RemoveApprovedAddress(address indexed senderAddress, address indexed userAddress);
/**
* 総発行高を返す
* @return {uint} コインの総発行高
*/
function totalSupply() auth public view returns (uint) {
return coinStorage.totalSupply();
}
/**
* 指定したアドレスが保有するコインの残高を返す
* @param addr {address} - コインの残高を調べたいアドレス
* @return {uint} コインの残高
*/
function balanceOf(address addr) auth public view returns (uint) {
return coinStorage.coinBalanceOf(addr);
}
/**
* ERC20 Token Standardに準拠した関数
*
* あるユーザが保有するコインを指定したアドレスに送金する
* @param sender {address} - 送信元 (資金源) のアドレス
* @param to {address} - 宛先のアドレス
* @param amount {uint} - 送付するコインの分量
* @return {bool} コインの残高
*/
function transfer(address sender, address to, uint amount) auth public returns (bool) {
// 残高を超えて送金してないか確認
require(coinStorage.coinBalanceOf(sender) >= amount);
// 1円以上送ろうとしているか確認
require(amount > 0);
// 受取者がオーナーまたは許可された (KYC 通過済み) アドレスかを確認
require(canTransfer(sender, to));
// 送金元の残高を減らし、送金先の残高を増やす
coinStorage.setCoinBalance(sender, safeSub(coinStorage.coinBalanceOf(sender), amount));
coinStorage.setCoinBalance(to, safeAdd(coinStorage.coinBalanceOf(to), amount));
// 送金先がコントラクトで、isDrivezyPrivateTokenAcceptable が true を返すコントラクトでは
// receiveToken() 関数をコールする
if (isContract(to)) {
DrivezyPrivateCoinAcceptableContract receiver = DrivezyPrivateCoinAcceptableContract(to);
if (receiver.isDrivezyPrivateTokenAcceptable()) {
require(receiver.receiveToken(sender, amount));
}
}
return true;
}
/**
* ERC20 Token Standardに準拠した関数
*
* 指定したユーザが保有するコインを指定したアドレスに送金する
* @param sender {address} - 送付操作を実行するユーザのアドレス
* @param from {address} - 資金源となるユーザのアドレス
* @param to {address} - 宛先のアドレス
* @param amount {uint} - 送付するコインの分量
* @return {bool} 送付に成功した場合は true を返す
*/
function transferFrom(address sender, address from, address to, uint amount) auth public returns (bool) {
// アローアンスを超えて送金してないか確認
require(coinStorage.coinAllowanceOf(sender, from) >= amount);
// transfer 処理に引き継ぐ
transfer(from, to, amount);
// アローアンスを減らす
coinStorage.setCoinAllowance(from, sender, safeSub(coinStorage.coinAllowanceOf(sender, from), amount));
return true;
}
/**
* ERC20 Token Standardに準拠した関数
*
* spender(支払い元のアドレス)にsender(送信者)がamount分だけ支払うのを許可する
* この関数が呼ばれる度に送金可能な金額を更新する。
*
* @param sender {address} - 許可操作を実行するユーザのアドレス
* @param spender (address} - 送付操作を許可する対象ユーザのアドレス
* @param amount {uint} - 送付を許可するコインの分量
* @return {bool} 許可に成功した場合は true を返す
*/
function approve(address sender, address spender, uint amount) auth public returns (bool) {
coinStorage.setCoinAllowance(sender, spender, amount);
return true;
}
/**
* ERC20 Token Standardに準拠した関数
*
* 指定したユーザに対し、送付操作が許可されているトークンの分量を返す
*
* @param owner {address} - 資金源となるユーザのアドレス
* @param spender {address} - 送付操作を許可しているユーザのアドレス
* @return {uint} 許可されているトークンの分量を返す
*/
function allowance(address owner, address spender) auth public constant returns (uint) {
return coinStorage.coinAllowanceOf(owner, spender);
}
/**
* トークンストレージ (このトークンに限り有効なストレージ) を設定する <Ownerのみ実行可能>
* @param addr {address} - DrivezyPrivateCoinStorage のアドレス
* @return {bool} Storage の設定に成功したら true を返す
*/
function setStorage(address addr) auth public returns (bool) {
coinStorage = DrivezyPrivateCoinStorage(addr);
SetStorage(msg.sender, addr);
return true;
}
/**
* 共有ストレージ (一連の発行において共通利用するストレージ) を設定する <Ownerのみ実行可能>
* @param addr {address} - DrivezyPrivateCoinSharedStorage のアドレス
* @return {bool} Storage の設定に成功したら true を返す
*/
function setSharedStorage(address addr) auth public returns (bool) {
sharedStorage = DrivezyPrivateCoinSharedStorage(addr);
SetSharedStorage(msg.sender, addr);
return true;
}
/**
* Coin (ERC20 準拠の公開するコントラクト) を設定する <Ownerのみ実行可能>
* @param addr {address} - DrivezyPrivateCoin のアドレス
* @return {bool} Coin の設定に成功したら true を返す
*/
function setCoin(address addr) auth public returns (bool) {
coin = DrivezyPrivateCoin(addr);
SetCoin(msg.sender, addr);
return true;
}
/**
* 指定したアドレスにコインを発行する <Ownerのみ実行可能>
* @param receiver {address} - 発行したコインの受取アカウント
* @param amount {uint} - 発行量
* @return {bool} 発行に成功したら true を返す
*/
function mint(address receiver, uint amount) auth public returns (bool) {
// 1円以上発行しようとしているか確認
require(amount > 0);
// 発行残高を増やす
coinStorage.setTotalSupply(safeAdd(coinStorage.totalSupply(), amount));
// 自分自身に発行する
// 発行に先立ち、自分がトークンを持てるようにする
addApprovedAddress(address(this));
coinStorage.setCoinBalance(address(this), safeAdd(coinStorage.coinBalanceOf(address(this)), amount));
// 自分自身から相手に送付する
require(coin.transfer(receiver, amount));
// ログに保存
Mint(msg.sender, receiver, amount);
return true;
}
/**
* 指定したアドレスからコインを回収する <Ownerのみ実行可能>
* @param receiver {address} - 回収先のアカウント
* @param amount {uint} - 回収量
* @return {bool} 回収に成功したら true を返す
*/
function burn(address receiver, uint amount) auth public returns (bool) {
// 1円以上回収しようとしているか確認
require(amount > 0);
// 回収先のアカウントの所持金額以下を回収しようとしているか確認
require(coinStorage.coinBalanceOf(receiver) >= amount);
// 回収する残量の approve を強制的に設定する
// 回収に先立ち、自分がトークンを持てるようにする
approve(address(this), receiver, amount);
addApprovedAddress(address(this));
// 自分自身のコントラクトに回収する
require(coin.transferFrom(receiver, address(this), amount));
// 回収後、コインを溶かす
coinStorage.setTotalSupply(safeSub(coinStorage.totalSupply(), amount));
coinStorage.setCoinBalance(address(this), safeSub(coinStorage.coinBalanceOf(address(this)), amount));
// ログに保存
Burn(msg.sender, receiver, amount);
return true;
}
/**
* 指定したアドレスをホワイトリストに追加 <Ownerのみ実行可能>
* @param addr {address} - 追加するアカウント
* @return {bool} 追加に成功したら true を返す
*/
function addApprovedAddress(address addr) auth public returns (bool) {
sharedStorage.addApprovedAddress(addr);
AddApprovedAddress(msg.sender, addr);
return true;
}
/**
* 指定したアドレスをホワイトリストから削除 <Ownerのみ実行可能>
* @param addr {address} - 削除するアカウント
* @return {bool} 削除に成功したら true を返す
*/
function removeApprovedAddress(address addr) auth public returns (bool) {
sharedStorage.removeApprovedAddress(addr);
RemoveApprovedAddress(msg.sender, addr);
return true;
}
/**
* ユーザ間の送金を許可する <Ownerのみ実行可能>
* @return {bool} 許可に成功したら true を返す
*/
function allowTransferBetweenUsers() auth public returns (bool) {
coinStorage.allowTransferBetweenUsers();
return true;
}
/**
* ユーザ間の送金を禁止する <Ownerのみ実行可能>
* @return {bool} 禁止に成功したら true を返す
*/
function disallowTransferBetweenUsers() auth public returns (bool) {
coinStorage.disallowTransferBetweenUsers();
return true;
}
/**
* DSAuth の canCall(src, dst, sig) の override
* シグネチャと実行者レベルで関数の実行可否を返す
#
* @param src {address} - 呼び出し元ユーザのアドレス
* @param dst {address} - 実行先コントラクトのアドレス
* @param sig {bytes4} - 関数のシグネチャ (SHA3)
* @return {bool} 関数が実行可能であれば true を返す
*/
function canCall(address src, address dst, bytes4 sig) public constant returns (bool) {
dst; // HACK - 引数を使わないとコンパイラが警告を出す
sig; // HACK - こちらも同様
// オーナーによる実行、「信用するコントラクト」からの呼び出し、コインからの呼び出しは許可
return src == owner || sharedStorage.isOwnerAddress(src) || sharedStorage.isTrustedContractAddress(src) || src == address(coin);
}
/**
* 指定したユーザ間での転送が承認されるかどうか
* - 受取者が approvedAddress か ownerAddress に属する
* - coinStorage.canTransferBetweenUsers = false の場合、受取者か送信者のいずれかが ownerAddress または trustedContractAddress に属する
* @param from {address} - 送付者のアドレス
* @param to {address} - 受取者のアドレス
* @return {bool} 転送できる場合は true を返す
*/
function canTransfer(address from, address to) internal constant returns (bool) {
// 受取者がオーナーまたは許可された (KYC 通過済み) アドレスかを確認
require(sharedStorage.isOwnerAddress(to) || sharedStorage.isApprovedAddress(to));
// ユーザ間の送金が許可されているか、そうでない場合は送り手または受け手が「オーナー」あるいは「信頼できるコントラクト」に入っているか。
require(coinStorage.canTransferBetweenUsers() || sharedStorage.isOwnerAddress(from) || sharedStorage.isTrustedContractAddress(from) || sharedStorage.isOwnerAddress(to) || sharedStorage.isTrustedContractAddress(to));
return true;
}
/**
* DSAuth の isAuthorized(src, sig) の override
* @param src {address} - コントラクトの実行者
* @param sig {bytes4} - コントラクトのシグネチャの SHA3 値
* @return {bool} 呼び出し可能な関数の場合は true を返す
*/
function isAuthorized(address src, bytes4 sig) internal constant returns (bool) {
return canCall(src, address(this), sig);
}
/**
* 指定されたアドレスがコントラクトであるか判定する
* @param addr {address} - 判定対象のコントラクト
* @return {bool} コントラクトであれば true
*/
function isContract(address addr) public view returns (bool result) {
uint length;
assembly {
// アドレスが持つマシン語のサイズを取得する
length := extcodesize(addr)
}
// 当該アドレスがマシン語を持てばコントラクトと見做せる
return (length > 0);
}
/**
* DrivezyPrivateCoinAcceptableContract#isDrivezyPrivateTokenAcceptable の override
* このコントラクトは Private Token を受け取らない
* @return {bool} 常に false を返す
*/
function isDrivezyPrivateTokenAcceptable() public pure returns (bool result) {
return false;
}
}
/**
* ERC20 に準拠したコインの公開インタフェース
*/
contract DrivezyPrivateCoin is ERC20, DSAuth {
/**
* public variables - Etherscan などに表示される
*/
/* コインの名前 */
string public name = "Uni 0.1.0";
/* コインのシンボル */
string public symbol = "ORI";
/* 通貨の最小単位の桁数。 6 の場合は小数第6位が最小単位となる (0.000001 ORI) */
uint8 public decimals = 6;
/**
* custom events
*/
/* Implementation を設定したときに発生するイベント
* {address} senderAddress - 実行者のアドレス
* {address} contractAddress - 設定した implementation のコントラクトアドレス
*/
event SetImplementation(address indexed senderAddress, address indexed contractAddress);
/**
* private variables
*/
// トークンのロジック実装インスタンス
DrivezyPrivateCoinImplementation public implementation;
// ----------------------------------------------------------------------------------------------------
// ERC20 Token Standard functions
// ----------------------------------------------------------------------------------------------------
/**
* 総発行高を返す
* @return {uint} コインの総発行高
*/
function totalSupply() public constant returns (uint) {
return implementation.totalSupply();
}
/**
* 指定したアドレスが保有するコインの残高を返す
* @param addr {address} - コインの残高を調べたいアドレス
* @return {uint} コインの残高
*/
function balanceOf(address addr) public constant returns (uint) {
return implementation.balanceOf(addr);
}
/**
* 自分が保有するコインを指定したアドレスに送金する
* @param to {address} - 宛先のアドレス
* @param amount {uint} - 送付するコインの分量
* @return {bool} 送付に成功した場合は true を返す
*/
function transfer(address to, uint amount) public returns (bool) {
if (implementation.transfer(msg.sender, to, amount)) {
Transfer(msg.sender, to, amount);
return true;
} else {
return false;
}
}
/**
* 指定したユーザが保有するコインを指定したアドレスに送金する
* @param from {address} - 資金源となるユーザのアドレス
* @param to {address} - 宛先のアドレス
* @param amount {uint} - 送付するコインの分量
* @return {bool} 送付に成功した場合は true を返す
*/
function transferFrom(address from, address to, uint amount) public returns (bool) {
if (implementation.transferFrom(msg.sender, from, to, amount)) {
Transfer(from, to, amount);
return true;
} else {
return false;
}
}
/**
* 指定したユーザに対し、(トークン所有者に代わって)指定した分量のトークンの送付を許可する
* @param spender {address} - 送付操作を許可する対象ユーザのアドレス
* @param amount {uint} - 送付を許可するコインの分量
* @return {bool} 許可に成功した場合は true を返す
*/
function approve(address spender, uint amount) public returns (bool) {
if (implementation.approve(msg.sender, spender, amount)) {
Approval(msg.sender, spender, amount);
return true;
} else {
return false;
}
}
/**
* 指定したユーザに対し、送付操作が許可されているトークンの分量を返す
* @param addr {address} - 資金源となるユーザのアドレス
* @param spender {uint} - 送付操作を許可しているユーザのアドレス
* @return {uint} 許可されているトークンの分量を返す
*/
function allowance(address addr, address spender) public constant returns (uint) {
return implementation.allowance(addr, spender);
}
/**
* implementation (実装) が定義されたコントラクトを設定する <Ownerのみ実行可能>
* @param addr {address} - コントラクトのアドレス
* @return {bool} 設定変更に成功した場合は true を返す
*/
function setImplementation(address addr) auth public returns (bool) {
implementation = DrivezyPrivateCoinImplementation(addr);
SetImplementation(msg.sender, addr);
return true;
}
/**
* DSAuth の isAuthorized(src, sig) の override
* @param src {address} - コントラクトの実行者
* @param sig {bytes4} - コントラクトのシグネチャの SHA3 値
* @return {bool} 呼び出し可能な関数の場合は true を返す
*/
function isAuthorized(address src, bytes4 sig) internal constant returns (bool) {
return src == address(this) || // コントラクト自身による呼び出す
src == owner || // コントラクトのデプロイ者
// implementation が定義済みである場合は、Implementation#canCall に呼び出し可否チェックを委譲
(implementation != DrivezyPrivateCoinImplementation(0) && implementation.canCall(src, address(this), sig));
}
}
/**
* ERC20 に準拠したコインの公開インタフェース
*/
contract DrivezyPrivateDecemberCoin is DrivezyPrivateCoin {
/**
* public variables - Etherscan などに表示される
*/
/* コインの名前 */
string public name = "Rental Coins 1.0 1st private offering";
/* コインのシンボル */
string public symbol = "RC1";
/* 通貨の最小単位の桁数。 6 の場合は小数第6位が最小単位となる (0.000001 RC1) */
uint8 public decimals = 6;
} | KYC承認済みアドレスの一覧に登録しているアドレス数を調べる 同一アドレスについて、リストの追加と削除を繰り返した場合は重複してカウントされる return {uint} 登録されているアドレスの数/ | function approvedAddressSize() public constant returns (uint) {
return approvedAddressLUT.length;
}
| 6,415,954 |
// 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/StabilizeStrategyXUSDArb.sol
pragma solidity =0.6.6;
// This is a strategy that takes advantage of arb opportunities for these emerging stablecoins
// Users deposit various tokens into the strategy and the strategy will sell into the lowest priced token
// Selling will occur via Curve and buying WETH via Sushiswap
// Half the profit earned from the sell and interest will be used to buy WETH and split it among the treasury, stakers and executor
// It will sell on withdrawals only when a non-contract calls it and certain requirements are met
// Anyone can be an executors and profit a percentage on a trade
// Gas cost is reimbursed, up to a percentage of the total WETH profit / stipend
// Added feature to trade for maximum profit
interface StabilizeStakingPool {
function notifyRewardAmount(uint256) external;
}
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
function get_dy(int128, int128, uint256) external view returns (uint256); // Get quantity estimate
function exchange(int128, int128, uint256, uint256) external; // Exchange tokens
}
interface TradeRouter {
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 AggregatorV3Interface {
function latestRoundData() external view returns (uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound);
}
interface SafetyERC20 {
function transfer(address recipient, uint256 amount) external;
}
contract StabilizeStrategyXUSDArb 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;
uint256 public lastActionBalance; // Balance before last deposit, withdraw or trade
uint256 public percentTradeTrigger = 500; // 0.5% change in value will trigger a trade
uint256 public percentSell = 100000; // 100% of the tokens are sold to the cheapest token
uint256 public maxAmountSell = 200000; // 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; // 10000 = 10% of WETH goes to executor
uint256 public percentStakers = 50000; // 50% of non-executor WETH goes to stakers, can be changed, rest goes to treasury
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 public minTradeSplit = 20000; // If the balance of ETH is less than or equal to this, it trades the entire balance
uint256 constant minGain = 1e13; // Minimum amount of eth gain (0.00001) before buying WETH and splitting it
bool public safetyMode; // Due to the novelty of the tokens in this pool, one or more of them may decide to fail,
// Make sure strategy can still transfer in case that happens
// Also locks withdraws/deposits/swaps until new strategy is deployed
// Token information
// This strategy accepts multiple stablecoins
// USDN, MUSD, PAX, DUSD, GUSD, BUSD
// All the pools go through USDC to trade between each other
struct TokenInfo {
IERC20 token; // Reference of token
uint256 decimals; // Decimals of token
int128 tokenCurveID; // ID on curve
int128 usdcCurveID; // ID for intermediary token USDC
address curvePoolAddress;
bool useUnderlying;
bool active;
}
TokenInfo[] private tokenList; // An array of tokens accepted as deposits
// Strategy specific variables
address constant WETH_ADDRESS = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
address constant SUSHISWAP_ROUTER = address(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F); //Address of Sushiswap
address constant GAS_ORACLE_ADDRESS = address(0x169E633A2D1E6c10dD91238Ba11c4A708dfEF37C); // Chainlink address for fast gas oracle
address constant USDC_ADDRESS = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
constructor(
address _treasury,
address _staking,
address _zsToken
) public {
treasuryAddress = _treasury;
stakingAddress = _staking;
zsTokenAddress = _zsToken;
setupWithdrawTokens();
}
// Initialization functions
function setupWithdrawTokens() internal {
// USDN, MUSD, PAX, DUSD, GUSD, BUSD
// Start with USDN (by Neutrino)
IERC20 _token = IERC20(address(0x674C6Ad92Fd080e4004b2312b45f796a192D27a0));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x0f9cb53Ebe405d49A0bbdBD291A65Ff571bC83e1),
tokenCurveID: 0,
usdcCurveID: 2,
useUnderlying: true,
active: true
})
);
// MUSD from MStable
_token = IERC20(address(0xe2f2a5C287993345a840Db3B0845fbC70f5935a5));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x8474DdbE98F5aA3179B3B3F5942D724aFcdec9f6),
tokenCurveID: 0,
usdcCurveID: 2,
useUnderlying: true,
active: true
})
);
// PAX
_token = IERC20(address(0x8E870D67F660D95d5be530380D0eC0bd388289E1));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x06364f10B501e868329afBc005b3492902d6C763),
tokenCurveID: 3,
usdcCurveID: 1,
useUnderlying: true,
active: true
})
);
// DUSD by DefiDollar
_token = IERC20(address(0x5BC25f649fc4e26069dDF4cF4010F9f706c23831));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x8038C01A0390a8c547446a0b2c18fc9aEFEcc10c),
tokenCurveID: 0,
usdcCurveID: 2,
useUnderlying: true,
active: true
})
);
// GUSD by Gemini
_token = IERC20(address(0x056Fd409E1d7A124BD7017459dFEa2F387b6d5Cd));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x4f062658EaAF2C1ccf8C8e36D6824CDf41167956),
tokenCurveID: 0,
usdcCurveID: 2,
useUnderlying: true,
active: true
})
);
// BUSD by Binance
_token = IERC20(address(0x4Fabb145d64652a948d72533023f6E7A623C7C53));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x79a8C46DeA5aDa233ABaFFD40F3A0A2B1e5A4F27),
tokenCurveID: 3,
usdcCurveID: 1,
useUnderlying: true,
active: true
})
);
// USDP by Unit
_token = IERC20(address(0x1456688345527bE1f37E9e627DA0837D6f08C925));
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: address(0x42d7025938bEc20B69cBae5A77421082407f053A),
tokenCurveID: 0,
usdcCurveID: 2,
useUnderlying: true,
active: true
})
);
}
// 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 rewardTokenActive(uint256 _pos) external view returns (bool) {
require(_pos < tokenList.length,"No token at that position");
return tokenList[_pos].active;
}
function balance() public view returns (uint256) {
return getNormalizedTotalBalance(address(this));
}
function getNormalizedTotalBalance(address _address) public view returns (uint256) {
// Get the balance of the atokens+tokens at this address
uint256 _balance = 0;
uint256 _length = tokenList.length;
for(uint256 i = 0; i < _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) {
(uint256 targetID, uint256 _bal) = withdrawTokenReservesID();
if(_bal == 0){
return (address(0), _bal);
}else{
return (address(tokenList[targetID].token), _bal);
}
}
function withdrawTokenReservesID() internal view returns (uint256, uint256) {
// This function will return the address and amount of the token with the highest balance
uint256 length = tokenList.length;
uint256 targetID = 0;
uint256 targetNormBalance = 0;
for(uint256 i = 0; i < length; i++){
uint256 _normBal = tokenList[i].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i].decimals);
if(_normBal > 0){
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i;
}
}
}
if(targetNormBalance > 0){
return (targetID, tokenList[targetID].token.balanceOf(address(this)));
}else{
return (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
if(safetyMode == true){return;} // Skip withdraw if safety mode is on
withdraw(_msgSender(),1,1, false);
}
function deposit(bool nonContract) public onlyZSToken {
// Only the ZS token can call the function
require(safetyMode == false, "Safety Mode enabled, wait for new strategy deployment");
// No trading is performed on deposit
if(nonContract == true){}
lastActionBalance = balance(); // This action balance represents pool post stablecoin deposit
}
function withdraw(address _depositor, uint256 _share, uint256 _total, bool nonContract) public onlyZSToken returns (uint256) {
require(balance() > 0, "There are no tokens in this strategy");
require(safetyMode == false, "Safety Mode enabled, wait for new strategy deployment");
if(nonContract == true){
if(_share > _total.mul(percentTradeTrigger).div(DIVISION_FACTOR)){
uint256 buyID = getCheapestCurveToken();
(uint256 sellID, ) = withdrawTokenReservesID(); // These may often be the same tokens
checkAndSwapTokens(address(0), sellID, buyID);
}
}
uint256 withdrawAmount = 0;
uint256 _balance = balance();
if(_share < _total){
uint256 _myBalance = _balance.mul(_share).div(_total);
withdrawPerBalance(_depositor, _myBalance, false); // This will withdraw based on token balance
withdrawAmount = _myBalance;
}else{
// We are all shares, transfer all
withdrawPerBalance(_depositor, _balance, true);
withdrawAmount = _balance;
}
lastActionBalance = balance();
return withdrawAmount;
}
// This will withdraw the tokens from the contract based on their balance, from highest balance to lowest
function withdrawPerBalance(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;
}
bool[4] memory done;
uint256 targetID = 0;
uint256 targetNormBalance = 0;
for(uint256 i = 0; i < length; i++){
targetNormBalance = 0; // Reset the target balance
// Find the highest balanced token to withdraw
for(uint256 i2 = 0; i2 < length; i2++){
if(done[i2] == false){
uint256 _normBal = tokenList[i2].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[i2].decimals);
if(targetNormBalance == 0 || _normBal >= targetNormBalance){
targetNormBalance = _normBal;
targetID = i2;
}
}
}
done[targetID] = true;
// Determine the balance left
uint256 _normalizedBalance = tokenList[targetID].token.balanceOf(address(this)).mul(1e18).div(10**tokenList[targetID].decimals);
if(_normalizedBalance <= _withdrawAmount){
// Withdraw the entire balance of this token
if(_normalizedBalance > 0){
_withdrawAmount = _withdrawAmount.sub(_normalizedBalance);
tokenList[targetID].token.safeTransfer(_receiver, tokenList[targetID].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[targetID].decimals).div(1e18);
_withdrawAmount = 0;
tokenList[targetID].token.safeTransfer(_receiver, _balance);
}
break; // Nothing more to withdraw
}
}
}
function simulateExchange(uint256 _idIn, uint256 _idOut, uint256 _amount) internal view returns (uint256) {
CurvePool pool = CurvePool(tokenList[_idIn].curvePoolAddress);
if(_idOut == tokenList.length){
// This is special code that says we want WETH out
// Simple Sushiswap route
// Convert to USDC
if(tokenList[_idIn].useUnderlying == true){
_amount = pool.get_dy_underlying(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount);
}else{
_amount = pool.get_dy(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount);
}
// Then sell for WETH on Sushiswap
TradeRouter router = TradeRouter(SUSHISWAP_ROUTER);
address[] memory path = new address[](2);
path[0] = USDC_ADDRESS;
path[1] = WETH_ADDRESS;
uint256[] memory estimates = router.getAmountsOut(_amount, path);
_amount = estimates[estimates.length - 1];
return _amount;
}else{
// We will use 2 curve pools to find the prices
// First get USDC
if(tokenList[_idIn].useUnderlying == true){
_amount = pool.get_dy_underlying(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount);
}else{
_amount = pool.get_dy(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount);
}
// Then convert to target token
pool = CurvePool(tokenList[_idOut].curvePoolAddress);
if(tokenList[_idOut].useUnderlying == true){
_amount = pool.get_dy_underlying(tokenList[_idOut].usdcCurveID, tokenList[_idOut].tokenCurveID, _amount);
}else{
_amount = pool.get_dy(tokenList[_idOut].usdcCurveID, tokenList[_idOut].tokenCurveID, _amount);
}
return _amount;
}
}
function exchange(uint256 _idIn, uint256 _idOut, uint256 _amount) internal {
CurvePool pool = CurvePool(tokenList[_idIn].curvePoolAddress);
tokenList[_idIn].token.safeApprove(address(pool), 0);
tokenList[_idIn].token.safeApprove(address(pool), _amount);
if(_idOut == tokenList.length){
// This is special code that says we want WETH out
// Simple Sushiswap route
// Convert to USDC
uint256 _before = IERC20(USDC_ADDRESS).balanceOf(address(this));
if(tokenList[_idIn].useUnderlying == true){
pool.exchange_underlying(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount, 1);
}else{
pool.exchange(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount, 1);
}
_amount = IERC20(USDC_ADDRESS).balanceOf(address(this)).sub(_before); // Get USDC amount
// Then sell for WETH on Sushiswap
TradeRouter router = TradeRouter(SUSHISWAP_ROUTER);
address[] memory path = new address[](2);
path[0] = USDC_ADDRESS;
path[1] = WETH_ADDRESS;
IERC20(USDC_ADDRESS).safeApprove(SUSHISWAP_ROUTER, 0);
IERC20(USDC_ADDRESS).safeApprove(SUSHISWAP_ROUTER, _amount);
router.swapExactTokensForTokens(_amount, 1, path, address(this), now.add(60)); // Get WETH from token
return;
}else{
// We will use 2 curve pools to find the prices
// First get USDC
uint256 _before = IERC20(USDC_ADDRESS).balanceOf(address(this));
if(tokenList[_idIn].useUnderlying == true){
pool.exchange_underlying(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount, 1);
}else{
pool.exchange(tokenList[_idIn].tokenCurveID, tokenList[_idIn].usdcCurveID, _amount, 1);
}
_amount = IERC20(USDC_ADDRESS).balanceOf(address(this)).sub(_before); // Get USDC amount
// Then convert to target token
pool = CurvePool(tokenList[_idOut].curvePoolAddress);
IERC20(USDC_ADDRESS).safeApprove(address(pool), 0);
IERC20(USDC_ADDRESS).safeApprove(address(pool), _amount);
if(tokenList[_idOut].useUnderlying == true){
pool.exchange_underlying(tokenList[_idOut].usdcCurveID, tokenList[_idOut].tokenCurveID, _amount, 1);
}else{
pool.exchange(tokenList[_idOut].usdcCurveID, tokenList[_idOut].tokenCurveID, _amount, 1);
}
return;
}
}
function getCheapestCurveToken() internal view returns (uint256) {
// This will give us the ID of the cheapest token in the pool
// We will estimate the return for trading 1000 USDN
// The higher the return, the lower the price of the other token
uint256 targetID = 0;
uint256 usdnAmount = uint256(10).mul(10**tokenList[0].decimals);
uint256 highAmount = usdnAmount;
uint256 length = tokenList.length;
for(uint256 i = 1; i < length; i++){
if(tokenList[i].active == false){ continue; } // Cannot sell an inactive token
uint256 estimate = simulateExchange(0, i, usdnAmount);
// Normalize the estimate into usdn decimals
estimate = estimate.mul(10**tokenList[0].decimals).div(10**tokenList[i].decimals);
if(estimate > highAmount){
// This token is worth less than the usdn
highAmount = estimate;
targetID = i;
}
}
return targetID;
}
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 estimateSellAtMaximumProfit(uint256 originID, uint256 targetID, uint256 _tokenBalance) internal view returns (uint256) {
// This will estimate the amount that can be sold for the maximum profit possible
// We discover the price then compare it to the actual return
// The return must be positive to return a positive amount
// Discover the price with near 0 slip
uint256 _minAmount = _tokenBalance.mul(percentSell.div(1000)).div(DIVISION_FACTOR);
if(_minAmount == 0){ return 0; } // Nothing to sell, can't calculate
uint256 _minReturn = _minAmount.mul(10**tokenList[targetID].decimals).div(10**tokenList[originID].decimals); // Convert decimals
uint256 _return = simulateExchange(originID, targetID, _minAmount);
if(_return <= _minReturn){
return 0; // We are not going to gain from this trade
}
_return = _return.mul(10**tokenList[originID].decimals).div(10**tokenList[targetID].decimals); // Convert to origin decimals
uint256 _startPrice = _return.mul(1e18).div(_minAmount);
// Now get the price at a higher amount, expected to be lower due to slippage
uint256 _bigAmount = _tokenBalance.mul(percentSell).div(DIVISION_FACTOR);
_return = simulateExchange(originID, targetID, _bigAmount);
_return = _return.mul(10**tokenList[originID].decimals).div(10**tokenList[targetID].decimals); // Convert to origin decimals
uint256 _endPrice = _return.mul(1e18).div(_bigAmount);
if(_endPrice >= _startPrice){
// Really good liquidity
return _bigAmount;
}
// Else calculate amount at max profit
uint256 scaleFactor = uint256(1).mul(10**tokenList[originID].decimals);
uint256 _targetAmount = _startPrice.sub(1e18).mul(scaleFactor).div(_startPrice.sub(_endPrice).mul(scaleFactor).div(_bigAmount.sub(_minAmount))).div(2);
if(_targetAmount > _bigAmount){
// Cannot create an estimate larger than what we want to sell
return _bigAmount;
}
return _targetAmount;
}
function checkAndSwapTokens(address _executor, uint256 _sellID, uint256 _buyID) internal {
if(_sellID == _buyID){return;}
require(_sellID < tokenList.length && _buyID < tokenList.length, "Token ID not found");
require(safetyMode == false, "Unable to swap while in safety mode");
require(tokenList[_sellID].active == true && tokenList[_buyID].active == true, "Token IDs not both active");
// Since this is a gas heavy function, we can reduce the gas by asking executors to select the tokens to swap
// This will likely be the token that is the highest quantity in the strat
lastTradeTime = now;
// Now find our target token to sell into
// Now sell all the other tokens into this token
uint256 _totalBalance = balance(); // Get the token balance at this contract, should increase
bool _expectIncrease = false;
if(_sellID != _buyID){
uint256 sellBalance = 0;
uint256 _tokenBalance = tokenList[_sellID].token.balanceOf(address(this));
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[_sellID].decimals);
if(_tokenBalance <= _minTradeTarget){
// If balance is too small,sell all tokens at once
sellBalance = _tokenBalance;
}else{
sellBalance = estimateSellAtMaximumProfit(_sellID, _buyID, _tokenBalance);
}
uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[_sellID].decimals);
if(sellBalance > _maxTradeTarget){
sellBalance = _maxTradeTarget;
}
if(sellBalance > 0){
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[_buyID].decimals).div(10**tokenList[_sellID].decimals); // Change to match decimals of destination
uint256 estimate = simulateExchange(_sellID, _buyID, sellBalance);
if(estimate > minReceiveBalance){
_expectIncrease = true;
// We are getting a greater number of tokens, complete the exchange
exchange(_sellID, _buyID, sellBalance);
}
}
}
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");
}
uint256 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 Sushiswap with tokens
uint256 sellBalance = gain.mul(10**tokenList[_buyID].decimals).div(1e18); // Convert to target decimals
sellBalance = sellBalance.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR);
if(sellBalance <= tokenList[_buyID].token.balanceOf(address(this))){
// Sell some of our gained token for WETH
exchange(_buyID, tokenList.length, sellBalance);
_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) external view returns (uint256, uint256, uint256) {
// This view will return the expected profit in wei units that a trading activity will have on the pool
// It will also return the highest profit token ID to sell for the lowest token that that will be bought for that profit
// Now find our target token to sell into
uint256 targetID = getCheapestCurveToken(); // Curve may have a slightly different cheap
uint256 length = tokenList.length;
uint256 sellID = 0;
uint256 largestGain = 0;
// Now sell all the other tokens into this token
//uint256 _normalizedGain = 0;
for(uint256 i = 0; i < length; i++){
if(i != targetID){
if(tokenList[i].active == false){continue;} // Cannot sell an inactive token
uint256 sellBalance = 0;
uint256 _tokenBalance = tokenList[i].token.balanceOf(address(this));
uint256 _minTradeTarget = minTradeSplit.mul(10**tokenList[i].decimals);
if(_tokenBalance <= _minTradeTarget){
// If balance is too small,sell all tokens at once
sellBalance = _tokenBalance;
}else{
sellBalance = estimateSellAtMaximumProfit(i, targetID, _tokenBalance);
}
uint256 _maxTradeTarget = maxAmountSell.mul(10**tokenList[i].decimals);
if(sellBalance > _maxTradeTarget){
sellBalance = _maxTradeTarget;
}
if(sellBalance > 0){
uint256 minReceiveBalance = sellBalance.mul(10**tokenList[targetID].decimals).div(10**tokenList[i].decimals); // Change to match decimals of destination
uint256 estimate = simulateExchange(i, targetID, sellBalance);
if(estimate > minReceiveBalance){
uint256 _gain = estimate.sub(minReceiveBalance).mul(1e18).div(10**tokenList[targetID].decimals); // Normalized gain
//_normalizedGain = _normalizedGain.add(_gain);
if(_gain > largestGain){
// We are only selling 1 token for another 1 token
largestGain = _gain;
sellID = i;
}
}
}
}
}
if(inWETHForExecutor == false){
//return (_normalizedGain, targetID);
return (largestGain, sellID, targetID);
}else{
// Calculate WETH profit
if(largestGain == 0){
return (0, 0, 0);
}
// Calculate how much WETH the executor would make as profit
uint256 estimate = 0;
uint256 sellBalance = largestGain.mul(10**tokenList[targetID].decimals).div(1e18); // Convert to target decimals
sellBalance = sellBalance.mul(uint256(100000).sub(percentDepositor)).div(DIVISION_FACTOR);
// Estimate output
if(sellBalance > 0){
estimate = simulateExchange(targetID, tokenList.length, sellBalance);
}
// 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), sellID, targetID); // 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), sellID, targetID); // Executor amount with fee added
}
}
}
function executorSwapTokens(address _executor, uint256 _minSecSinceLastTrade, uint256 _sellID, uint256 _buyID) external {
// Function designed to promote trading with incentive. Users get percentage 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, _sellID, _buyID);
}
// Governance functions
function governanceSwapTokens(uint256 _sellID, uint256 _buyID) external onlyGovernance {
// This is function that force trade tokens at anytime. It can only be called by governance
checkAndSwapTokens(_msgSender(), _sellID, _buyID);
}
function activateSafetyMode() external onlyGovernance {
require(safetyMode == false, "Safety mode already active");
// This function will attempt to transfer tokens to itself and if that fails it will go into safety mode
uint256 length = tokenList.length;
for(uint256 i = 0; i < length; i++){
uint256 _bal = tokenList[i].token.balanceOf(address(this));
if(_bal > 0){
try SafetyERC20(address(tokenList[i].token)).transfer(address(this), _bal) {}
catch {
safetyMode = true;
return;
}
}
}
}
// 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;
address private _timelock_address_2;
uint256[6] 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 _minSplit, uint256 _maxStipend,
uint256 _pMaxStipend, uint256 _maxSell) external onlyGovernance {
// Changes a lot of trading parameters in one call
require(_pTradeTrigger <= 100000 && _pSellPercent <= 100000 && _pMaxStipend <= 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] = _maxSell;
}
function finishChangeTradingConditions() external onlyGovernance timelockConditionsMet(5) {
percentTradeTrigger = _timelock_data[0];
percentSell = _timelock_data[1];
minTradeSplit = _timelock_data[2];
gasStipend = _timelock_data[3];
maxPercentStipend = _timelock_data[4];
maxAmountSell = _timelock_data[5];
}
// --------------------
// Change the strategy allocations between the parties
// --------------------
function startChangeStrategyAllocations(uint256 _pDepositors, uint256 _pExecutor, uint256 _pStakers) 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;
}
function finishChangeStrategyAllocations() external onlyGovernance timelockConditionsMet(6) {
percentDepositor = _timelock_data[0];
percentExecutor = _timelock_data[1];
percentStakers = _timelock_data[2];
}
// --------------------
// Recover trapped tokens
// --------------------
function startRecoverStuckTokens(address _token, uint256 _amount) external onlyGovernance {
require(safetyMode == true, "Cannot execute this function unless safety mode active");
_timelockStart = now;
_timelockType = 7;
_timelock_address = _token;
_timelock_data[0] = _amount;
}
function finishRecoverStuckTokens() external onlyGovernance timelockConditionsMet(7) {
IERC20(_timelock_address).safeTransfer(governance(), _timelock_data[0]);
}
// Add a new token to the strategy
// --------------------
function startAddNewStableToken(address _tokenAddress, address _curvePool, uint256 _curveID, uint256 _usdcID, uint256 _underlying) external onlyGovernance {
_timelockStart = now;
_timelockType = 8;
_timelock_address = _tokenAddress;
_timelock_address_2 = _curvePool;
_timelock_data[0] = _curveID;
_timelock_data[1] = _usdcID;
_timelock_data[2] = _underlying;
}
function finishAddNewStableToken() external onlyGovernance timelockConditionsMet(8) {
IERC20 _token = IERC20(address(_timelock_address));
bool underlying = true;
if(_timelock_data[2] == 0){
underlying = false;
}
tokenList.push(
TokenInfo({
token: _token,
decimals: _token.decimals(),
curvePoolAddress: _timelock_address_2,
tokenCurveID: int128(_timelock_data[0]),
usdcCurveID: int128(_timelock_data[1]),
active: true,
useUnderlying: underlying
})
);
uint256 id = tokenList.length - 1;
// Verify the new token will work
simulateExchange(id, 0, uint256(1).mul(10**tokenList[id].decimals));
}
// Deactivate a token from trading
// --------------------
function startDeactivateToken(uint256 _id) external onlyGovernance {
_timelockStart = now;
_timelockType = 9;
_timelock_data[0] = _id;
}
function finishDeactivateToken() external onlyGovernance timelockConditionsMet(9) {
tokenList[_timelock_data[0]].active = false;
}
} | Governance functions This is function that force trade tokens at anytime. It can only be called by governance | function governanceSwapTokens(uint256 _sellID, uint256 _buyID) external onlyGovernance {
checkAndSwapTokens(_msgSender(), _sellID, _buyID);
}
| 6,170,937 |
// File: contracts/interface/ICoFiXFactory.sol
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.6.12;
interface ICoFiXFactory {
// All pairs: {ETH <-> ERC20 Token}
event PairCreated(address indexed token, address pair, uint256);
event NewGovernance(address _new);
event NewController(address _new);
event NewFeeReceiver(address _new);
event NewFeeVaultForLP(address token, address feeVault);
event NewVaultForLP(address _new);
event NewVaultForTrader(address _new);
event NewVaultForCNode(address _new);
/// @dev Create a new token pair for trading
/// @param token the address of token to trade
/// @return pair the address of new token pair
function createPair(
address token
)
external
returns (address pair);
function getPair(address token) external view returns (address pair);
function allPairs(uint256) external view returns (address pair);
function allPairsLength() external view returns (uint256);
function getTradeMiningStatus(address token) external view returns (bool status);
function setTradeMiningStatus(address token, bool status) external;
function getFeeVaultForLP(address token) external view returns (address feeVault); // for LPs
function setFeeVaultForLP(address token, address feeVault) external;
function setGovernance(address _new) external;
function setController(address _new) external;
function setFeeReceiver(address _new) external;
function setVaultForLP(address _new) external;
function setVaultForTrader(address _new) external;
function setVaultForCNode(address _new) external;
function getController() external view returns (address controller);
function getFeeReceiver() external view returns (address feeReceiver); // For CoFi Holders
function getVaultForLP() external view returns (address vaultForLP);
function getVaultForTrader() external view returns (address vaultForTrader);
function getVaultForCNode() external view returns (address vaultForCNode);
}
// File: contracts/interface/ICoFiXERC20.sol
pragma solidity 0.6.12;
interface ICoFiXERC20 {
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;
}
// File: contracts/interface/ICoFiXPair.sol
pragma solidity 0.6.12;
interface ICoFiXPair is ICoFiXERC20 {
struct OraclePrice {
uint256 ethAmount;
uint256 erc20Amount;
uint256 blockNum;
uint256 K;
uint256 theta;
}
// All pairs: {ETH <-> ERC20 Token}
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, address outToken, uint outAmount, address indexed to);
event Swap(
address indexed sender,
uint amountIn,
uint amountOut,
address outToken,
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);
function mint(address to) external payable returns (uint liquidity, uint oracleFeeChange);
function burn(address outToken, address to) external payable returns (uint amountOut, uint oracleFeeChange);
function swapWithExact(address outToken, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function swapForExact(address outToken, uint amountOutExact, address to) external payable returns (uint amountIn, uint amountOut, uint oracleFeeChange, uint256[4] memory tradeInfo);
function skim(address to) external;
function sync() external;
function initialize(address, address, string memory, string memory) external;
/// @dev get Net Asset Value Per Share
/// @param ethAmount ETH side of Oracle price {ETH <-> ERC20 Token}
/// @param erc20Amount Token side of Oracle price {ETH <-> ERC20 Token}
/// @return navps The Net Asset Value Per Share (liquidity) represents
function getNAVPerShare(uint256 ethAmount, uint256 erc20Amount) external view returns (uint256 navps);
}
// File: contracts/interface/INestPriceFacade.sol
pragma solidity ^0.6.12;
/// @dev This interface defines the methods for price call entry
interface INestPriceFacade {
// /// @dev Price call entry configuration structure
// struct Config {
// // Single query fee(0.0001 ether, DIMI_ETHER). 100
// uint16 singleFee;
// // Double query fee(0.0001 ether, DIMI_ETHER). 100
// uint16 doubleFee;
// // The normal state flag of the call address. 0
// uint8 normalFlag;
// }
// /// @dev Modify configuration
// /// @param config Configuration object
// function setConfig(Config memory config) external;
// /// @dev Get configuration
// /// @return Configuration object
// function getConfig() external view returns (Config memory);
/// @dev Set the address flag. Only the address flag equals to config.normalFlag can the price be called
/// @param addr Destination address
/// @param flag Address flag
function setAddressFlag(address addr, uint flag) external;
/// @dev Get the flag. Only the address flag equals to config.normalFlag can the price be called
/// @param addr Destination address
/// @return Address flag
function getAddressFlag(address addr) external view returns(uint);
/// @dev Set INestQuery implemention contract address for token
/// @param tokenAddress Destination token address
/// @param nestQueryAddress INestQuery implemention contract address, 0 means delete
function setNestQuery(address tokenAddress, address nestQueryAddress) external;
/// @dev Get INestQuery implemention contract address for token
/// @param tokenAddress Destination token address
/// @return INestQuery implemention contract address, 0 means use default
function getNestQuery(address tokenAddress) external view returns (address);
/// @dev Get the latest trigger price
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function triggeredPrice(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price);
/// @dev Get the full information of latest trigger price
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return avgPrice Average price
/// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ);
/// @dev Find the price at block number
/// @param tokenAddress Destination token address
/// @param height Destination block number
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function findPrice(address tokenAddress, uint height, address paybackAddress) external payable returns (uint blockNumber, uint price);
/// @dev Get the latest effective price
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
function latestPrice(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price);
/// @dev Get the last (num) effective price
/// @param tokenAddress Destination token address
/// @param count The number of prices that want to return
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return An array which length is num * 2, each two element expresses one price like blockNumber|price
function lastPriceList(address tokenAddress, uint count, address paybackAddress) external payable returns (uint[] memory);
/// @dev Returns the results of latestPrice() and triggeredPriceInfo()
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return latestPriceBlockNumber The block number of latest price
/// @return latestPriceValue The token latest price. (1eth equivalent to (price) token)
/// @return triggeredPriceBlockNumber The block number of triggered price
/// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
/// @return triggeredAvgPrice Average price
/// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function latestPriceAndTriggeredPriceInfo(address tokenAddress, address paybackAddress)
external
payable
returns (
uint latestPriceBlockNumber,
uint latestPriceValue,
uint triggeredPriceBlockNumber,
uint triggeredPriceValue,
uint triggeredAvgPrice,
uint triggeredSigmaSQ
);
/// @dev Get the latest trigger price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
function triggeredPrice2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice);
/// @dev Get the full information of latest trigger price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return avgPrice Average price
/// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
/// @return ntokenAvgPrice Average price of ntoken
/// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that
/// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447,
/// it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint avgPrice, uint sigmaSQ, uint ntokenBlockNumber, uint ntokenPrice, uint ntokenAvgPrice, uint ntokenSigmaSQ);
/// @dev Get the latest effective price. (token and ntoken)
/// @param tokenAddress Destination token address
/// @param paybackAddress As the charging fee may change, it is suggested that the caller pay more fees, and the excess fees will be returned through this address
/// @return blockNumber The block number of price
/// @return price The token price. (1eth equivalent to (price) token)
/// @return ntokenBlockNumber The block number of ntoken price
/// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken)
function latestPrice2(address tokenAddress, address paybackAddress) external payable returns (uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice);
}
// File: contracts/interface/ICoFiXController.sol
pragma solidity 0.6.12;
interface ICoFiXController {
event NewK(address token, int128 K, int128 sigma, uint256 T, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 tIdx, uint256 sigmaIdx, int128 K0);
event NewGovernance(address _new);
event NewOracle(address _priceOracle);
event NewKTable(address _kTable);
event NewTimespan(uint256 _timeSpan);
event NewKRefreshInterval(uint256 _interval);
event NewKLimit(int128 maxK0);
event NewGamma(int128 _gamma);
event NewTheta(address token, uint32 theta);
event NewK(address token, uint32 k);
function addCaller(address caller) external;
function queryOracle(address token, uint8 op, bytes memory data) external payable returns (uint256 k, uint256 ethAmount, uint256 erc20Amount, uint256 blockNum, uint256 theta);
}
// File: contracts/lib/TransferHelper.sol
pragma solidity 0.6.12;
// helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false
library TransferHelper {
function safeApprove(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('approve(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED');
}
function safeTransfer(address token, address to, uint value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED');
}
function safeTransferFrom(address token, address from, address to, uint value) internal {
// bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED');
}
function safeTransferETH(address to, uint value) internal {
(bool success,) = to.call{value:value}(new bytes(0));
require(success, 'TransferHelper: ETH_TRANSFER_FAILED');
}
}
// File: contracts/interface/ICoFiXKTable.sol
pragma solidity 0.6.12;
interface ICoFiXKTable {
function setK0(uint256 tIdx, uint256 sigmaIdx, int128 k0) external;
function setK0InBatch(uint256[] memory tIdxs, uint256[] memory sigmaIdxs, int128[] memory k0s) external;
function getK0(uint256 tIdx, uint256 sigmaIdx) external view returns (int128);
}
// File: contracts/lib/ABDKMath64x64.sol
/*
* ABDK Math 64.64 Smart Contract Library. Copyright © 2019 by ABDK Consulting.
* Author: Mikhail Vladimirov <[email protected]>
*/
pragma solidity 0.6.12;
/**
* Smart contract library of mathematical functions operating with signed
* 64.64-bit fixed point numbers. Signed 64.64-bit fixed point number is
* basically a simple fraction whose numerator is signed 128-bit integer and
* denominator is 2^64. As long as denominator is always the same, there is no
* need to store it, thus in Solidity signed 64.64-bit fixed point numbers are
* represented by int128 type holding only the numerator.
*/
library ABDKMath64x64 {
/**
* @dev Minimum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MIN_64x64 = -0x80000000000000000000000000000000;
/**
* @dev Maximum value signed 64.64-bit fixed point number may have.
*/
int128 private constant MAX_64x64 = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF;
/**
* Convert signed 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromInt (int256 x) internal pure returns (int128) {
require (x >= -0x8000000000000000 && x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into signed 64-bit integer number
* rounding down.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64-bit integer number
*/
function toInt (int128 x) internal pure returns (int64) {
return int64 (x >> 64);
}
/**
* Convert unsigned 256-bit integer number into signed 64.64-bit fixed point
* number. Revert on overflow.
*
* @param x unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function fromUInt (uint256 x) internal pure returns (int128) {
require (x <= 0x7FFFFFFFFFFFFFFF);
return int128 (x << 64);
}
/**
* Convert signed 64.64 fixed point number into unsigned 64-bit integer
* number rounding down. Revert on underflow.
*
* @param x signed 64.64-bit fixed point number
* @return unsigned 64-bit integer number
*/
function toUInt (int128 x) internal pure returns (uint64) {
require (x >= 0);
return uint64 (x >> 64);
}
/**
* Convert signed 128.128 fixed point number into signed 64.64-bit fixed point
* number rounding down. Revert on overflow.
*
* @param x signed 128.128-bin fixed point number
* @return signed 64.64-bit fixed point number
*/
function from128x128 (int256 x) internal pure returns (int128) {
int256 result = x >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Convert signed 64.64 fixed point number into signed 128.128 fixed point
* number.
*
* @param x signed 64.64-bit fixed point number
* @return signed 128.128 fixed point number
*/
function to128x128 (int128 x) internal pure returns (int256) {
return int256 (x) << 64;
}
/**
* Calculate x + y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function add (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) + y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x - y. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sub (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) - y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding down. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function mul (int128 x, int128 y) internal pure returns (int128) {
int256 result = int256(x) * y >> 64;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x * y rounding towards zero, where x is signed 64.64 fixed point
* number and y is signed 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y signed 256-bit integer number
* @return signed 256-bit integer number
*/
function muli (int128 x, int256 y) internal pure returns (int256) {
if (x == MIN_64x64) {
require (y >= -0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF &&
y <= 0x1000000000000000000000000000000000000000000000000);
return -y << 63;
} else {
bool negativeResult = false;
if (x < 0) {
x = -x;
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint256 absoluteResult = mulu (x, uint256 (y));
if (negativeResult) {
require (absoluteResult <=
0x8000000000000000000000000000000000000000000000000000000000000000);
return -int256 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <=
0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int256 (absoluteResult);
}
}
}
/**
* Calculate x * y rounding down, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64 fixed point number
* @param y unsigned 256-bit integer number
* @return unsigned 256-bit integer number
*/
function mulu (int128 x, uint256 y) internal pure returns (uint256) {
if (y == 0) return 0;
require (x >= 0);
uint256 lo = (uint256 (x) * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) >> 64;
uint256 hi = uint256 (x) * (y >> 128);
require (hi <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
hi <<= 64;
require (hi <=
0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF - lo);
return hi + lo;
}
/**
* Calculate x / y rounding towards zero. Revert on overflow or when y is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function div (int128 x, int128 y) internal pure returns (int128) {
require (y != 0);
int256 result = (int256 (x) << 64) / y;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate x / y rounding towards zero, where x and y are signed 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x signed 256-bit integer number
* @param y signed 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divi (int256 x, int256 y) internal pure returns (int128) {
require (y != 0);
bool negativeResult = false;
if (x < 0) {
x = -x; // We rely on overflow behavior here
negativeResult = true;
}
if (y < 0) {
y = -y; // We rely on overflow behavior here
negativeResult = !negativeResult;
}
uint128 absoluteResult = divuu (uint256 (x), uint256 (y));
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return signed 64.64-bit fixed point number
*/
function divu (uint256 x, uint256 y) internal pure returns (int128) {
require (y != 0);
uint128 result = divuu (x, y);
require (result <= uint128 (MAX_64x64));
return int128 (result);
}
/**
* Calculate -x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function neg (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return -x;
}
/**
* Calculate |x|. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function abs (int128 x) internal pure returns (int128) {
require (x != MIN_64x64);
return x < 0 ? -x : x;
}
/**
* Calculate 1 / x rounding towards zero. Revert on overflow or when x is
* zero.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function inv (int128 x) internal pure returns (int128) {
require (x != 0);
int256 result = int256 (0x100000000000000000000000000000000) / x;
require (result >= MIN_64x64 && result <= MAX_64x64);
return int128 (result);
}
/**
* Calculate arithmetics average of x and y, i.e. (x + y) / 2 rounding down.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function avg (int128 x, int128 y) internal pure returns (int128) {
return int128 ((int256 (x) + int256 (y)) >> 1);
}
/**
* Calculate geometric average of x and y, i.e. sqrt (x * y) rounding down.
* Revert on overflow or in case x * y is negative.
*
* @param x signed 64.64-bit fixed point number
* @param y signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function gavg (int128 x, int128 y) internal pure returns (int128) {
int256 m = int256 (x) * int256 (y);
require (m >= 0);
require (m <
0x4000000000000000000000000000000000000000000000000000000000000000);
return int128 (sqrtu (uint256 (m), uint256 (x) + uint256 (y) >> 1));
}
/**
* Calculate x^y assuming 0^0 is 1, where x is signed 64.64 fixed point number
* and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @param y uint256 value
* @return signed 64.64-bit fixed point number
*/
function pow (int128 x, uint256 y) internal pure returns (int128) {
uint256 absoluteResult;
bool negativeResult = false;
if (x >= 0) {
absoluteResult = powu (uint256 (x) << 63, y);
} else {
// We rely on overflow behavior here
absoluteResult = powu (uint256 (uint128 (-x)) << 63, y);
negativeResult = y & 1 > 0;
}
absoluteResult >>= 63;
if (negativeResult) {
require (absoluteResult <= 0x80000000000000000000000000000000);
return -int128 (absoluteResult); // We rely on overflow behavior here
} else {
require (absoluteResult <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return int128 (absoluteResult); // We rely on overflow behavior here
}
}
/**
* Calculate sqrt (x) rounding down. Revert if x < 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function sqrt (int128 x) internal pure returns (int128) {
require (x >= 0);
return int128 (sqrtu (uint256 (x) << 64, 0x10000000000000000));
}
/**
* Calculate binary logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function log_2 (int128 x) internal pure returns (int128) {
require (x > 0);
int256 msb = 0;
int256 xc = x;
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 result = msb - 64 << 64;
uint256 ux = uint256 (x) << 127 - msb;
for (int256 bit = 0x8000000000000000; bit > 0; bit >>= 1) {
ux *= ux;
uint256 b = ux >> 255;
ux >>= 127 + b;
result += bit * int256 (b);
}
return int128 (result);
}
/**
* Calculate natural logarithm of x. Revert if x <= 0.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function ln (int128 x) internal pure returns (int128) {
require (x > 0);
return int128 (
uint256 (log_2 (x)) * 0xB17217F7D1CF79ABC9E3B39803F2F6AF >> 128);
}
/**
* Calculate binary exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp_2 (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
uint256 result = 0x80000000000000000000000000000000;
if (x & 0x8000000000000000 > 0)
result = result * 0x16A09E667F3BCC908B2FB1366EA957D3E >> 128;
if (x & 0x4000000000000000 > 0)
result = result * 0x1306FE0A31B7152DE8D5A46305C85EDEC >> 128;
if (x & 0x2000000000000000 > 0)
result = result * 0x1172B83C7D517ADCDF7C8C50EB14A791F >> 128;
if (x & 0x1000000000000000 > 0)
result = result * 0x10B5586CF9890F6298B92B71842A98363 >> 128;
if (x & 0x800000000000000 > 0)
result = result * 0x1059B0D31585743AE7C548EB68CA417FD >> 128;
if (x & 0x400000000000000 > 0)
result = result * 0x102C9A3E778060EE6F7CACA4F7A29BDE8 >> 128;
if (x & 0x200000000000000 > 0)
result = result * 0x10163DA9FB33356D84A66AE336DCDFA3F >> 128;
if (x & 0x100000000000000 > 0)
result = result * 0x100B1AFA5ABCBED6129AB13EC11DC9543 >> 128;
if (x & 0x80000000000000 > 0)
result = result * 0x10058C86DA1C09EA1FF19D294CF2F679B >> 128;
if (x & 0x40000000000000 > 0)
result = result * 0x1002C605E2E8CEC506D21BFC89A23A00F >> 128;
if (x & 0x20000000000000 > 0)
result = result * 0x100162F3904051FA128BCA9C55C31E5DF >> 128;
if (x & 0x10000000000000 > 0)
result = result * 0x1000B175EFFDC76BA38E31671CA939725 >> 128;
if (x & 0x8000000000000 > 0)
result = result * 0x100058BA01FB9F96D6CACD4B180917C3D >> 128;
if (x & 0x4000000000000 > 0)
result = result * 0x10002C5CC37DA9491D0985C348C68E7B3 >> 128;
if (x & 0x2000000000000 > 0)
result = result * 0x1000162E525EE054754457D5995292026 >> 128;
if (x & 0x1000000000000 > 0)
result = result * 0x10000B17255775C040618BF4A4ADE83FC >> 128;
if (x & 0x800000000000 > 0)
result = result * 0x1000058B91B5BC9AE2EED81E9B7D4CFAB >> 128;
if (x & 0x400000000000 > 0)
result = result * 0x100002C5C89D5EC6CA4D7C8ACC017B7C9 >> 128;
if (x & 0x200000000000 > 0)
result = result * 0x10000162E43F4F831060E02D839A9D16D >> 128;
if (x & 0x100000000000 > 0)
result = result * 0x100000B1721BCFC99D9F890EA06911763 >> 128;
if (x & 0x80000000000 > 0)
result = result * 0x10000058B90CF1E6D97F9CA14DBCC1628 >> 128;
if (x & 0x40000000000 > 0)
result = result * 0x1000002C5C863B73F016468F6BAC5CA2B >> 128;
if (x & 0x20000000000 > 0)
result = result * 0x100000162E430E5A18F6119E3C02282A5 >> 128;
if (x & 0x10000000000 > 0)
result = result * 0x1000000B1721835514B86E6D96EFD1BFE >> 128;
if (x & 0x8000000000 > 0)
result = result * 0x100000058B90C0B48C6BE5DF846C5B2EF >> 128;
if (x & 0x4000000000 > 0)
result = result * 0x10000002C5C8601CC6B9E94213C72737A >> 128;
if (x & 0x2000000000 > 0)
result = result * 0x1000000162E42FFF037DF38AA2B219F06 >> 128;
if (x & 0x1000000000 > 0)
result = result * 0x10000000B17217FBA9C739AA5819F44F9 >> 128;
if (x & 0x800000000 > 0)
result = result * 0x1000000058B90BFCDEE5ACD3C1CEDC823 >> 128;
if (x & 0x400000000 > 0)
result = result * 0x100000002C5C85FE31F35A6A30DA1BE50 >> 128;
if (x & 0x200000000 > 0)
result = result * 0x10000000162E42FF0999CE3541B9FFFCF >> 128;
if (x & 0x100000000 > 0)
result = result * 0x100000000B17217F80F4EF5AADDA45554 >> 128;
if (x & 0x80000000 > 0)
result = result * 0x10000000058B90BFBF8479BD5A81B51AD >> 128;
if (x & 0x40000000 > 0)
result = result * 0x1000000002C5C85FDF84BD62AE30A74CC >> 128;
if (x & 0x20000000 > 0)
result = result * 0x100000000162E42FEFB2FED257559BDAA >> 128;
if (x & 0x10000000 > 0)
result = result * 0x1000000000B17217F7D5A7716BBA4A9AE >> 128;
if (x & 0x8000000 > 0)
result = result * 0x100000000058B90BFBE9DDBAC5E109CCE >> 128;
if (x & 0x4000000 > 0)
result = result * 0x10000000002C5C85FDF4B15DE6F17EB0D >> 128;
if (x & 0x2000000 > 0)
result = result * 0x1000000000162E42FEFA494F1478FDE05 >> 128;
if (x & 0x1000000 > 0)
result = result * 0x10000000000B17217F7D20CF927C8E94C >> 128;
if (x & 0x800000 > 0)
result = result * 0x1000000000058B90BFBE8F71CB4E4B33D >> 128;
if (x & 0x400000 > 0)
result = result * 0x100000000002C5C85FDF477B662B26945 >> 128;
if (x & 0x200000 > 0)
result = result * 0x10000000000162E42FEFA3AE53369388C >> 128;
if (x & 0x100000 > 0)
result = result * 0x100000000000B17217F7D1D351A389D40 >> 128;
if (x & 0x80000 > 0)
result = result * 0x10000000000058B90BFBE8E8B2D3D4EDE >> 128;
if (x & 0x40000 > 0)
result = result * 0x1000000000002C5C85FDF4741BEA6E77E >> 128;
if (x & 0x20000 > 0)
result = result * 0x100000000000162E42FEFA39FE95583C2 >> 128;
if (x & 0x10000 > 0)
result = result * 0x1000000000000B17217F7D1CFB72B45E1 >> 128;
if (x & 0x8000 > 0)
result = result * 0x100000000000058B90BFBE8E7CC35C3F0 >> 128;
if (x & 0x4000 > 0)
result = result * 0x10000000000002C5C85FDF473E242EA38 >> 128;
if (x & 0x2000 > 0)
result = result * 0x1000000000000162E42FEFA39F02B772C >> 128;
if (x & 0x1000 > 0)
result = result * 0x10000000000000B17217F7D1CF7D83C1A >> 128;
if (x & 0x800 > 0)
result = result * 0x1000000000000058B90BFBE8E7BDCBE2E >> 128;
if (x & 0x400 > 0)
result = result * 0x100000000000002C5C85FDF473DEA871F >> 128;
if (x & 0x200 > 0)
result = result * 0x10000000000000162E42FEFA39EF44D91 >> 128;
if (x & 0x100 > 0)
result = result * 0x100000000000000B17217F7D1CF79E949 >> 128;
if (x & 0x80 > 0)
result = result * 0x10000000000000058B90BFBE8E7BCE544 >> 128;
if (x & 0x40 > 0)
result = result * 0x1000000000000002C5C85FDF473DE6ECA >> 128;
if (x & 0x20 > 0)
result = result * 0x100000000000000162E42FEFA39EF366F >> 128;
if (x & 0x10 > 0)
result = result * 0x1000000000000000B17217F7D1CF79AFA >> 128;
if (x & 0x8 > 0)
result = result * 0x100000000000000058B90BFBE8E7BCD6D >> 128;
if (x & 0x4 > 0)
result = result * 0x10000000000000002C5C85FDF473DE6B2 >> 128;
if (x & 0x2 > 0)
result = result * 0x1000000000000000162E42FEFA39EF358 >> 128;
if (x & 0x1 > 0)
result = result * 0x10000000000000000B17217F7D1CF79AB >> 128;
result >>= 63 - (x >> 64);
require (result <= uint256 (MAX_64x64));
return int128 (result);
}
/**
* Calculate natural exponent of x. Revert on overflow.
*
* @param x signed 64.64-bit fixed point number
* @return signed 64.64-bit fixed point number
*/
function exp (int128 x) internal pure returns (int128) {
require (x < 0x400000000000000000); // Overflow
if (x < -0x400000000000000000) return 0; // Underflow
return exp_2 (
int128 (int256 (x) * 0x171547652B82FE1777D0FFDA0D23A7D12 >> 128));
}
/**
* Calculate x / y rounding towards zero, where x and y are unsigned 256-bit
* integer numbers. Revert on overflow or when y is zero.
*
* @param x unsigned 256-bit integer number
* @param y unsigned 256-bit integer number
* @return unsigned 64.64-bit fixed point number
*/
function divuu (uint256 x, uint256 y) private pure returns (uint128) {
require (y != 0);
uint256 result;
if (x <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)
result = (x << 64) / y;
else {
uint256 msb = 192;
uint256 xc = x >> 192;
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
result = (x << 255 - msb) / ((y - 1 >> msb - 191) + 1);
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 hi = result * (y >> 128);
uint256 lo = result * (y & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
uint256 xh = x >> 192;
uint256 xl = x << 64;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
lo = hi << 128;
if (xl < lo) xh -= 1;
xl -= lo; // We rely on overflow behavior here
assert (xh == hi >> 128);
result += xl / y;
}
require (result <= 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF);
return uint128 (result);
}
/**
* Calculate x^y assuming 0^0 is 1, where x is unsigned 129.127 fixed point
* number and y is unsigned 256-bit integer number. Revert on overflow.
*
* @param x unsigned 129.127-bit fixed point number
* @param y uint256 value
* @return unsigned 129.127-bit fixed point number
*/
function powu (uint256 x, uint256 y) private pure returns (uint256) {
if (y == 0) return 0x80000000000000000000000000000000;
else if (x == 0) return 0;
else {
int256 msb = 0;
uint256 xc = x;
if (xc >= 0x100000000000000000000000000000000) { xc >>= 128; msb += 128; }
if (xc >= 0x10000000000000000) { xc >>= 64; msb += 64; }
if (xc >= 0x100000000) { xc >>= 32; msb += 32; }
if (xc >= 0x10000) { xc >>= 16; msb += 16; }
if (xc >= 0x100) { xc >>= 8; msb += 8; }
if (xc >= 0x10) { xc >>= 4; msb += 4; }
if (xc >= 0x4) { xc >>= 2; msb += 2; }
if (xc >= 0x2) msb += 1; // No need to shift xc anymore
int256 xe = msb - 127;
if (xe > 0) x >>= xe;
else x <<= -xe;
uint256 result = 0x80000000000000000000000000000000;
int256 re = 0;
while (y > 0) {
if (y & 1 > 0) {
result = result * x;
y -= 1;
re += xe;
if (result >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
result >>= 128;
re += 1;
} else result >>= 127;
if (re < -127) return 0; // Underflow
require (re < 128); // Overflow
} else {
x = x * x;
y >>= 1;
xe <<= 1;
if (x >=
0x8000000000000000000000000000000000000000000000000000000000000000) {
x >>= 128;
xe += 1;
} else x >>= 127;
if (xe < -127) return 0; // Underflow
require (xe < 128); // Overflow
}
}
if (re > 0) result <<= re;
else if (re < 0) result >>= -re;
return result;
}
}
/**
* Calculate sqrt (x) rounding down, where x is unsigned 256-bit integer
* number.
*
* @param x unsigned 256-bit integer number
* @return unsigned 128-bit integer number
*/
function sqrtu (uint256 x, uint256 r) private pure returns (uint128) {
if (x == 0) return 0;
else {
require (r > 0);
while (true) {
uint256 rr = x / r;
if (r == rr || r + 1 == rr) return uint128 (r);
else if (r == rr + 1) return uint128 (rr);
r = r + rr + 1 >> 1;
}
}
}
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// File: contracts/CoFiXController04.sol
pragma solidity 0.6.12;
// Controller contract to call NEST Oracle for prices, managed by governance
// Governance role of this contract should be the `Timelock` contract, which is further managed by a multisig contract
contract CoFiXController04 is ICoFiXController { // ctrl-03: change contract name to avoid truffle complaint
using SafeMath for uint256;
enum CoFiX_OP { QUERY, MINT, BURN, SWAP_WITH_EXACT, SWAP_FOR_EXACT } // operations in CoFiX
uint256 constant public AONE = 1 ether;
uint256 constant public K_BASE = 1E8;
uint256 constant public NAVPS_BASE = 1E18; // NAVPS (Net Asset Value Per Share), need accuracy
uint256 internal T = 900; // ctrl-v2: V1 (900) -> V2 (600)
uint256 internal K_EXPECTED_VALUE = 0.005*1E8; // ctrl-v2: V1 (0.0025) -> V2 (0.005)
// impact cost params
uint256 constant internal C_BUYIN_ALPHA = 25700000000000; // α=2.570e-05*1e18
uint256 constant internal C_BUYIN_BETA = 854200000000; // β=8.542e-07*1e18
uint256 constant internal C_SELLOUT_ALPHA = 117100000000000; // α=-1.171e-04*1e18
uint256 constant internal C_SELLOUT_BETA = 838600000000; // β=8.386e-07*1e18
int128 constant internal SIGMA_STEP = 0x346DC5D638865; // (0.00005*2**64).toString(16), 0.00005 as 64.64-bit fixed point
int128 constant internal ZERO_POINT_FIVE = 0x8000000000000000; // (0.5*2**64).toString(16)
uint256 constant PRICE_DEVIATION = 10; // price deviation < 10%
mapping(address => uint32[3]) internal KInfoMap; // gas saving, index [0] is k vlaue, index [1] is updatedAt, index [2] is theta
mapping(address => bool) public callerAllowed;
// managed by governance
address public governance;
address public immutable oracle;
address public immutable nestToken;
address public immutable factory;
address public kTable;
uint256 public timespan = 14;
uint256 public kRefreshInterval = 5 minutes;
uint256 public DESTRUCTION_AMOUNT = 0 ether; // from nest oracle
int128 public MAX_K0 = 0xCCCCCCCCCCCCD00; // (0.05*2**64).toString(16)
int128 public GAMMA = 0x8000000000000000; // (0.5*2**64).toString(16)
struct OracleParams {
uint256 ethAmount;
uint256 erc20Amount;
uint256 blockNum;
uint256 K;
uint256 T; // time offset
uint256 avgPrice; // average price
uint256 theta;
uint256 sigma;
uint256 tIdx;
uint256 sigmaIdx;
}
modifier onlyGovernance() {
require(msg.sender == governance, "CoFiXCtrl: !governance");
_;
}
constructor(address _oracle, address _nest, address _factory, address _kTable) public {
governance = msg.sender;
oracle = _oracle;
nestToken = _nest;
factory = _factory;
kTable = _kTable;
// add previous pair as caller
ICoFiXFactory cFactory = ICoFiXFactory(_factory);
uint256 pairCnt = cFactory.allPairsLength();
for (uint256 i = 0; i < pairCnt; i++) {
address pair = cFactory.allPairs(i);
callerAllowed[pair] = true;
}
}
receive() external payable {}
/* setters for protocol governance */
function setGovernance(address _new) external onlyGovernance {
governance = _new;
emit NewGovernance(_new);
}
function setKTable(address _kTable) external onlyGovernance {
kTable = _kTable;
emit NewKTable(_kTable);
}
function setTimespan(uint256 _timeSpan) external onlyGovernance {
timespan = _timeSpan;
emit NewTimespan(_timeSpan);
}
function setKRefreshInterval(uint256 _interval) external onlyGovernance {
kRefreshInterval = _interval;
emit NewKRefreshInterval(_interval);
}
function setOracleDestructionAmount(uint256 _amount) external onlyGovernance {
DESTRUCTION_AMOUNT = _amount;
}
function setTLimit(uint256 _T) external onlyGovernance { // ctrl-v2: new setter for T
T = _T;
}
function setK(address token, uint32 k) external onlyGovernance { // ctrl-v2: new setter for K, adjustable by governance
K_EXPECTED_VALUE = uint256(k);
emit NewK(token, k); // new event for setting K
}
function setTheta(address token, uint32 theta) external onlyGovernance {
KInfoMap[token][2] = theta;
emit NewTheta(token, theta);
}
function addCaller(address caller) external override {
require(msg.sender == factory || msg.sender == governance, "CoFiXCtrl: only factory or gov");
callerAllowed[caller] = true;
}
// Calc variance of price and K in CoFiX is very expensive
// We use expected value of K based on statistical calculations here to save gas
// In the near future, NEST could provide the variance of price directly. We will adopt it then.
// We can make use of `data` bytes in the future
function queryOracle(address token, uint8 op, bytes memory data) external override payable returns (uint256 _k, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum, uint256 _theta) {
require(callerAllowed[msg.sender], "CoFiXCtrl: caller not allowed");
(_k, _ethAmount, _erc20Amount, _blockNum) = getLatestPrice(token);
CoFiX_OP cop = CoFiX_OP(op);
uint256 impactCost;
if (cop == CoFiX_OP.SWAP_WITH_EXACT) {
impactCost = calcImpactCostFor_SWAP_WITH_EXACT(token, data, _ethAmount, _erc20Amount);
} else if (cop == CoFiX_OP.SWAP_FOR_EXACT) {
revert("disabled experimental feature!"); // ctrl-v2: disable swapForExact function
} else if (cop == CoFiX_OP.BURN) {
impactCost = calcImpactCostFor_BURN(token, data, _ethAmount, _erc20Amount);
}
_k = _k.add(impactCost); // ctrl-v2: adjustable K + impactCost is the final K
_theta = KInfoMap[token][2];
return (_k, _ethAmount, _erc20Amount, _blockNum, _theta);
}
function calcImpactCostFor_BURN(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public view returns (uint256 impactCost) {
// bytes memory data = abi.encode(msg.sender, outToken, to, liquidity);
(, address outToken, , uint256 liquidity) = abi.decode(data, (address, address, address, uint256));
// calc real vol by liquidity * np
uint256 navps = ICoFiXPair(msg.sender).getNAVPerShare(ethAmount, erc20Amount); // pair call controller, msg.sender is pair
uint256 vol = liquidity.mul(navps).div(NAVPS_BASE);
if (outToken != token) {
// buy in ETH, outToken is ETH
return impactCostForBuyInETH(vol);
}
// sell out liquidity, outToken is token, take this as sell out ETH and get token
return impactCostForSellOutETH(vol);
}
function calcImpactCostFor_SWAP_WITH_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public pure returns (uint256 impactCost) {
(, address outToken, , uint256 amountIn) = abi.decode(data, (address, address, address, uint256));
if (outToken != token) {
// buy in ETH, outToken is ETH, amountIn is token
// convert to amountIn in ETH
uint256 vol = uint256(amountIn).mul(ethAmount).div(erc20Amount);
return impactCostForBuyInETH(vol);
}
// sell out ETH, amountIn is ETH
return impactCostForSellOutETH(amountIn);
}
function calcImpactCostFor_SWAP_FOR_EXACT(address token, bytes memory data, uint256 ethAmount, uint256 erc20Amount) public pure returns (uint256 impactCost) {
(, address outToken, uint256 amountOutExact,) = abi.decode(data, (address, address, uint256, address));
if (outToken != token) {
// buy in ETH, outToken is ETH, amountOutExact is ETH
return impactCostForBuyInETH(amountOutExact);
}
// sell out ETH, amountIn is ETH, amountOutExact is token
// convert to amountOutExact in ETH
uint256 vol = uint256(amountOutExact).mul(ethAmount).div(erc20Amount);
return impactCostForSellOutETH(vol);
}
// impact cost
// - C = 0, if VOL < 500
// - C = α + β * VOL, if VOL >= 500
// α=2.570e-05,β=8.542e-07
function impactCostForBuyInETH(uint256 vol) public pure returns (uint256 impactCost) {
if (vol < 500 ether) {
return 0;
}
// return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).mul(1e8).div(1e18);
return C_BUYIN_ALPHA.add(C_BUYIN_BETA.mul(vol).div(1e18)).div(1e10); // combine mul div
}
// α=-1.171e-04,β=8.386e-07
function impactCostForSellOutETH(uint256 vol) public pure returns (uint256 impactCost) {
if (vol < 500 ether) {
return 0;
}
// return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).mul(1e8).div(1e18);
return (C_SELLOUT_BETA.mul(vol).div(1e18)).sub(C_SELLOUT_ALPHA).div(1e10); // combine mul div
}
function getKInfo(address token) external view returns (uint32 k, uint32 updatedAt, uint32 theta) {
// ctrl-v3: load from storage instead of constant value
uint32 kStored = KInfoMap[token][0];
if (kStored != 0) {
k = kStored;
} else {
k = uint32(K_EXPECTED_VALUE);
}
updatedAt = KInfoMap[token][1];
theta = KInfoMap[token][2];
}
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint y) internal pure returns (uint z) {
if (y > 3) {
z = y;
uint x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
function getLatestPrice(address token) internal returns (uint256 _k, uint256 _ethAmount, uint256 _erc20Amount, uint256 _blockNum) {
uint256 _balanceBefore = address(this).balance;
OracleParams memory _op;
// query oracle
/// latestPriceBlockNumber The block number of latest price
/// latestPriceValue The token latest price. (1eth equivalent to (price) token)
/// triggeredPriceBlockNumber The block number of triggered price
/// triggeredPriceValue The token triggered price. (1eth equivalent to (price) token)
/// triggeredAvgPrice Average price
/// triggeredSigmaSQ The square of the volatility (18 decimal places).
(
_op.blockNum,
_op.erc20Amount,
/* uint triggeredPriceBlockNumber */,
/* uint triggeredPriceValue */,
_op.avgPrice,
_op.sigma
) = INestPriceFacade(oracle).latestPriceAndTriggeredPriceInfo{value: msg.value}(token, address(this));
_op.sigma = sqrt(_op.sigma.mul(1e18));
_op.ethAmount = 1 ether;
// validate T
_op.T = block.number.sub(_op.blockNum).mul(timespan);
require(_op.T < T, "CoFiXCtrl: oralce price outdated"); // ctrl-v2: adjustable T
{
// check if the price is steady
uint256 price;
bool isDeviated;
price = _op.erc20Amount.mul(1e18).div(_op.ethAmount);
uint256 diff = price > _op.avgPrice? (price - _op.avgPrice) : (_op.avgPrice - price);
isDeviated = (diff.mul(100) < _op.avgPrice.mul(PRICE_DEVIATION))? false : true;
require(isDeviated == false, "CoFiXCtrl: price deviation"); // validate
}
// calc K
// int128 K0; // K0AndK[0]
// int128 K; // K0AndK[1]
int128[2] memory K0AndK;
{
_op.tIdx = (_op.T.add(5)).div(10); // rounding to the nearest
_op.sigmaIdx = ABDKMath64x64.toUInt(
ABDKMath64x64.add(
ABDKMath64x64.div(int128(_op.sigma), SIGMA_STEP), // _sigma / 0.00005, e.g. (0.00098/0.00005)=9.799 => 9
ZERO_POINT_FIVE // e.g. (0.00098/0.00005)+0.5=20.0999 => 20
)
);
if (_op.sigmaIdx > 0) {
_op.sigmaIdx = _op.sigmaIdx.sub(1);
}
// getK0(uint256 tIdx, uint256 sigmaIdx)
// K0 is K0AndK[0]
K0AndK[0] = ICoFiXKTable(kTable).getK0(
_op.tIdx,
_op.sigmaIdx
);
// K = gamma * K0
K0AndK[1] = ABDKMath64x64.mul(GAMMA, K0AndK[0]);
emit NewK(token, K0AndK[1], int128(_op.sigma), _op.T, _op.ethAmount, _op.erc20Amount, _op.blockNum, _op.tIdx, _op.sigmaIdx, K0AndK[0]);
}
require(K0AndK[0] <= MAX_K0, "CoFiXCtrl: K0");
{
// return oracle fee change
// we could decode data in the future to pay the fee change and mining award token directly to reduce call cost
// TransferHelper.safeTransferETH(payback, msg.value.sub(_balanceBefore.sub(address(this).balance)));
uint256 oracleFeeChange = msg.value.sub(_balanceBefore.sub(address(this).balance));
if (oracleFeeChange > 0) TransferHelper.safeTransferETH(msg.sender, oracleFeeChange);
_k = ABDKMath64x64.toUInt(ABDKMath64x64.mul(K0AndK[1], ABDKMath64x64.fromUInt(K_BASE)));
KInfoMap[token][0] = uint32(_k); // k < MAX_K << uint32(-1)
KInfoMap[token][1] = uint32(block.timestamp); // 2106
return (_k, _op.ethAmount, _op.erc20Amount, _op.blockNum);
}
}
/**
* @notice Calc K value
* @param vola The square of the volatility (18 decimal places).
* @param bn The block number when (ETH, TOKEN) price takes into effective
* @return k The K value
*/
function calcK(uint256 vola, uint256 bn) external view returns (uint32 k) {
// int128 K0; // K0AndK[0]
// int128 K; // K0AndK[1]
vola = sqrt(vola.mul(1e18));
int128[2] memory K0AndK;
uint256 _T = block.number.sub(bn).mul(timespan);
uint256 tIdx = (_T.add(5)).div(10); // rounding to the nearest
uint256 sigmaIdx = ABDKMath64x64.toUInt(
ABDKMath64x64.add(
ABDKMath64x64.div(int128(vola), SIGMA_STEP), // _sigma / 0.00005, e.g. (0.00098/0.00005)=9.799 => 9
ZERO_POINT_FIVE // e.g. (0.00098/0.00005)+0.5=20.0999 => 20
)
);
if (sigmaIdx > 0) {
sigmaIdx = sigmaIdx.sub(1);
}
// getK0(uint256 tIdx, uint256 sigmaIdx)
// K0 is K0AndK[0]
K0AndK[0] = ICoFiXKTable(kTable).getK0(
tIdx,
sigmaIdx
);
// K = gamma * K0
K0AndK[1] = ABDKMath64x64.mul(GAMMA, K0AndK[0]);
k = uint32(ABDKMath64x64.toUInt(ABDKMath64x64.mul(K0AndK[1], ABDKMath64x64.fromUInt(K_BASE))));
}
// ctrl-v2: remove unused code bellow according to PeckShield's advice
} | ctrl-v2: new setter for T | function setTLimit(uint256 _T) external onlyGovernance { | 623,036 |
pragma solidity ^0.4.24;
import "openzeppelin-eth/contracts/math/SafeMath.sol";
/**
* @title Props Rewards Library
* @dev Library to manage application and validators and parameters
**/
library PropsRewardsLib {
using SafeMath for uint256;
/*
* Events
*/
/*
* Storage
*/
// The various parameters used by the contract
enum ParameterName { ApplicationRewardsPercent, ApplicationRewardsMaxVariationPercent, ValidatorMajorityPercent, ValidatorRewardsPercent}
enum RewardedEntityType { Application, Validator }
// Represents a parameter current, previous and time of change
struct Parameter {
uint256 currentValue; // current value in Pphm valid after timestamp
uint256 previousValue; // previous value in Pphm for use before timestamp
uint256 rewardsDay; // timestamp of when the value was updated
}
// Represents application details
struct RewardedEntity {
bytes32 name; // Application name
address rewardsAddress; // address where rewards will be minted to
address sidechainAddress; // address used on the sidechain
bool isInitializedState; // A way to check if there's something in the map and whether it is already added to the list
RewardedEntityType entityType; // Type of rewarded entity
}
// Represents validators current and previous lists
struct RewardedEntityList {
mapping (address => bool) current;
mapping (address => bool) previous;
address[] currentList;
address[] previousList;
uint256 rewardsDay;
}
// Represents daily rewards submissions and confirmations
struct DailyRewards {
mapping (bytes32 => Submission) submissions;
bytes32[] submittedRewardsHashes;
uint256 totalSupply;
bytes32 lastConfirmedRewardsHash;
uint256 lastApplicationsRewardsDay;
}
struct Submission {
mapping (address => bool) validators;
address[] validatorsList;
uint256 confirmations;
uint256 finalizedStatus; // 0 - initialized, 1 - finalized
bool isInitializedState; // A way to check if there's something in the map and whether it is already added to the list
}
// represent the storage structures
struct Data {
// applications data
mapping (address => RewardedEntity) applications;
address[] applicationsList;
// validators data
mapping (address => RewardedEntity) validators;
address[] validatorsList;
// adjustable parameters data
mapping (uint256 => Parameter) parameters; // uint256 is the parameter enum index
// the participating validators
RewardedEntityList selectedValidators;
// the participating applications
RewardedEntityList selectedApplications;
// daily rewards submission data
DailyRewards dailyRewards;
uint256 minSecondsBetweenDays;
uint256 rewardsStartTimestamp;
uint256 maxTotalSupply;
uint256 lastValidatorsRewardsDay;
}
/*
* Modifiers
*/
modifier onlyOneConfirmationPerValidatorPerRewardsHash(Data storage _self, bytes32 _rewardsHash) {
require(
!_self.dailyRewards.submissions[_rewardsHash].validators[msg.sender],
"Must be one submission per validator"
);
_;
}
modifier onlyExistingApplications(Data storage _self, address[] _entities) {
for (uint256 i = 0; i < _entities.length; i++) {
require(
_self.applications[_entities[i]].isInitializedState,
"Application must exist"
);
}
_;
}
modifier onlyExistingValidators(Data storage _self, address[] _entities) {
for (uint256 i = 0; i < _entities.length; i++) {
require(
_self.validators[_entities[i]].isInitializedState,
"Validator must exist"
);
}
_;
}
modifier onlySelectedValidators(Data storage _self, uint256 _rewardsDay) {
if (!_usePreviousSelectedRewardsEntityList(_self.selectedValidators, _rewardsDay)) {
require (
_self.selectedValidators.current[msg.sender],
"Must be a current selected validator"
);
} else {
require (
_self.selectedValidators.previous[msg.sender],
"Must be a previous selected validator"
);
}
_;
}
modifier onlyValidRewardsDay(Data storage _self, uint256 _rewardsDay) {
require(
_currentRewardsDay(_self) > _rewardsDay && _rewardsDay > _self.lastValidatorsRewardsDay,
"Must be for a previous day but after the last rewards day"
);
_;
}
modifier onlyValidFutureRewardsDay(Data storage _self, uint256 _rewardsDay) {
require(
_rewardsDay >= _currentRewardsDay(_self),
"Must be future rewardsDay"
);
_;
}
modifier onlyValidAddresses(address _rewardsAddress, address _sidechainAddress) {
require(
_rewardsAddress != address(0) &&
_sidechainAddress != address(0),
"Must have valid rewards and sidechain addresses"
);
_;
}
/**
* @dev The function is called by validators with the calculation of the daily rewards
* @param _self Data pointer to storage
* @param _rewardsDay uint256 the rewards day
* @param _rewardsHash bytes32 hash of the rewards data
* @param _allValidators bool should the calculation be based on all the validators or just those which submitted
*/
function calculateValidatorRewards(
Data storage _self,
uint256 _rewardsDay,
bytes32 _rewardsHash,
bool _allValidators
)
public
view
returns (uint256)
{
uint256 numOfValidators;
if (_self.dailyRewards.submissions[_rewardsHash].finalizedStatus == 1)
{
if (_allValidators) {
numOfValidators = _requiredValidatorsForValidatorsRewards(_self, _rewardsDay);
if (numOfValidators > _self.dailyRewards.submissions[_rewardsHash].confirmations) return 0;
} else {
numOfValidators = _self.dailyRewards.submissions[_rewardsHash].confirmations;
}
uint256 rewardsPerValidator = _getValidatorRewardsDailyAmountPerValidator(_self, _rewardsDay, numOfValidators);
return rewardsPerValidator;
}
return 0;
}
/**
* @dev The function is called by validators with the calculation of the daily rewards
* @param _self Data pointer to storage
* @param _rewardsDay uint256 the rewards day
* @param _rewardsHash bytes32 hash of the rewards data
* @param _applications address[] array of application addresses getting the daily reward
* @param _amounts uint256[] array of amounts each app should get
* @param _currentTotalSupply uint256 current total supply
*/
function calculateAndFinalizeApplicationRewards(
Data storage _self,
uint256 _rewardsDay,
bytes32 _rewardsHash,
address[] _applications,
uint256[] _amounts,
uint256 _currentTotalSupply
)
public
onlyValidRewardsDay(_self, _rewardsDay)
onlyOneConfirmationPerValidatorPerRewardsHash(_self, _rewardsHash)
onlySelectedValidators(_self, _rewardsDay)
returns (uint256)
{
require(
_rewardsHashIsValid(_self, _rewardsDay, _rewardsHash, _applications, _amounts),
"Rewards Hash is invalid"
);
if (!_self.dailyRewards.submissions[_rewardsHash].isInitializedState) {
_self.dailyRewards.submissions[_rewardsHash].isInitializedState = true;
_self.dailyRewards.submittedRewardsHashes.push(_rewardsHash);
}
_self.dailyRewards.submissions[_rewardsHash].validators[msg.sender] = true;
_self.dailyRewards.submissions[_rewardsHash].validatorsList.push(msg.sender);
_self.dailyRewards.submissions[_rewardsHash].confirmations++;
if (_self.dailyRewards.submissions[_rewardsHash].confirmations == _requiredValidatorsForAppRewards(_self, _rewardsDay)) {
uint256 sum = _validateSubmittedData(_self, _applications, _amounts);
require(
sum <= _getMaxAppRewardsDailyAmount(_self, _rewardsDay, _currentTotalSupply),
"Rewards data is invalid - exceed daily variation"
);
_finalizeDailyApplicationRewards(_self, _rewardsDay, _rewardsHash, _currentTotalSupply);
return sum;
}
return 0;
}
/**
* @dev Finalizes the state, rewards Hash, total supply and block timestamp for the day
* @param _self Data pointer to storage
* @param _rewardsDay uint256 the rewards day
* @param _rewardsHash bytes32 the daily rewards hash
* @param _currentTotalSupply uint256 the current total supply
*/
function _finalizeDailyApplicationRewards(Data storage _self, uint256 _rewardsDay, bytes32 _rewardsHash, uint256 _currentTotalSupply)
public
{
_self.dailyRewards.totalSupply = _currentTotalSupply;
_self.dailyRewards.lastConfirmedRewardsHash = _rewardsHash;
_self.dailyRewards.lastApplicationsRewardsDay = _rewardsDay;
_self.dailyRewards.submissions[_rewardsHash].finalizedStatus = 1;
}
/**
* @dev Get parameter's value
* @param _self Data pointer to storage
* @param _name ParameterName name of the parameter
* @param _rewardsDay uint256 the rewards day
*/
function getParameterValue(
Data storage _self,
ParameterName _name,
uint256 _rewardsDay
)
public
view
returns (uint256)
{
if (_rewardsDay >= _self.parameters[uint256(_name)].rewardsDay) {
return _self.parameters[uint256(_name)].currentValue;
} else {
return _self.parameters[uint256(_name)].previousValue;
}
}
/**
* @dev Allows the controller/owner to update rewards parameters
* @param _self Data pointer to storage
* @param _name ParameterName name of the parameter
* @param _value uint256 new value for the parameter
* @param _rewardsDay uint256 the rewards day
*/
function updateParameter(
Data storage _self,
ParameterName _name,
uint256 _value,
uint256 _rewardsDay
)
public
onlyValidFutureRewardsDay(_self, _rewardsDay)
{
if (_rewardsDay <= _self.parameters[uint256(_name)].rewardsDay) {
_self.parameters[uint256(_name)].currentValue = _value;
_self.parameters[uint256(_name)].rewardsDay = _rewardsDay;
} else {
_self.parameters[uint256(_name)].previousValue = _self.parameters[uint256(_name)].currentValue;
_self.parameters[uint256(_name)].currentValue = _value;
_self.parameters[uint256(_name)].rewardsDay = _rewardsDay;
}
}
/**
* @dev Allows an application to add/update its details
* @param _self Data pointer to storage
* @param _entityType RewardedEntityType either application (0) or validator (1)
* @param _name bytes32 name of the app
* @param _rewardsAddress address an address for the app to receive the rewards
* @param _sidechainAddress address the address used for using the sidechain
*/
function updateEntity(
Data storage _self,
RewardedEntityType _entityType,
bytes32 _name,
address _rewardsAddress,
address _sidechainAddress
)
public
onlyValidAddresses(_rewardsAddress, _sidechainAddress)
{
if (_entityType == RewardedEntityType.Application) {
updateApplication(_self, _name, _rewardsAddress, _sidechainAddress);
} else {
updateValidator(_self, _name, _rewardsAddress, _sidechainAddress);
}
}
/**
* @dev Allows an application to add/update its details
* @param _self Data pointer to storage
* @param _name bytes32 name of the app
* @param _rewardsAddress address an address for the app to receive the rewards
* @param _sidechainAddress address the address used for using the sidechain
*/
function updateApplication(
Data storage _self,
bytes32 _name,
address _rewardsAddress,
address _sidechainAddress
)
public
returns (uint256)
{
_self.applications[msg.sender].name = _name;
_self.applications[msg.sender].rewardsAddress = _rewardsAddress;
_self.applications[msg.sender].sidechainAddress = _sidechainAddress;
if (!_self.applications[msg.sender].isInitializedState) {
_self.applicationsList.push(msg.sender);
_self.applications[msg.sender].isInitializedState = true;
_self.applications[msg.sender].entityType = RewardedEntityType.Application;
}
return uint256(RewardedEntityType.Application);
}
/**
* @dev Allows a validator to add/update its details
* @param _self Data pointer to storage
* @param _name bytes32 name of the validator
* @param _rewardsAddress address an address for the validator to receive the rewards
* @param _sidechainAddress address the address used for using the sidechain
*/
function updateValidator(
Data storage _self,
bytes32 _name,
address _rewardsAddress,
address _sidechainAddress
)
public
returns (uint256)
{
_self.validators[msg.sender].name = _name;
_self.validators[msg.sender].rewardsAddress = _rewardsAddress;
_self.validators[msg.sender].sidechainAddress = _sidechainAddress;
if (!_self.validators[msg.sender].isInitializedState) {
_self.validatorsList.push(msg.sender);
_self.validators[msg.sender].isInitializedState = true;
_self.validators[msg.sender].entityType = RewardedEntityType.Validator;
}
return uint256(RewardedEntityType.Validator);
}
/**
* @dev Set new validators list
* @param _self Data pointer to storage
* @param _rewardsDay uint256 the rewards day from which the list should be active
* @param _validators address[] array of validators
*/
function setValidators(
Data storage _self,
uint256 _rewardsDay,
address[] _validators
)
public
onlyValidFutureRewardsDay(_self, _rewardsDay)
onlyExistingValidators(_self, _validators)
{
// no need to update the previous if its' the first time or second update in the same day
if (_rewardsDay > _self.selectedValidators.rewardsDay && _self.selectedValidators.currentList.length > 0)
_updatePreviousEntityList(_self.selectedValidators);
_updateCurrentEntityList(_self.selectedValidators, _validators);
_self.selectedValidators.rewardsDay = _rewardsDay;
}
/**
* @dev Set new applications list
* @param _self Data pointer to storage
* @param _rewardsDay uint256 the rewards day from which the list should be active
* @param _applications address[] array of applications
*/
function setApplications(
Data storage _self,
uint256 _rewardsDay,
address[] _applications
)
public
onlyValidFutureRewardsDay(_self, _rewardsDay)
onlyExistingApplications(_self, _applications)
{
if (_rewardsDay > _self.selectedApplications.rewardsDay && _self.selectedApplications.currentList.length > 0)
_updatePreviousEntityList(_self.selectedApplications);
_updateCurrentEntityList(_self.selectedApplications, _applications);
_self.selectedApplications.rewardsDay = _rewardsDay;
}
/**
* @dev Get applications or validators list
* @param _self Data pointer to storage
* @param _entityType RewardedEntityType either application (0) or validator (1)
* @param _rewardsDay uint256 the rewards day to determine which list to get
*/
function getEntities(
Data storage _self,
RewardedEntityType _entityType,
uint256 _rewardsDay
)
public
view
returns (address[])
{
if (_entityType == RewardedEntityType.Application) {
if (!_usePreviousSelectedRewardsEntityList(_self.selectedApplications, _rewardsDay)) {
return _self.selectedApplications.currentList;
} else {
return _self.selectedApplications.previousList;
}
} else {
if (!_usePreviousSelectedRewardsEntityList(_self.selectedValidators, _rewardsDay)) {
return _self.selectedValidators.currentList;
} else {
return _self.selectedValidators.previousList;
}
}
}
/**
* @dev Get which entity list to use. If true use previous if false use current
* @param _rewardedEntitylist RewardedEntityList pointer to storage
* @param _rewardsDay uint256 the rewards day to determine which list to get
*/
function _usePreviousSelectedRewardsEntityList(RewardedEntityList _rewardedEntitylist, uint256 _rewardsDay)
internal
pure
returns (bool)
{
if (_rewardsDay >= _rewardedEntitylist.rewardsDay) {
return false;
} else {
return true;
}
}
/**
* @dev Checks how many validators are needed for app rewards
* @param _self Data pointer to storage
* @param _rewardsDay uint256 the rewards day
* @param _currentTotalSupply uint256 current total supply
*/
function _getMaxAppRewardsDailyAmount(
Data storage _self,
uint256 _rewardsDay,
uint256 _currentTotalSupply
)
public
view
returns (uint256)
{
return ((_self.maxTotalSupply.sub(_currentTotalSupply)).mul(
getParameterValue(_self, ParameterName.ApplicationRewardsPercent, _rewardsDay)).mul(
getParameterValue(_self, ParameterName.ApplicationRewardsMaxVariationPercent, _rewardsDay))).div(1e16);
}
/**
* @dev Checks how many validators are needed for app rewards
* @param _self Data pointer to storage
* @param _rewardsDay uint256 the rewards day
* @param _numOfValidators uint256 number of validators
*/
function _getValidatorRewardsDailyAmountPerValidator(
Data storage _self,
uint256 _rewardsDay,
uint256 _numOfValidators
)
public
view
returns (uint256)
{
return (((_self.maxTotalSupply.sub(_self.dailyRewards.totalSupply)).mul(
getParameterValue(_self, ParameterName.ValidatorRewardsPercent, _rewardsDay))).div(1e8)).div(_numOfValidators);
}
/**
* @dev Checks if app daily rewards amount is valid
* @param _self Data pointer to storage
* @param _applications address[] array of application addresses getting the daily rewards
* @param _amounts uint256[] array of amounts each app should get
*/
function _validateSubmittedData(
Data storage _self,
address[] _applications,
uint256[] _amounts
)
public
view
returns (uint256)
{
uint256 sum;
bool valid = true;
for (uint256 i = 0; i < _amounts.length; i++) {
sum = sum.add(_amounts[i]);
if (!_self.applications[_applications[i]].isInitializedState) valid = false;
}
require(
sum > 0 && valid,
"Sum zero or none existing app submitted"
);
return sum;
}
/**
* @dev Checks if submitted data matches rewards hash
* @param _rewardsDay uint256 the rewards day
* @param _rewardsHash bytes32 hash of the rewards data
* @param _applications address[] array of application addresses getting the daily rewards
* @param _amounts uint256[] array of amounts each app should get
*/
function _rewardsHashIsValid(
Data storage _self,
uint256 _rewardsDay,
bytes32 _rewardsHash,
address[] _applications,
uint256[] _amounts
)
public
view
returns (bool)
{
bool nonActiveApplication = false;
if (!_usePreviousSelectedRewardsEntityList(_self.selectedApplications, _rewardsDay)) {
for (uint256 i = 0; i < _applications.length; i++) {
if (!_self.selectedApplications.current[_applications[i]]) {
nonActiveApplication = true;
}
}
} else {
for (uint256 j = 0; j < _applications.length; j++) {
if (!_self.selectedApplications.previous[_applications[j]]) {
nonActiveApplication = true;
}
}
}
return
_applications.length > 0 &&
_applications.length == _amounts.length &&
!nonActiveApplication &&
keccak256(abi.encodePacked(_rewardsDay, _applications.length, _amounts.length, _applications, _amounts)) == _rewardsHash;
}
/**
* @dev Checks how many validators are needed for app rewards
* @param _self Data pointer to storage
* @param _rewardsDay uint256 the rewards day
*/
function _requiredValidatorsForValidatorsRewards(Data storage _self, uint256 _rewardsDay)
public
view
returns (uint256)
{
if (!_usePreviousSelectedRewardsEntityList(_self.selectedValidators, _rewardsDay)) {
return _self.selectedValidators.currentList.length;
} else {
return _self.selectedValidators.previousList.length;
}
}
/**
* @dev Checks how many validators are needed for app rewards
* @param _self Data pointer to storage
* @param _rewardsDay uint256 the rewards day
*/
function _requiredValidatorsForAppRewards(Data storage _self, uint256 _rewardsDay)
public
view
returns (uint256)
{
if (!_usePreviousSelectedRewardsEntityList(_self.selectedValidators, _rewardsDay)) {
return ((_self.selectedValidators.currentList.length.mul(getParameterValue(_self, ParameterName.ValidatorMajorityPercent, _rewardsDay))).div(1e8)).add(1);
} else {
return ((_self.selectedValidators.previousList.length.mul(getParameterValue(_self, ParameterName.ValidatorMajorityPercent, _rewardsDay))).div(1e8)).add(1);
}
}
/**
* @dev Get rewards day from block.timestamp
* @param _self Data pointer to storage
*/
function _currentRewardsDay(Data storage _self)
public
view
returns (uint256)
{
//the the start time - floor timestamp to previous midnight divided by seconds in a day will give the rewards day number
if (_self.minSecondsBetweenDays > 0) {
return (block.timestamp.sub(_self.rewardsStartTimestamp)).div(_self.minSecondsBetweenDays).add(1);
} else {
return 0;
}
}
/**
* @dev Update current daily applications list.
* If new, push.
* If same size, replace
* If different size, delete, and then push.
* @param _rewardedEntitylist RewardedEntityList pointer to storage
* @param _entities address[] array of entities
*/
//_updateCurrentEntityList(_rewardedEntitylist, _entities,_rewardedEntityType),
function _updateCurrentEntityList(
RewardedEntityList storage _rewardedEntitylist,
address[] _entities
)
internal
{
bool emptyCurrentList = _rewardedEntitylist.currentList.length == 0;
if (!emptyCurrentList && _rewardedEntitylist.currentList.length != _entities.length) {
_deleteCurrentEntityList(_rewardedEntitylist);
emptyCurrentList = true;
}
for (uint256 i = 0; i < _entities.length; i++) {
if (emptyCurrentList) {
_rewardedEntitylist.currentList.push(_entities[i]);
} else {
_rewardedEntitylist.currentList[i] = _entities[i];
}
_rewardedEntitylist.current[_entities[i]] = true;
}
}
/**
* @dev Update previous daily list
* @param _rewardedEntitylist RewardedEntityList pointer to storage
*/
function _updatePreviousEntityList(RewardedEntityList storage _rewardedEntitylist)
internal
{
bool emptyPreviousList = _rewardedEntitylist.previousList.length == 0;
if (
!emptyPreviousList &&
_rewardedEntitylist.previousList.length != _rewardedEntitylist.currentList.length
) {
_deletePreviousEntityList(_rewardedEntitylist);
emptyPreviousList = true;
}
for (uint256 i = 0; i < _rewardedEntitylist.currentList.length; i++) {
if (emptyPreviousList) {
_rewardedEntitylist.previousList.push(_rewardedEntitylist.currentList[i]);
} else {
_rewardedEntitylist.previousList[i] = _rewardedEntitylist.currentList[i];
}
_rewardedEntitylist.previous[_rewardedEntitylist.currentList[i]] = true;
}
}
/**
* @dev Delete existing values from the current list
* @param _rewardedEntitylist RewardedEntityList pointer to storage
*/
function _deleteCurrentEntityList(RewardedEntityList storage _rewardedEntitylist)
internal
{
for (uint256 i = 0; i < _rewardedEntitylist.currentList.length ; i++) {
delete _rewardedEntitylist.current[_rewardedEntitylist.currentList[i]];
}
delete _rewardedEntitylist.currentList;
}
/**
* @dev Delete existing values from the previous applications list
* @param _rewardedEntitylist RewardedEntityList pointer to storage
*/
function _deletePreviousEntityList(RewardedEntityList storage _rewardedEntitylist)
internal
{
for (uint256 i = 0; i < _rewardedEntitylist.previousList.length ; i++) {
delete _rewardedEntitylist.previous[_rewardedEntitylist.previousList[i]];
}
delete _rewardedEntitylist.previousList;
}
/**
* @dev Deletes rewards day submission data
* @param _self Data pointer to storage
* @param _rewardsHash bytes32 rewardsHash
*/
function _resetDailyRewards(
Data storage _self,
bytes32 _rewardsHash
)
public
{
_self.lastValidatorsRewardsDay = _self.dailyRewards.lastApplicationsRewardsDay;
for (uint256 j = 0; j < _self.dailyRewards.submissions[_rewardsHash].validatorsList.length; j++) {
delete(
_self.dailyRewards.submissions[_rewardsHash].validators[_self.dailyRewards.submissions[_rewardsHash].validatorsList[j]]
);
}
delete _self.dailyRewards.submissions[_rewardsHash].validatorsList;
_self.dailyRewards.submissions[_rewardsHash].confirmations = 0;
_self.dailyRewards.submissions[_rewardsHash].finalizedStatus = 0;
_self.dailyRewards.submissions[_rewardsHash].isInitializedState = false;
}
} | Checks if submitted data matches rewards hash _rewardsDay uint256 the rewards day _rewardsHash bytes32 hash of the rewards data _applications address[] array of application addresses getting the daily rewards _amounts uint256[] array of amounts each app should get/ | function _rewardsHashIsValid(
Data storage _self,
uint256 _rewardsDay,
bytes32 _rewardsHash,
address[] _applications,
uint256[] _amounts
)
public
view
returns (bool)
{
bool nonActiveApplication = false;
if (!_usePreviousSelectedRewardsEntityList(_self.selectedApplications, _rewardsDay)) {
for (uint256 i = 0; i < _applications.length; i++) {
if (!_self.selectedApplications.current[_applications[i]]) {
nonActiveApplication = true;
}
}
for (uint256 j = 0; j < _applications.length; j++) {
if (!_self.selectedApplications.previous[_applications[j]]) {
nonActiveApplication = true;
}
}
}
return
_applications.length > 0 &&
_applications.length == _amounts.length &&
!nonActiveApplication &&
keccak256(abi.encodePacked(_rewardsDay, _applications.length, _amounts.length, _applications, _amounts)) == _rewardsHash;
}
| 12,700,626 |
// SPDX-License-Identifier: SEE LICENSE IN LICENSE
pragma solidity 0.6.12;
import "../utility/TokenHandler.sol";
import "../utility/ContractRegistryClient.sol";
import "./interfaces/IConverter.sol";
import "./interfaces/IConverterFactory.sol";
import "./interfaces/IConverterRegistry.sol";
import "./interfaces/IConverterRegistryData.sol";
import "../token/interfaces/IDSToken.sol";
/**
* @dev The ConverterRegistry maintains a list of all active converters in the Bancor Network.
*
* Since converters can be upgraded and thus their address can change, the registry actually keeps
* converter anchors internally and not the converters themselves.
* The active converter for each anchor can be easily accessed by querying the anchor's owner.
*
* The registry exposes 3 differnet lists that can be accessed and iterated, based on the use-case of the caller:
* - Anchors - can be used to get all the latest / historical data in the network
* - Liquidity pools - can be used to get all liquidity pools for funding, liquidation etc.
* - Convertible tokens - can be used to get all tokens that can be converted in the network (excluding pool
* tokens), and for each one - all anchors that hold it in their reserves
*
*
* The contract fires events whenever one of the primitives is added to or removed from the registry
*
* The contract is upgradable.
*/
contract ConverterRegistry is IConverterRegistry, ContractRegistryClient, TokenHandler {
/**
* @dev triggered when a converter anchor is added to the registry
*
* @param _anchor anchor token
*/
event ConverterAnchorAdded(IConverterAnchor indexed _anchor);
/**
* @dev triggered when a converter anchor is removed from the registry
*
* @param _anchor anchor token
*/
event ConverterAnchorRemoved(IConverterAnchor indexed _anchor);
/**
* @dev triggered when a liquidity pool is added to the registry
*
* @param _liquidityPool liquidity pool
*/
event LiquidityPoolAdded(IConverterAnchor indexed _liquidityPool);
/**
* @dev triggered when a liquidity pool is removed from the registry
*
* @param _liquidityPool liquidity pool
*/
event LiquidityPoolRemoved(IConverterAnchor indexed _liquidityPool);
/**
* @dev triggered when a convertible token is added to the registry
*
* @param _convertibleToken convertible token
* @param _smartToken associated anchor token
*/
event ConvertibleTokenAdded(IERC20Token indexed _convertibleToken, IConverterAnchor indexed _smartToken);
/**
* @dev triggered when a convertible token is removed from the registry
*
* @param _convertibleToken convertible token
* @param _smartToken associated anchor token
*/
event ConvertibleTokenRemoved(IERC20Token indexed _convertibleToken, IConverterAnchor indexed _smartToken);
/**
* @dev deprecated, backward compatibility, use `ConverterAnchorAdded`
*/
event SmartTokenAdded(IConverterAnchor indexed _smartToken);
/**
* @dev deprecated, backward compatibility, use `ConverterAnchorRemoved`
*/
event SmartTokenRemoved(IConverterAnchor indexed _smartToken);
/**
* @dev initializes a new ConverterRegistry instance
*
* @param _registry address of a contract registry contract
*/
constructor(IContractRegistry _registry) ContractRegistryClient(_registry) public {
}
/**
* @dev creates a zero supply liquid token / empty liquidity pool and adds its converter to the registry
*
* @param _type converter type, see ConverterBase contract main doc
* @param _name token / pool name
* @param _symbol token / pool symbol
* @param _decimals token / pool decimals
* @param _maxConversionFee maximum conversion-fee
* @param _reserveTokens reserve tokens
* @param _reserveWeights reserve weights
*
* @return new converter
*/
function newConverter(
uint16 _type,
string memory _name,
string memory _symbol,
uint8 _decimals,
uint32 _maxConversionFee,
IERC20Token[] memory _reserveTokens,
uint32[] memory _reserveWeights
)
public virtual returns (IConverter)
{
uint256 length = _reserveTokens.length;
require(length == _reserveWeights.length, "ERR_INVALID_RESERVES");
require(getLiquidityPoolByConfig(_type, _reserveTokens, _reserveWeights) == IConverterAnchor(0), "ERR_ALREADY_EXISTS");
IConverterFactory factory = IConverterFactory(addressOf(CONVERTER_FACTORY));
IConverterAnchor anchor = IConverterAnchor(factory.createAnchor(_type, _name, _symbol, _decimals));
IConverter converter = IConverter(factory.createConverter(_type, anchor, registry, _maxConversionFee));
anchor.acceptOwnership();
converter.acceptOwnership();
for (uint256 i = 0; i < length; i++)
converter.addReserve(_reserveTokens[i], _reserveWeights[i]);
anchor.transferOwnership(address(converter));
converter.acceptAnchorOwnership();
converter.transferOwnership(msg.sender);
addConverterInternal(converter);
return converter;
}
/**
* @dev adds an existing converter to the registry
* can only be called by the owner
*
* @param _converter converter
*/
function addConverter(IConverter _converter) public ownerOnly {
require(isConverterValid(_converter), "ERR_INVALID_CONVERTER");
addConverterInternal(_converter);
}
/**
* @dev removes a converter from the registry
* anyone can remove an existing converter from the registry, as long as the converter is invalid
* note that the owner can also remove valid converters
*
* @param _converter converter
*/
function removeConverter(IConverter _converter) public {
require(msg.sender == owner || !isConverterValid(_converter), "ERR_ACCESS_DENIED");
removeConverterInternal(_converter);
}
/**
* @dev returns the number of converter anchors in the registry
*
* @return number of anchors
*/
function getAnchorCount() public view override returns (uint256) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getSmartTokenCount();
}
/**
* @dev returns the list of converter anchors in the registry
*
* @return list of anchors
*/
function getAnchors() public view override returns (address[] memory) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getSmartTokens();
}
/**
* @dev returns the converter anchor at a given index
*
* @param _index index
* @return anchor at the given index
*/
function getAnchor(uint256 _index) public view override returns (IConverterAnchor) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getSmartToken(_index);
}
/**
* @dev checks whether or not a given value is a converter anchor
*
* @param _value value
* @return true if the given value is an anchor, false if not
*/
function isAnchor(address _value) public view override returns (bool) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).isSmartToken(_value);
}
/**
* @dev returns the number of liquidity pools in the registry
*
* @return number of liquidity pools
*/
function getLiquidityPoolCount() public view override returns (uint256) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getLiquidityPoolCount();
}
/**
* @dev returns the list of liquidity pools in the registry
*
* @return list of liquidity pools
*/
function getLiquidityPools() public view override returns (address[] memory) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getLiquidityPools();
}
/**
* @dev returns the liquidity pool at a given index
*
* @param _index index
* @return liquidity pool at the given index
*/
function getLiquidityPool(uint256 _index) public view override returns (IConverterAnchor) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getLiquidityPool(_index);
}
/**
* @dev checks whether or not a given value is a liquidity pool
*
* @param _value value
* @return true if the given value is a liquidity pool, false if not
*/
function isLiquidityPool(address _value) public view override returns (bool) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).isLiquidityPool(_value);
}
/**
* @dev returns the number of convertible tokens in the registry
*
* @return number of convertible tokens
*/
function getConvertibleTokenCount() public view override returns (uint256) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenCount();
}
/**
* @dev returns the list of convertible tokens in the registry
*
* @return list of convertible tokens
*/
function getConvertibleTokens() public view override returns (address[] memory) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokens();
}
/**
* @dev returns the convertible token at a given index
*
* @param _index index
* @return convertible token at the given index
*/
function getConvertibleToken(uint256 _index) public view override returns (IERC20Token) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleToken(_index);
}
/**
* @dev checks whether or not a given value is a convertible token
*
* @param _value value
* @return true if the given value is a convertible token, false if not
*/
function isConvertibleToken(address _value) public view override returns (bool) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).isConvertibleToken(_value);
}
/**
* @dev returns the number of converter anchors associated with a given convertible token
*
* @param _convertibleToken convertible token
* @return number of anchors associated with the given convertible token
*/
function getConvertibleTokenAnchorCount(IERC20Token _convertibleToken) public view override returns (uint256) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartTokenCount(_convertibleToken);
}
/**
* @dev returns the list of aoncerter anchors associated with a given convertible token
*
* @param _convertibleToken convertible token
* @return list of anchors associated with the given convertible token
*/
function getConvertibleTokenAnchors(IERC20Token _convertibleToken) public view override returns (address[] memory) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartTokens(_convertibleToken);
}
/**
* @dev returns the converter anchor associated with a given convertible token at a given index
*
* @param _index index
* @return anchor associated with the given convertible token at the given index
*/
function getConvertibleTokenAnchor(IERC20Token _convertibleToken, uint256 _index) public view override returns (IConverterAnchor) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartToken(_convertibleToken, _index);
}
/**
* @dev checks whether or not a given value is a converter anchor of a given convertible token
*
* @param _convertibleToken convertible token
* @param _value value
* @return true if the given value is an anchor of the given convertible token, false if not
*/
function isConvertibleTokenAnchor(IERC20Token _convertibleToken, address _value) public view override returns (bool) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).isConvertibleTokenSmartToken(_convertibleToken, _value);
}
/**
* @dev returns a list of converters for a given list of anchors
* this is a utility function that can be used to reduce the number of calls to the contract
*
* @param _anchors list of converter anchors
* @return list of converters
*/
function getConvertersByAnchors(address[] memory _anchors) public view returns (IConverter[] memory) {
IConverter[] memory converters = new IConverter[](_anchors.length);
for (uint256 i = 0; i < _anchors.length; i++)
converters[i] = IConverter(payable(IConverterAnchor(_anchors[i]).owner()));
return converters;
}
/**
* @dev checks whether or not a given converter is valid
*
* @param _converter converter
* @return true if the given converter is valid, false if not
*/
function isConverterValid(IConverter _converter) public view returns (bool) {
// verify that the converter is active
return _converter.token().owner() == address(_converter);
}
/**
* @dev checks if a liquidity pool with given configuration is already registered
*
* @param _converter converter with specific configuration
* @return if a liquidity pool with the same configuration is already registered
*/
function isSimilarLiquidityPoolRegistered(IConverter _converter) public view returns (bool) {
uint256 reserveTokenCount = _converter.connectorTokenCount();
IERC20Token[] memory reserveTokens = new IERC20Token[](reserveTokenCount);
uint32[] memory reserveWeights = new uint32[](reserveTokenCount);
// get the reserve-configuration of the converter
for (uint256 i = 0; i < reserveTokenCount; i++) {
IERC20Token reserveToken = _converter.connectorTokens(i);
reserveTokens[i] = reserveToken;
reserveWeights[i] = getReserveWeight(_converter, reserveToken);
}
// return if a liquidity pool with the same configuration is already registered
return getLiquidityPoolByConfig(getConverterType(_converter, reserveTokenCount), reserveTokens, reserveWeights) != IConverterAnchor(0);
}
/**
* @dev searches for a liquidity pool with specific configuration
*
* @param _type converter type, see ConverterBase contract main doc
* @param _reserveTokens reserve tokens
* @param _reserveWeights reserve weights
* @return the liquidity pool, or zero if no such liquidity pool exists
*/
function getLiquidityPoolByConfig(uint16 _type, IERC20Token[] memory _reserveTokens, uint32[] memory _reserveWeights) public view returns (IConverterAnchor) {
// verify that the input parameters represent a valid liquidity pool
if (_reserveTokens.length == _reserveWeights.length && _reserveTokens.length > 1) {
// get the anchors of the least frequent token (optimization)
address[] memory convertibleTokenAnchors = getLeastFrequentTokenAnchors(_reserveTokens);
// search for a converter with the same configuration
for (uint256 i = 0; i < convertibleTokenAnchors.length; i++) {
IConverterAnchor anchor = IConverterAnchor(convertibleTokenAnchors[i]);
IConverter converter = IConverter(payable(anchor.owner()));
if (isConverterReserveConfigEqual(converter, _type, _reserveTokens, _reserveWeights))
return anchor;
}
}
return IConverterAnchor(0);
}
/**
* @dev adds a converter anchor to the registry
*
* @param _anchor converter anchor
*/
function addAnchor(IConverterRegistryData _converterRegistryData, IConverterAnchor _anchor) internal {
_converterRegistryData.addSmartToken(_anchor);
emit ConverterAnchorAdded(_anchor);
emit SmartTokenAdded(_anchor);
}
/**
* @dev removes a converter anchor from the registry
*
* @param _anchor converter anchor
*/
function removeAnchor(IConverterRegistryData _converterRegistryData, IConverterAnchor _anchor) internal {
_converterRegistryData.removeSmartToken(_anchor);
emit ConverterAnchorRemoved(_anchor);
emit SmartTokenRemoved(_anchor);
}
/**
* @dev adds a liquidity pool to the registry
*
* @param _liquidityPoolAnchor liquidity pool converter anchor
*/
function addLiquidityPool(IConverterRegistryData _converterRegistryData, IConverterAnchor _liquidityPoolAnchor) internal {
_converterRegistryData.addLiquidityPool(_liquidityPoolAnchor);
emit LiquidityPoolAdded(_liquidityPoolAnchor);
}
/**
* @dev removes a liquidity pool from the registry
*
* @param _liquidityPoolAnchor liquidity pool converter anchor
*/
function removeLiquidityPool(IConverterRegistryData _converterRegistryData, IConverterAnchor _liquidityPoolAnchor) internal {
_converterRegistryData.removeLiquidityPool(_liquidityPoolAnchor);
emit LiquidityPoolRemoved(_liquidityPoolAnchor);
}
/**
* @dev adds a convertible token to the registry
*
* @param _convertibleToken convertible token
* @param _anchor associated converter anchor
*/
function addConvertibleToken(IConverterRegistryData _converterRegistryData, IERC20Token _convertibleToken, IConverterAnchor _anchor) internal {
_converterRegistryData.addConvertibleToken(_convertibleToken, _anchor);
emit ConvertibleTokenAdded(_convertibleToken, _anchor);
}
/**
* @dev removes a convertible token from the registry
*
* @param _convertibleToken convertible token
* @param _anchor associated converter anchor
*/
function removeConvertibleToken(IConverterRegistryData _converterRegistryData, IERC20Token _convertibleToken, IConverterAnchor _anchor) internal {
_converterRegistryData.removeConvertibleToken(_convertibleToken, _anchor);
emit ConvertibleTokenRemoved(_convertibleToken, _anchor);
}
function addConverterInternal(IConverter _converter) private {
IConverterRegistryData converterRegistryData = IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA));
IConverterAnchor anchor = IConverter(_converter).token();
uint256 reserveTokenCount = _converter.connectorTokenCount();
// add the converter anchor
addAnchor(converterRegistryData, anchor);
if (reserveTokenCount > 1)
addLiquidityPool(converterRegistryData, anchor);
else
addConvertibleToken(converterRegistryData, IDSToken(address(anchor)), anchor);
// add all reserve tokens
for (uint256 i = 0; i < reserveTokenCount; i++)
addConvertibleToken(converterRegistryData, _converter.connectorTokens(i), anchor);
}
function removeConverterInternal(IConverter _converter) private {
IConverterRegistryData converterRegistryData = IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA));
IConverterAnchor anchor = IConverter(_converter).token();
uint256 reserveTokenCount = _converter.connectorTokenCount();
// remove the converter anchor
removeAnchor(converterRegistryData, anchor);
if (reserveTokenCount > 1)
removeLiquidityPool(converterRegistryData, anchor);
else
removeConvertibleToken(converterRegistryData, IDSToken(address(anchor)), anchor);
// remove all reserve tokens
for (uint256 i = 0; i < reserveTokenCount; i++)
removeConvertibleToken(converterRegistryData, _converter.connectorTokens(i), anchor);
}
function getLeastFrequentTokenAnchors(IERC20Token[] memory _reserveTokens) private view returns (address[] memory) {
IConverterRegistryData converterRegistryData = IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA));
uint256 minAnchorCount = converterRegistryData.getConvertibleTokenSmartTokenCount(_reserveTokens[0]);
uint256 index = 0;
// find the reserve token which has the smallest number of converter anchors
for (uint256 i = 1; i < _reserveTokens.length; i++) {
uint256 convertibleTokenAnchorCount = converterRegistryData.getConvertibleTokenSmartTokenCount(_reserveTokens[i]);
if (minAnchorCount > convertibleTokenAnchorCount) {
minAnchorCount = convertibleTokenAnchorCount;
index = i;
}
}
return converterRegistryData.getConvertibleTokenSmartTokens(_reserveTokens[index]);
}
function isConverterReserveConfigEqual(IConverter _converter, uint16 _type, IERC20Token[] memory _reserveTokens, uint32[] memory _reserveWeights) private view returns (bool) {
uint256 reserveTokenCount = _converter.connectorTokenCount();
if (_type != getConverterType(_converter, reserveTokenCount))
return false;
if (_reserveTokens.length != reserveTokenCount)
return false;
for (uint256 i = 0; i < _reserveTokens.length; i++) {
if (_reserveWeights[i] != getReserveWeight(_converter, _reserveTokens[i]))
return false;
}
return true;
}
// utility to get the reserve weight (including from older converters that don't support the new getReserveWeight function)
function getReserveWeight(IConverter _converter, IERC20Token _reserveToken) private view returns (uint32) {
(, uint32 weight,,,) = _converter.connectors(_reserveToken);
return weight;
}
bytes4 private constant CONVERTER_TYPE_FUNC_SELECTOR = bytes4(keccak256("converterType()"));
// utility to get the converter type (including from older converters that don't support the new converterType function)
function getConverterType(IConverter _converter, uint256 _reserveTokenCount) private view returns (uint16) {
(bool success, bytes memory returnData) = address(_converter).staticcall(abi.encodeWithSelector(CONVERTER_TYPE_FUNC_SELECTOR));
if (success && returnData.length == 32)
return abi.decode(returnData, (uint16));
return _reserveTokenCount > 1 ? 1 : 0;
}
/**
* @dev deprecated, backward compatibility, use `getAnchorCount`
*/
function getSmartTokenCount() public view returns (uint256) {
return getAnchorCount();
}
/**
* @dev deprecated, backward compatibility, use `getAnchors`
*/
function getSmartTokens() public view returns (address[] memory) {
return getAnchors();
}
/**
* @dev deprecated, backward compatibility, use `getAnchor`
*/
function getSmartToken(uint256 _index) public view returns (IConverterAnchor) {
return getAnchor(_index);
}
/**
* @dev deprecated, backward compatibility, use `isAnchor`
*/
function isSmartToken(address _value) public view returns (bool) {
return isAnchor(_value);
}
/**
* @dev deprecated, backward compatibility, use `getConvertibleTokenAnchorCount`
*/
function getConvertibleTokenSmartTokenCount(IERC20Token _convertibleToken) public view returns (uint256) {
return getConvertibleTokenAnchorCount(_convertibleToken);
}
/**
* @dev deprecated, backward compatibility, use `getConvertibleTokenAnchors`
*/
function getConvertibleTokenSmartTokens(IERC20Token _convertibleToken) public view returns (address[] memory) {
return getConvertibleTokenAnchors(_convertibleToken);
}
/**
* @dev deprecated, backward compatibility, use `getConvertibleTokenAnchor`
*/
function getConvertibleTokenSmartToken(IERC20Token _convertibleToken, uint256 _index) public view returns (IConverterAnchor) {
return getConvertibleTokenAnchor(_convertibleToken, _index);
}
/**
* @dev deprecated, backward compatibility, use `isConvertibleTokenAnchor`
*/
function isConvertibleTokenSmartToken(IERC20Token _convertibleToken, address _value) public view returns (bool) {
return isConvertibleTokenAnchor(_convertibleToken, _value);
}
/**
* @dev deprecated, backward compatibility, use `getConvertersByAnchors`
*/
function getConvertersBySmartTokens(address[] memory _smartTokens) public view returns (IConverter[] memory) {
return getConvertersByAnchors(_smartTokens);
}
/**
* @dev deprecated, backward compatibility, use `getLiquidityPoolByConfig`
*/
function getLiquidityPoolByReserveConfig(IERC20Token[] memory _reserveTokens, uint32[] memory _reserveWeights) public view returns (IConverterAnchor) {
return getLiquidityPoolByConfig(_reserveTokens.length > 1 ? 1 : 0, _reserveTokens, _reserveWeights);
}
}
| returns the number of converter anchors associated with a given convertible token _convertibleToken convertible token return number of anchors associated with the given convertible token/ | function getConvertibleTokenAnchorCount(IERC20Token _convertibleToken) public view override returns (uint256) {
return IConverterRegistryData(addressOf(CONVERTER_REGISTRY_DATA)).getConvertibleTokenSmartTokenCount(_convertibleToken);
}
| 5,387,334 |
pragma solidity ^0.4.20;
/*
*
* ====================================*
* ____ ___ ____ _ _ *
* | _ \ / _ \ | _ \ | | | | *
* | |_) | | | | | | | | | | |_| | *
* | __/ | |_| | | |_| | | _ | *
* |_| \___/ |____/ |_| |_| *
* *
* ====================================*
* -> What?
* This source code is copy of a copy of a copy of Proof of Weak Hands (POWH3D)
* If POWL, POOH, POWM can do it, shit, why can't we?
* Call us dickheads, because we love PODH :)
*/
contract PODH {
/*=================================
= MODIFIERS =
=================================*/
// only people with tokens
modifier onlyBagholders() {
require(myTokens() > 0);
_;
}
// only people with profits
modifier onlyStronghands() {
require(myDividends(true) > 0);
_;
}
// administrators can:
// -> change the name of the contract
// -> change the name of the token
// -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later)
// they CANNOT:
// -> take funds
// -> disable withdrawals
// -> kill the contract
// -> change the price of tokens
modifier onlyAdministrator(){
address _customerAddress = msg.sender;
require(administrators[keccak256(_customerAddress)]);
_;
}
// ensures that the first tokens in the contract will be equally distributed
// meaning, no divine dump will be ever possible
// result: healthy longevity.
modifier antiEarlyWhale(uint256 _amountOfEthereum){
address _customerAddress = msg.sender;
// are we still in the vulnerable phase?
// if so, enact anti early whale protocol
if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){
require(
// is the customer in the ambassador list?
ambassadors_[_customerAddress] == true &&
// does the customer purchase exceed the max ambassador quota?
(ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_
);
// updated the accumulated quota
ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum);
// execute
_;
} else {
// in case the ether count drops low, the ambassador phase won't reinitiate
onlyAmbassadors = false;
_;
}
}
/*==============================
= EVENTS =
==============================*/
event onTokenPurchase(
address indexed customerAddress,
uint256 incomingEthereum,
uint256 tokensMinted,
address indexed referredBy
);
event onTokenSell(
address indexed customerAddress,
uint256 tokensBurned,
uint256 ethereumEarned
);
event onReinvestment(
address indexed customerAddress,
uint256 ethereumReinvested,
uint256 tokensMinted
);
event onWithdraw(
address indexed customerAddress,
uint256 ethereumWithdrawn
);
// ERC20
event Transfer(
address indexed from,
address indexed to,
uint256 tokens
);
/*=====================================
= CONFIGURABLES =
=====================================*/
string public name = "PODH";
string public symbol = "PODH";
uint8 constant public decimals = 18;
uint8 constant internal dividendFee_ = 10;
uint256 constant internal tokenPriceInitial_ = 0.0000001 ether;
uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether;
uint256 constant internal magnitude = 2**64;
// proof of stake (defaults at 100 tokens)
uint256 public stakingRequirement = 5e18;
// ambassador program
mapping(address => bool) internal ambassadors_;
uint256 constant internal ambassadorMaxPurchase_ = 2 ether;
uint256 constant internal ambassadorQuota_ = 3 ether;
/*================================
= DATASETS =
================================*/
// amount of shares for each address (scaled number)
mapping(address => uint256) internal tokenBalanceLedger_;
mapping(address => uint256) internal referralBalance_;
mapping(address => int256) internal payoutsTo_;
mapping(address => uint256) internal ambassadorAccumulatedQuota_;
uint256 internal tokenSupply_ = 0;
uint256 internal profitPerShare_;
// administrator list (see above on what they can do)
mapping(bytes32 => bool) public administrators;
// when this is set to true, only ambassadors can purchase tokens (this prevents a whale premine, it ensures a fairly distributed upper pyramid)
bool public onlyAmbassadors = true;
/*=======================================
= PUBLIC FUNCTIONS =
=======================================*/
/*
* -- APPLICATION ENTRY POINTS --
*/
function PODH()
public
{
// add administrators here
//fuck admin! Drive it like you stole it!
administrators[0xcd93345332dcaccf0b5b19db1714ee83265566d76060294d65956ac78c134882] = true; //SOOS
// add the ambassadors here.
ambassadors_[0xd8fa9c65623129fa4abaf44b7e21655d1ef835ce] = true; //OOF
ambassadors_[0x5D407efE6E17BE8ECC532Bc0cd4671fd25749331] = true; //SEES
}
/**
* Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any)
*/
function buy(address _referredBy)
public
payable
returns(uint256)
{
purchaseTokens(msg.value, _referredBy);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
payable
public
{
purchaseTokens(msg.value, 0x0);
}
/**
* Converts all of caller's dividends to tokens.
*/
function reinvest()
onlyStronghands()
public
{
// fetch dividends
uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code
// pay out the dividends virtually
address _customerAddress = msg.sender;
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// retrieve ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// dispatch a buy order with the virtualized "withdrawn dividends"
uint256 _tokens = purchaseTokens(_dividends, 0x0);
// fire event
onReinvestment(_customerAddress, _dividends, _tokens);
}
/**
* Alias of sell() and withdraw().
*/
function exit()
public
{
// get token count for caller & sell them all
address _customerAddress = msg.sender;
uint256 _tokens = tokenBalanceLedger_[_customerAddress];
if(_tokens > 0) sell(_tokens);
// lambo delivery service
withdraw();
}
/**
* Withdraws all of the callers earnings.
*/
function withdraw()
onlyStronghands()
public
{
// setup data
address _customerAddress = msg.sender;
uint256 _dividends = myDividends(false); // get ref. bonus later in the code
// update dividend tracker
payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude);
// add ref. bonus
_dividends += referralBalance_[_customerAddress];
referralBalance_[_customerAddress] = 0;
// lambo delivery service
_customerAddress.transfer(_dividends);
// fire event
onWithdraw(_customerAddress, _dividends);
}
/**
* Liquifies tokens to ethereum.
*/
function sell(uint256 _amountOfTokens)
onlyBagholders()
public
{
// setup data
address _customerAddress = msg.sender;
// russian hackers BTFO
require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
uint256 _tokens = _amountOfTokens;
uint256 _ethereum = tokensToEthereum_(_tokens);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
// burn the sold tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens);
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens);
// update dividends tracker
int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude));
payoutsTo_[_customerAddress] -= _updatedPayouts;
// dividing by zero is a bad idea
if (tokenSupply_ > 0) {
// update the amount of dividends per token
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
}
// fire event
onTokenSell(_customerAddress, _tokens, _taxedEthereum);
}
/**
* Transfer tokens from the caller to a new holder.
* Remember, there's a 10% fee here as well.
*/
function transfer(address _toAddress, uint256 _amountOfTokens)
onlyBagholders()
public
returns(bool)
{
// setup
address _customerAddress = msg.sender;
// make sure we have the requested tokens
// also disables transfers until ambassador phase is over
// ( we dont want whale premines )
require(!onlyAmbassadors && _amountOfTokens <= tokenBalanceLedger_[_customerAddress]);
// withdraw all outstanding dividends first
if(myDividends(true) > 0) withdraw();
// liquify 10% of the tokens that are transfered
// these are dispersed to shareholders
uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_);
uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee);
uint256 _dividends = tokensToEthereum_(_tokenFee);
// burn the fee tokens
tokenSupply_ = SafeMath.sub(tokenSupply_, _tokenFee);
// exchange tokens
tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _taxedTokens);
// update dividend trackers
payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens);
payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens);
// disperse dividends among holders
profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_);
// fire event
Transfer(_customerAddress, _toAddress, _taxedTokens);
// ERC20
return true;
}
/*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/
/**
* In case the amassador quota is not met, the administrator can manually disable the ambassador phase.
*/
function disableInitialStage()
onlyAdministrator()
public
{
onlyAmbassadors = false;
}
/**
* In case one of us dies, we need to replace ourselves.
*/
function setAdministrator(bytes32 _identifier, bool _status)
onlyAdministrator()
public
{
administrators[_identifier] = _status;
}
/**
* Precautionary measures in case we need to adjust the masternode rate.
*/
function setStakingRequirement(uint256 _amountOfTokens)
onlyAdministrator()
public
{
stakingRequirement = _amountOfTokens;
}
/**
* If we want to rebrand, we can.
*/
function setName(string _name)
onlyAdministrator()
public
{
name = _name;
}
/**
* If we want to rebrand, we can.
*/
function setSymbol(string _symbol)
onlyAdministrator()
public
{
symbol = _symbol;
}
/*---------- HELPERS AND CALCULATORS ----------*/
/**
* Method to view the current Ethereum stored in the contract
* Example: totalEthereumBalance()
*/
function totalEthereumBalance()
public
view
returns(uint)
{
return address (this).balance;
}
/**
* Retrieve the total token supply.
*/
function totalSupply()
public
view
returns(uint256)
{
return tokenSupply_;
}
/**
* Retrieve the tokens owned by the caller.
*/
function myTokens()
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return balanceOf(_customerAddress);
}
/**
* Retrieve the dividends owned by the caller.
* If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations.
* The reason for this, is that in the frontend, we will want to get the total divs (global + ref)
* But in the internal calculations, we want them separate.
*/
function myDividends(bool _includeReferralBonus)
public
view
returns(uint256)
{
address _customerAddress = msg.sender;
return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ;
}
/**
* Retrieve the token balance of any single address.
*/
function balanceOf(address _customerAddress)
view
public
returns(uint256)
{
return tokenBalanceLedger_[_customerAddress];
}
/**
* Retrieve the dividend balance of any single address.
*/
function dividendsOf(address _customerAddress)
view
public
returns(uint256)
{
return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude;
}
/**
* Return the buy price of 1 individual token.
*/
function sellPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ - tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Return the sell price of 1 individual token.
*/
function buyPrice()
public
view
returns(uint256)
{
// our calculation relies on the token supply, so we need supply. Doh.
if(tokenSupply_ == 0){
return tokenPriceInitial_ + tokenPriceIncremental_;
} else {
uint256 _ethereum = tokensToEthereum_(1e18);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ );
uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends);
return _taxedEthereum;
}
}
/**
* Function for the frontend to dynamically retrieve the price scaling of buy orders.
*/
function calculateTokensReceived(uint256 _ethereumToSpend)
public
view
returns(uint256)
{
uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
return _amountOfTokens;
}
/**
* Function for the frontend to dynamically retrieve the price scaling of sell orders.
*/
function calculateEthereumReceived(uint256 _tokensToSell)
public
view
returns(uint256)
{
require(_tokensToSell <= tokenSupply_);
uint256 _ethereum = tokensToEthereum_(_tokensToSell);
uint256 _dividends = SafeMath.div(_ethereum, dividendFee_);
uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends);
return _taxedEthereum;
}
/*==========================================
= INTERNAL FUNCTIONS =
==========================================*/
function purchaseTokens(uint256 _incomingEthereum, address _referredBy)
antiEarlyWhale(_incomingEthereum)
internal
returns(uint256)
{
// data setup
address _customerAddress = msg.sender;
uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_);
uint256 _referralBonus = SafeMath.div(_undividedDividends, 3);
uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus);
uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends);
uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum);
uint256 _fee = _dividends * magnitude;
// no point in continuing execution if OP is a poorfag russian hacker
// prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world
// (or hackers)
// and yes we know that the safemath function automatically rules out the "greater then" equasion.
require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_));
// is the user referred by a masternode?
if(
// is this a referred purchase?
_referredBy != 0x0000000000000000000000000000000000000000 &&
// no cheating!
_referredBy != _customerAddress &&
// does the referrer have at least X whole tokens?
// i.e is the referrer a godly chad masternode
tokenBalanceLedger_[_referredBy] >= stakingRequirement
){
// wealth redistribution
referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus);
} else {
// no ref purchase
// add the referral bonus back to the global dividends cake
_dividends = SafeMath.add(_dividends, _referralBonus);
_fee = _dividends * magnitude;
}
// we can't give people infinite ethereum
if(tokenSupply_ > 0){
// add tokens to the pool
tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens);
// take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder
profitPerShare_ += (_dividends * magnitude / (tokenSupply_));
// calculate the amount of tokens the customer receives over his purchase
_fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_))));
} else {
// add tokens to the pool
tokenSupply_ = _amountOfTokens;
}
// update circulating supply & the ledger address for the customer
tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens);
// Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them;
//really i know you think you do but you don't
int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee);
payoutsTo_[_customerAddress] += _updatedPayouts;
// fire event
onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy);
return _amountOfTokens;
}
/**
* Calculate Token price based on an amount of incoming ethereum
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function ethereumToTokens_(uint256 _ethereum)
internal
view
returns(uint256)
{
uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18;
uint256 _tokensReceived =
(
(
// underflow attempts BTFO
SafeMath.sub(
(sqrt
(
(_tokenPriceInitial**2)
+
(2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18))
+
(((tokenPriceIncremental_)**2)*(tokenSupply_**2))
+
(2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_)
)
), _tokenPriceInitial
)
)/(tokenPriceIncremental_)
)-(tokenSupply_)
;
return _tokensReceived;
}
/**
* Calculate token sell value.
* It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation;
* Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code.
*/
function tokensToEthereum_(uint256 _tokens)
internal
view
returns(uint256)
{
uint256 tokens_ = (_tokens + 1e18);
uint256 _tokenSupply = (tokenSupply_ + 1e18);
uint256 _etherReceived =
(
// underflow attempts BTFO
SafeMath.sub(
(
(
(
tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18))
)-tokenPriceIncremental_
)*(tokens_ - 1e18)
),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2
)
/1e18);
return _etherReceived;
}
//This is where all your gas goes, sorry
//Not sorry, you probably only paid 1 gwei
function sqrt(uint x) internal pure returns (uint y) {
uint z = (x + 1) / 2;
y = x;
while (z < y) {
y = z;
z = (x / z + z) / 2;
}
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
} | -- APPLICATION ENTRY POINTS --/ add administrators herefuck admin! Drive it like you stole it! add the ambassadors here. | function PODH()
public
{
}
| 15,158,604 |
pragma solidity ^0.5.12;
library SafeMath {
function MUL98(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
if (a == 0)
return 0;
uint256 c = a * b;
require(c / a == b);
return c;
}
function DIV107(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b > 0);
uint256 c = a / b;
return c;
}
function SUB705(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b <= a);
uint256 c = a - b;
return c;
}
function ADD235(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a);
return c;
}
function MOD157(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0);
return a % b;
}
}
contract ERC20 {
using SafeMath for uint256;
mapping (address => uint256) internal _balances;
mapping (address => mapping (address => uint256)) internal _allowed;
event TRANSFER731(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL787(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
uint256 internal _totalSupply;
function TOTALSUPPLY882() public view returns (uint256) { //inject NONSTANDARD NAMING
return _totalSupply;
}
function BALANCEOF767(address owner) public view returns (uint256) { //inject NONSTANDARD NAMING
return _balances[owner];
}
function ALLOWANCE10(address owner, address spender) public view returns (uint256) { //inject NONSTANDARD NAMING
return _allowed[owner][spender];
}
function TRANSFER204(address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER522(msg.sender, to, value);
return true;
}
function APPROVE277(address spender, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_allowed[msg.sender][spender] = value;
emit APPROVAL787(msg.sender, spender, value);
return true;
}
function TRANSFERFROM832(address from, address to, uint256 value) public returns (bool) { //inject NONSTANDARD NAMING
_TRANSFER522(from, to, value);
_allowed[msg.sender][to] = _allowed[msg.sender][to].SUB705(value);
return true;
}
function _TRANSFER522(address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
require(to != address(0));
_balances[from] = _balances[from].SUB705(value);
_balances[to] = _balances[to].ADD235(value);
emit TRANSFER731(from, to, value);
}
}
contract ERC20Mintable is ERC20 {
string public name;
string public symbol;
uint8 public decimals;
function _MINT321(address to, uint256 amount) internal { //inject NONSTANDARD NAMING
_balances[to] = _balances[to].ADD235(amount);
_totalSupply = _totalSupply.ADD235(amount);
emit TRANSFER731(address(0), to, amount);
}
function _BURN441(address from, uint256 amount) internal { //inject NONSTANDARD NAMING
_balances[from] = _balances[from].SUB705(amount);
_totalSupply = _totalSupply.SUB705(amount);
emit TRANSFER731(from, address(0), amount);
}
}
// ----------- Aave ----------------
contract ILendingPoolAddressesProvider {
function GETLENDINGPOOL38() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLIMPL881(address _pool) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLCORE21() public view returns (address payable); //inject NONSTANDARD NAMING
function SETLENDINGPOOLCOREIMPL156(address _lendingPoolCore) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLCONFIGURATOR254() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLCONFIGURATORIMPL555(address _configurator) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLDATAPROVIDER61() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLDATAPROVIDERIMPL193(address _provider) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLPARAMETERSPROVIDER362() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLPARAMETERSPROVIDERIMPL978(address _parametersProvider) public; //inject NONSTANDARD NAMING
function GETTOKENDISTRIBUTOR827() public view returns (address); //inject NONSTANDARD NAMING
function SETTOKENDISTRIBUTOR348(address _tokenDistributor) public; //inject NONSTANDARD NAMING
function GETFEEPROVIDER168() public view returns (address); //inject NONSTANDARD NAMING
function SETFEEPROVIDERIMPL718(address _feeProvider) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLLIQUIDATIONMANAGER82() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLLIQUIDATIONMANAGER708(address _manager) public; //inject NONSTANDARD NAMING
function GETLENDINGPOOLMANAGER762() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGPOOLMANAGER882(address _lendingPoolManager) public; //inject NONSTANDARD NAMING
function GETPRICEORACLE485() public view returns (address); //inject NONSTANDARD NAMING
function SETPRICEORACLE428(address _priceOracle) public; //inject NONSTANDARD NAMING
function GETLENDINGRATEORACLE592() public view returns (address); //inject NONSTANDARD NAMING
function SETLENDINGRATEORACLE655(address _lendingRateOracle) public; //inject NONSTANDARD NAMING
}
interface ILendingPool {
function ADDRESSESPROVIDER344() external view returns(address); //inject NONSTANDARD NAMING
function DEPOSIT818(address _reserve, uint256 _amount, uint16 _referralCode) external payable; //inject NONSTANDARD NAMING
function REDEEMUNDERLYING805(address _reserve, address _user, uint256 _amount) external; //inject NONSTANDARD NAMING
function BORROW264(address _reserve, uint256 _amount, uint256 _interestRateMode, uint16 _referralCode) external; //inject NONSTANDARD NAMING
function REPAY662(address _reserve, uint256 _amount, address _onBehalfOf) external payable; //inject NONSTANDARD NAMING
function SWAPBORROWRATEMODE766(address _reserve) external; //inject NONSTANDARD NAMING
function REBALANCEFIXEDBORROWRATE627(address _reserve, address _user) external; //inject NONSTANDARD NAMING
function SETUSERUSERESERVEASCOLLATERAL986(address _reserve, bool _useAsCollateral) external; //inject NONSTANDARD NAMING
function LIQUIDATIONCALL807(address _collateral, address _reserve, address _user, uint256 _purchaseAmount, bool _receiveAToken) external payable; //inject NONSTANDARD NAMING
function FLASHLOAN206(address _receiver, address _reserve, uint256 _amount, bytes calldata _params) external; //inject NONSTANDARD NAMING
function GETRESERVECONFIGURATIONDATA59(address _reserve) external view returns(uint256 ltv, uint256 liquidationThreshold, uint256 liquidationDiscount, address interestRateStrategyAddress, bool usageAsCollateralEnabled, bool borrowingEnabled, bool fixedBorrowRateEnabled, bool isActive); //inject NONSTANDARD NAMING
function GETRESERVEDATA692(address _reserve) external view returns(uint256 totalLiquidity, uint256 availableLiquidity, uint256 totalBorrowsFixed, uint256 totalBorrowsVariable, uint256 liquidityRate, uint256 variableBorrowRate, uint256 fixedBorrowRate, uint256 averageFixedBorrowRate, uint256 utilizationRate, uint256 liquidityIndex, uint256 variableBorrowIndex, address aTokenAddress, uint40 lastUpdateTimestamp); //inject NONSTANDARD NAMING
function GETUSERACCOUNTDATA811(address _user) external view returns(uint256 totalLiquidityETH, uint256 totalCollateralETH, uint256 totalBorrowsETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor); //inject NONSTANDARD NAMING
function GETUSERRESERVEDATA732(address _reserve, address _user) external view returns(uint256 currentATokenBalance, uint256 currentBorrowBalance, uint256 principalBorrowBalance, uint256 borrowRateMode, uint256 borrowRate, uint256 liquidityRate, uint256 originationFee, uint256 variableBorrowIndex, uint256 lastUpdateTimestamp, bool usageAsCollateralEnabled); //inject NONSTANDARD NAMING
function GETRESERVES689() external view; //inject NONSTANDARD NAMING
}
interface ILendingPoolCore {
function GETRESERVEATOKENADDRESS314(address _reserve) external view returns (address); //inject NONSTANDARD NAMING
function GETRESERVECURRENTVARIABLEBORROWRATE762(address _token) external view returns (uint256); //inject NONSTANDARD NAMING
function GETRESERVECURRENTLIQUIDITYRATE636(address _token) external view returns (uint256); //inject NONSTANDARD NAMING
}
interface IAavePriceOracleGetter {
function GETASSETPRICE734(address _asset) external view returns (uint256); //inject NONSTANDARD NAMING
function GETASSETSPRICES996(address[] calldata _assets) external view returns(uint256[] memory); //inject NONSTANDARD NAMING
function GETSOURCEOFASSET324(address _asset) external view returns(address); //inject NONSTANDARD NAMING
function GETFALLBACKORACLE535() external view returns(address); //inject NONSTANDARD NAMING
}
interface IAToken {
function REDIRECTINTERESTSTREAM242(address _to) external; //inject NONSTANDARD NAMING
function REDIRECTINTERESTSTREAMOF292(address _from, address _to) external; //inject NONSTANDARD NAMING
function ALLOWINTERESTREDIRECTIONTO292(address _to) external; //inject NONSTANDARD NAMING
function REDEEM632(uint256 _amount) external; //inject NONSTANDARD NAMING
function PRINCIPALBALANCEOF100(address _user) external view returns(uint256); //inject NONSTANDARD NAMING
function ISTRANSFERALLOWED396(address _user, uint256 _amount) external view returns (bool); //inject NONSTANDARD NAMING
function GETUSERINDEX768(address _user) external view returns(uint256); //inject NONSTANDARD NAMING
function GETINTERESTREDIRECTIONADDRESS228(address _user) external view returns(address); //inject NONSTANDARD NAMING
function GETREDIRECTEDBALANCE288(address _user) external view returns(uint256); //inject NONSTANDARD NAMING
function TOTALSUPPLY882() external view returns (uint256 supply); //inject NONSTANDARD NAMING
function BALANCEOF767(address _owner) external view returns (uint256 balance); //inject NONSTANDARD NAMING
function TRANSFER204(address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function TRANSFERFROM832(address _from, address _to, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function APPROVE277(address _spender, uint256 _value) external returns (bool success); //inject NONSTANDARD NAMING
function ALLOWANCE10(address _owner, address _spender) external view returns (uint256 remaining); //inject NONSTANDARD NAMING
function NAME858() external view returns (string memory); //inject NONSTANDARD NAMING
function SYMBOL894() external view returns (string memory); //inject NONSTANDARD NAMING
function DECIMALS454() external view returns (uint8); //inject NONSTANDARD NAMING
}
interface PriceOracle {
function GETUNDERLYINGPRICE929(address) external view returns (uint256); //inject NONSTANDARD NAMING
}
// ---------- Compound ----------
interface CErc20 {
function BORROW264(uint256) external returns (uint256); //inject NONSTANDARD NAMING
function BORROWRATEPERBLOCK388() external view returns (uint256); //inject NONSTANDARD NAMING
function BORROWBALANCECURRENT444(address) external returns (uint256); //inject NONSTANDARD NAMING
function REPAYBORROW515(uint256) external returns (uint256); //inject NONSTANDARD NAMING
}
interface CEth {
function MINT397() external payable; //inject NONSTANDARD NAMING
function REDEEMUNDERLYING805(uint redeemAmount) external returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOFUNDERLYING788(address owner) external returns (uint256); //inject NONSTANDARD NAMING
function SUPPLYRATEPERBLOCK15() external view returns (uint256); //inject NONSTANDARD NAMING
}
interface Comptroller {
function MARKETS249(address) external returns (bool, uint256); //inject NONSTANDARD NAMING
function ENTERMARKETS82(address[] calldata) //inject NONSTANDARD NAMING
external
returns (uint256[] memory);
function GETACCOUNTLIQUIDITY384(address) //inject NONSTANDARD NAMING
external
view
returns (uint256, uint256, uint256);
function ORACLE168() external view returns(address); //inject NONSTANDARD NAMING
}
// ---------- kyber ----------
interface Exchange {
function TRADE301( //inject NONSTANDARD NAMING
address src,
uint srcAmount,
address dest,
address destAddress,
uint maxDestAmount,
uint minConversionRate,
address walletId )external payable returns(uint);
}
// -----tCDP-----
contract tCDPConstants {
uint256 constant dust264 = 1e6; // minimum mint amount //inject NONSTANDARD NAMING
ERC20 constant dai445 = ERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); // DAI(debt) token address //inject NONSTANDARD NAMING
//Compound
Comptroller constant comptroller75 = Comptroller(0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B); //inject NONSTANDARD NAMING
CEth constant ceth501 = CEth(0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5); //inject NONSTANDARD NAMING
CErc20 constant cdai61 = CErc20(0x5d3a536E4D6DbD6114cc1Ead35777bAB948E3643); //inject NONSTANDARD NAMING
//AAVE
ILendingPoolAddressesProvider constant addressesprovider654 = ILendingPoolAddressesProvider(0x24a42fD28C976A61Df5D00D0599C34c4f90748c8); //inject NONSTANDARD NAMING
uint16 constant referral215 = 47; // TODO: apply new referral code //inject NONSTANDARD NAMING
//Kyber
Exchange constant kybernetwork927 = Exchange(0x818E6FECD516Ecc3849DAf6845e3EC868087B755); //inject NONSTANDARD NAMING
address constant etheraddr36 = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; //inject NONSTANDARD NAMING
address constant ref472 = 0xD0533664013a82c31584B7FFDB215139f38Ad77A; //inject NONSTANDARD NAMING
//rebalance target/boundary/size
uint256 constant targetratio559 = 0.4e18; //40% //inject NONSTANDARD NAMING
uint256 constant upperbound23 = 444444444444444444; // 1/225% //inject NONSTANDARD NAMING
uint256 constant lowerbound414 = 363636363636363636; // 1/275% //inject NONSTANDARD NAMING
uint256 constant bite558 = 0.025 * 1e18; //2.5% //inject NONSTANDARD NAMING
}
contract tCDP is ERC20Mintable, tCDPConstants{
using SafeMath for *;
bool public isCompound;
event MIGRATION431(uint8); // 0x01 = to Compound, 0x02 = to Aave //inject NONSTANDARD NAMING
constructor() public {
symbol = "tETH-DAI";
name = "tokenized CDP ETH-DAI v1";
decimals = 18;
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
dai445.APPROVE277(lendingPoolCoreAddress, uint256(-1));
dai445.APPROVE277(address(cdai61), uint256(-1));
address[] memory cTokens = new address[](1);
cTokens[0] = address(ceth501);
uint256[] memory errors = comptroller75.ENTERMARKETS82(cTokens);
require(errors[0] == 0, "Comptroller.enterMarkets failed.");
dai445.APPROVE277(address(kybernetwork927), uint256(-1));
isCompound = FINDBESTRATE616();
}
function INITIATE270(uint256 amount) external payable { //inject NONSTANDARD NAMING
require(_totalSupply < dust264, "initiated");
require(msg.value > dust264, "value too small");
if(isCompound) {
ceth501.MINT397.value(msg.value)();
_MINT321(msg.sender, msg.value);
require(cdai61.BORROW264(amount) == 0, "borrow failed");
dai445.TRANSFER204(msg.sender, amount);
}
else {
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.DEPOSIT818.value(msg.value)(etheraddr36, msg.value, referral215);
_MINT321(msg.sender, msg.value);
lendingPool.BORROW264(address(dai445), amount, 2, referral215);
dai445.TRANSFER204(msg.sender, amount);
}
}
function COLLATERAL797() public returns(uint256) { //inject NONSTANDARD NAMING
if(isCompound) {
return ceth501.BALANCEOFUNDERLYING788(address(this));
}
else {
address lendingPoolCore = addressesprovider654.GETLENDINGPOOLCORE21();
address aETH = ILendingPoolCore(lendingPoolCore).GETRESERVEATOKENADDRESS314(etheraddr36);
return IAToken(aETH).BALANCEOF767(address(this));
}
}
function DEBT567() public returns(uint256) { //inject NONSTANDARD NAMING
if(isCompound) {
return cdai61.BORROWBALANCECURRENT444(address(this));
}
else {
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
(, uint256 borrowBalance,,,,,,,,) = lendingPool.GETUSERRESERVEDATA732(address(dai445), address(this));
return borrowBalance;
}
}
function MINT397() external payable returns(uint256) { //inject NONSTANDARD NAMING
require(_totalSupply >= dust264, "not initiated");
uint256 amount = msg.value;
uint256 tokenToMint = _totalSupply.MUL98(amount).DIV107(COLLATERAL797());
uint256 tokenToBorrow = DEBT567().MUL98(amount).DIV107(COLLATERAL797());
_MINT321(msg.sender, tokenToMint);
if(isCompound) {
ceth501.MINT397.value(amount)();
require(cdai61.BORROW264(tokenToBorrow) == 0, "borrow failed");
dai445.TRANSFER204(msg.sender, tokenToBorrow);
}
else{
// deposit
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.DEPOSIT818.value(amount)(etheraddr36, amount, referral215);
// borrow
lendingPool.BORROW264(address(dai445), tokenToBorrow, 2, referral215);
// transfer
dai445.TRANSFER204(msg.sender, tokenToBorrow);
}
return tokenToMint;
}
function BURN250(uint256 amount) external { //inject NONSTANDARD NAMING
uint256 tokenToRepay = amount.MUL98(DEBT567()).DIV107(_totalSupply);
uint256 tokenToDraw = amount.MUL98(COLLATERAL797()).DIV107(_totalSupply);
_BURN441(msg.sender, amount);
dai445.TRANSFERFROM832(msg.sender, address(this), tokenToRepay);
if(isCompound) {
require(cdai61.REPAYBORROW515(tokenToRepay) == 0, "repay failed");
require(ceth501.REDEEMUNDERLYING805(tokenToDraw) == 0, "redeem failed");
}
else {
// repay
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
// Dai.approve(lendingPoolCoreAddress, tokenToRepay);
lendingPool.REPAY662(address(dai445), tokenToRepay, address(this));
// redeem
IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36));
aETH.REDEEM632(tokenToDraw);
}
(bool success, ) = msg.sender.call.value(tokenToDraw)("");
require(success, "Failed to transfer ether to msg.sender");
}
function() external payable{}
//true if (cEth APR - cDai APR) >= (aEth APR - aDai APR), otherwise, false
function FINDBESTRATE616() public view returns (bool) { //inject NONSTANDARD NAMING
return AAVEDAIAPR797().MUL98(targetratio559).DIV107(1e18).ADD235(COMPOUNDETHAPR912()) > COMPOUNDDAIAPR961().MUL98(targetratio559).DIV107(1e18).ADD235(AAVEETHAPR160());
}
function COMPOUNDDAIAPR961() public view returns (uint256) { //inject NONSTANDARD NAMING
return cdai61.BORROWRATEPERBLOCK388().MUL98(2102400);
}
function COMPOUNDETHAPR912() public view returns (uint256) { //inject NONSTANDARD NAMING
return ceth501.SUPPLYRATEPERBLOCK15().MUL98(2102400);
}
function AAVEDAIAPR797() public view returns (uint256) { //inject NONSTANDARD NAMING
ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21());
return core.GETRESERVECURRENTVARIABLEBORROWRATE762(address(dai445)).DIV107(1e9);
}
function AAVEETHAPR160() public view returns (uint256) { //inject NONSTANDARD NAMING
ILendingPoolCore core = ILendingPoolCore(addressesprovider654.GETLENDINGPOOLCORE21());
return core.GETRESERVECURRENTLIQUIDITYRATE636(etheraddr36).DIV107(1e9);
}
function GETUNDERLYINGPRICE929() public view returns(uint256) { //inject NONSTANDARD NAMING
uint256 price;
if(isCompound) {
address oracle = comptroller75.ORACLE168();
PriceOracle priceOracle = PriceOracle(oracle);
price = priceOracle.GETUNDERLYINGPRICE929(address(cdai61));
}
else {
address oracleAddress = addressesprovider654.GETPRICEORACLE485();
IAavePriceOracleGetter priceOracle = IAavePriceOracleGetter(oracleAddress);
price = priceOracle.GETASSETPRICE734(address(dai445));
}
return price;
}
function DEBTRATIO670() public returns (uint256) { //inject NONSTANDARD NAMING
uint256 price = GETUNDERLYINGPRICE929();
uint256 ratio = DEBT567().MUL98(price).DIV107(COLLATERAL797());
return ratio;
}
function DELEVERAGE904() external { //inject NONSTANDARD NAMING
require(_totalSupply >= dust264, "not initiated");
require(DEBTRATIO670() > upperbound23, "debt ratio is good");
uint256 amount = COLLATERAL797().MUL98(bite558).DIV107(1e18);
if(isCompound) {
require(ceth501.REDEEMUNDERLYING805(amount) == 0, "redeem failed");
uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472);
require(cdai61.REPAYBORROW515(income) == 0, "repay failed");
}
else {
// redeem
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36));
aETH.REDEEM632(amount);
uint256 income = kybernetwork927.TRADE301.value(amount)(etheraddr36, amount, address(dai445), address(this), 1e28, 1, ref472);
// repay
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
// Dai.approve(lendingPoolCoreAddress, income);
lendingPool.REPAY662(address(dai445), income, address(this));
}
}
function LEVERAGE920() external { //inject NONSTANDARD NAMING
require(_totalSupply >= dust264, "not initiated");
require(DEBTRATIO670() < lowerbound414, "debt ratio is good");
uint256 amount = DEBT567().MUL98(bite558).DIV107(1e18);
if(isCompound) {
require(cdai61.BORROW264(amount) == 0, "borrow failed");
uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472);
ceth501.MINT397.value(income)();
}
else {
// borrow
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.BORROW264(address(dai445), amount, 2, referral215);
uint256 income = kybernetwork927.TRADE301(address(dai445), amount, etheraddr36, address(this), 1e28, 1, ref472);
// deposit
lendingPool.DEPOSIT818.value(income)(etheraddr36, income, referral215);
}
}
function MIGRATE814() external { //inject NONSTANDARD NAMING
if(FINDBESTRATE616() != isCompound) {
uint256 _debt = DEBT567();
uint256 _collateral = COLLATERAL797();
dai445.TRANSFERFROM832(msg.sender, address(this), _debt);
uint256 newBorrow = _debt.ADD235(2);
if(isCompound) {
require(cdai61.REPAYBORROW515(_debt) == 0, "borrow failed");
require(ceth501.REDEEMUNDERLYING805(_collateral) == 0, "redeem failed");
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
lendingPool.DEPOSIT818.value(_collateral)(etheraddr36, _collateral, referral215);
lendingPool.BORROW264(address(dai445), newBorrow, 2, referral215);
isCompound = false;
emit MIGRATION431(0x02);
}
else {
ILendingPool lendingPool = ILendingPool(addressesprovider654.GETLENDINGPOOL38());
address lendingPoolCoreAddress = addressesprovider654.GETLENDINGPOOLCORE21();
lendingPool.REPAY662(address(dai445), _debt, address(this));
IAToken aETH = IAToken(ILendingPoolCore(lendingPoolCoreAddress).GETRESERVEATOKENADDRESS314(etheraddr36));
aETH.REDEEM632(_collateral);
ceth501.MINT397.value(_collateral)();
require(cdai61.BORROW264(newBorrow) == 0, "borrow failed");
isCompound = true;
emit MIGRATION431(0x01);
}
dai445.TRANSFER204(msg.sender, newBorrow);
}
}
} | inject NONSTANDARD NAMING | function REDIRECTINTERESTSTREAM242(address _to) external; | 5,544,593 |
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity =0.7.6;
pragma experimental ABIEncoderV2;
// Forked from Compound
// See https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/GovernorAlpha.sol
contract GovernorAlpha {
/// @notice The name of this contract
// solhint-disable-next-line const-name-snakecase
string public constant name = "Ring Governor Alpha";
/// @notice The number of votes in support of a proposal required in order for a quorum to be reached and for a vote to succeed
function quorumVotes() public pure returns (uint) { return 25000000e18; } // 25,000,000 = 2.5% of Ring
/// @notice The number of votes required in order for a voter to become a proposer
function proposalThreshold() public pure returns (uint) { return 2500000e18; } // 2,500,000 = .25% of Ring
/// @notice The maximum number of actions that can be included in a proposal
function proposalMaxOperations() public pure returns (uint) { return 10; } // 10 actions
/// @notice The delay before voting on a proposal may take place, once proposed
function votingDelay() public pure returns (uint) { return 3333; } // ~0.5 days in blocks (assuming 13s blocks)
/// @notice The duration of voting on a proposal, in blocks
function votingPeriod() public pure returns (uint) { return 10000; } // ~1.5 days in blocks (assuming 13s blocks)
/// @notice The address of the Ring Protocol Timelock
TimelockInterface public timelock;
/// @notice The address of the Ring governance token
RingInterface public ring;
/// @notice The address of the Governor Guardian
address public guardian;
/// @notice The total number of proposals
uint public proposalCount;
struct Proposal {
uint id;
address proposer;
uint eta;
address[] targets;
uint[] values;
string[] signatures;
bytes[] calldatas;
uint startBlock;
uint endBlock;
uint forVotes;
uint againstVotes;
bool canceled;
bool executed;
mapping (address => Receipt) receipts;
}
/// @notice Ballot receipt record for a voter
struct Receipt {
bool hasVoted;
bool support;
uint96 votes;
}
/// @notice Possible states that a proposal may be in
enum ProposalState {
Pending,
Active,
Canceled,
Defeated,
Succeeded,
Queued,
Expired,
Executed
}
/// @notice The official record of all proposals ever proposed
mapping (uint => Proposal) public proposals;
/// @notice The latest proposal for each proposer
mapping (address => uint) public latestProposalIds;
/// @notice The EIP-712 typehash for the contract's domain
bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)");
/// @notice The EIP-712 typehash for the ballot struct used by the contract
bytes32 public constant BALLOT_TYPEHASH = keccak256("Ballot(uint256 proposalId,bool support)");
/// @notice An event emitted when a new proposal is created
event ProposalCreated(uint id, address proposer, address[] targets, uint[] values, string[] signatures, bytes[] calldatas, uint startBlock, uint endBlock, string description);
/// @notice An event emitted when a vote has been cast on a proposal
event VoteCast(address voter, uint proposalId, bool support, uint votes);
/// @notice An event emitted when a proposal has been canceled
event ProposalCanceled(uint id);
/// @notice An event emitted when a proposal has been queued in the Timelock
event ProposalQueued(uint id, uint eta);
/// @notice An event emitted when a proposal has been executed in the Timelock
event ProposalExecuted(uint id);
constructor(address timelock_, address ring_, address guardian_) {
timelock = TimelockInterface(timelock_);
ring = RingInterface(ring_);
guardian = guardian_;
}
function propose(address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas, string memory description) public returns (uint) {
require(ring.getPriorVotes(msg.sender, sub256(block.number, 1)) > proposalThreshold(), "GovernorAlpha: proposer votes below proposal threshold");
require(targets.length == values.length && targets.length == signatures.length && targets.length == calldatas.length, "GovernorAlpha: proposal function information arity mismatch");
require(targets.length != 0, "GovernorAlpha: must provide actions");
require(targets.length <= proposalMaxOperations(), "GovernorAlpha: too many actions");
uint latestProposalId = latestProposalIds[msg.sender];
if (latestProposalId != 0) {
ProposalState proposersLatestProposalState = state(latestProposalId);
require(proposersLatestProposalState != ProposalState.Active, "GovernorAlpha: one live proposal per proposer, found an already active proposal");
require(proposersLatestProposalState != ProposalState.Pending, "GovernorAlpha: one live proposal per proposer, found an already pending proposal");
}
uint startBlock = add256(block.number, votingDelay());
uint endBlock = add256(startBlock, votingPeriod());
proposalCount++;
Proposal storage newProposal = proposals[proposalCount];
newProposal.id = proposalCount;
newProposal.proposer = msg.sender;
newProposal.eta = 0;
newProposal.targets = targets;
newProposal.values = values;
newProposal.signatures = signatures;
newProposal.calldatas = calldatas;
newProposal.startBlock = startBlock;
newProposal.endBlock = endBlock;
newProposal.forVotes = 0;
newProposal.againstVotes = 0;
newProposal.canceled = false;
newProposal.executed = false;
latestProposalIds[newProposal.proposer] = newProposal.id;
emit ProposalCreated(newProposal.id, msg.sender, targets, values, signatures, calldatas, startBlock, endBlock, description);
return newProposal.id;
}
function queue(uint proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
// solhint-disable-next-line not-rely-on-time
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
function _queueOrRevert(address target, uint value, string memory signature, bytes memory data, uint eta) internal {
require(!timelock.queuedTransactions(keccak256(abi.encode(target, value, signature, data, eta))), "GovernorAlpha: proposal action already queued at eta");
timelock.queueTransaction(target, value, signature, data, eta);
}
function execute(uint proposalId) public payable {
require(state(proposalId) == ProposalState.Queued, "GovernorAlpha: proposal can only be executed if it is queued");
Proposal storage proposal = proposals[proposalId];
proposal.executed = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.executeTransaction{value : proposal.values[i]}(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalExecuted(proposalId);
}
function cancel(uint proposalId) public {
ProposalState _state = state(proposalId);
require(_state == ProposalState.Active || _state == ProposalState.Pending, "GovernorAlpha: can only cancel Active or Pending Proposal");
Proposal storage proposal = proposals[proposalId];
require(msg.sender == guardian || ring.getPriorVotes(proposal.proposer, sub256(block.number, 1)) < proposalThreshold(), "GovernorAlpha: proposer above threshold");
proposal.canceled = true;
for (uint i = 0; i < proposal.targets.length; i++) {
timelock.cancelTransaction(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], proposal.eta);
}
emit ProposalCanceled(proposalId);
}
function getActions(uint proposalId) public view returns (address[] memory targets, uint[] memory values, string[] memory signatures, bytes[] memory calldatas) {
Proposal storage p = proposals[proposalId];
return (p.targets, p.values, p.signatures, p.calldatas);
}
function getReceipt(uint proposalId, address voter) public view returns (Receipt memory) {
return proposals[proposalId].receipts[voter];
}
function state(uint proposalId) public view returns (ProposalState) {
require(proposalCount >= proposalId && proposalId > 0, "GovernorAlpha: invalid proposal id");
Proposal storage proposal = proposals[proposalId];
if (proposal.canceled) {
return ProposalState.Canceled;
} else if (block.number <= proposal.startBlock) {
return ProposalState.Pending;
} else if (block.number <= proposal.endBlock) {
return ProposalState.Active;
} else if (proposal.forVotes <= proposal.againstVotes || proposal.forVotes < quorumVotes()) {
return ProposalState.Defeated;
} else if (proposal.eta == 0) {
return ProposalState.Succeeded;
} else if (proposal.executed) {
return ProposalState.Executed;
// solhint-disable-next-line not-rely-on-time
} else if (block.timestamp >= add256(proposal.eta, timelock.GRACE_PERIOD())) {
return ProposalState.Expired;
} else {
return ProposalState.Queued;
}
}
function castVote(uint proposalId, bool support) public {
return _castVote(msg.sender, proposalId, support);
}
function castVoteBySig(uint proposalId, bool support, uint8 v, bytes32 r, bytes32 s) public {
bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this)));
bytes32 structHash = keccak256(abi.encode(BALLOT_TYPEHASH, proposalId, support));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "GovernorAlpha: invalid signature");
return _castVote(signatory, proposalId, support);
}
function _castVote(address voter, uint proposalId, bool support) internal {
require(state(proposalId) == ProposalState.Active, "GovernorAlpha: voting is closed");
Proposal storage proposal = proposals[proposalId];
Receipt storage receipt = proposal.receipts[voter];
require(receipt.hasVoted == false, "GovernorAlpha: voter already voted");
uint96 votes = ring.getPriorVotes(voter, proposal.startBlock);
if (support) {
proposal.forVotes = add256(proposal.forVotes, votes);
} else {
proposal.againstVotes = add256(proposal.againstVotes, votes);
}
receipt.hasVoted = true;
receipt.support = support;
receipt.votes = votes;
emit VoteCast(voter, proposalId, support, votes);
}
function __acceptAdmin() public {
require(msg.sender == guardian, "GovernorAlpha: sender must be gov guardian");
timelock.acceptAdmin();
}
function __abdicate() public {
require(msg.sender == guardian, "GovernorAlpha: sender must be gov guardian");
guardian = address(0);
}
function __transferGuardian(address newGuardian) public {
require(msg.sender == guardian, "GovernorAlpha: sender must be gov guardian");
guardian = newGuardian;
}
function __queueSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha: sender must be gov guardian");
timelock.queueTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function __executeSetTimelockPendingAdmin(address newPendingAdmin, uint eta) public {
require(msg.sender == guardian, "GovernorAlpha: sender must be gov guardian");
timelock.executeTransaction(address(timelock), 0, "setPendingAdmin(address)", abi.encode(newPendingAdmin), eta);
}
function add256(uint256 a, uint256 b) internal pure returns (uint) {
uint c = a + b;
require(c >= a, "addition overflow");
return c;
}
function sub256(uint256 a, uint256 b) internal pure returns (uint) {
require(b <= a, "subtraction underflow");
return a - b;
}
function getChainId() internal pure returns (uint) {
uint chainId;
// solhint-disable-next-line no-inline-assembly
assembly { chainId := chainid() }
return chainId;
}
}
interface TimelockInterface {
function delay() external view returns (uint);
// solhint-disable-next-line func-name-mixedcase
function GRACE_PERIOD() external view returns (uint);
function acceptAdmin() external;
function queuedTransactions(bytes32 hash) external view returns (bool);
function queueTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external returns (bytes32);
function cancelTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external;
function executeTransaction(address target, uint value, string calldata signature, bytes calldata data, uint eta) external payable returns (bytes memory);
}
interface RingInterface {
function getPriorVotes(address account, uint blockNumber) external view returns (uint96);
}
| solhint-disable-next-line not-rely-on-time | function queue(uint proposalId) public {
require(state(proposalId) == ProposalState.Succeeded, "GovernorAlpha: proposal can only be queued if it is succeeded");
Proposal storage proposal = proposals[proposalId];
uint eta = add256(block.timestamp, timelock.delay());
for (uint i = 0; i < proposal.targets.length; i++) {
_queueOrRevert(proposal.targets[i], proposal.values[i], proposal.signatures[i], proposal.calldatas[i], eta);
}
proposal.eta = eta;
emit ProposalQueued(proposalId, eta);
}
| 1,503,748 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
import "../../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using Address for address;
function safeTransfer(
IERC20 token,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(
IERC20 token,
address from,
address to,
uint256 value
) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(
IERC20 token,
address spender,
uint256 value
) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
require(
(value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
uint256 newAllowance = token.allowance(address(this), spender) + value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(
IERC20 token,
address spender,
uint256 value
) internal {
unchecked {
uint256 oldAllowance = token.allowance(address(this), spender);
require(oldAllowance >= value, "SafeERC20: decreased allowance below zero");
uint256 newAllowance = oldAllowance - value;
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) {
// Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @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 Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such 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.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library SafeCast {
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 value) internal pure returns (uint224) {
require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(value);
}
/**
* @dev Returns the downcasted uint128 from uint256, reverting on
* overflow (when the input is greater than largest uint128).
*
* Counterpart to Solidity's `uint128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*/
function toUint128(uint256 value) internal pure returns (uint128) {
require(value <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits");
return uint128(value);
}
/**
* @dev Returns the downcasted uint96 from uint256, reverting on
* overflow (when the input is greater than largest uint96).
*
* Counterpart to Solidity's `uint96` operator.
*
* Requirements:
*
* - input must fit into 96 bits
*/
function toUint96(uint256 value) internal pure returns (uint96) {
require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits");
return uint96(value);
}
/**
* @dev Returns the downcasted uint64 from uint256, reverting on
* overflow (when the input is greater than largest uint64).
*
* Counterpart to Solidity's `uint64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*/
function toUint64(uint256 value) internal pure returns (uint64) {
require(value <= type(uint64).max, "SafeCast: value doesn't fit in 64 bits");
return uint64(value);
}
/**
* @dev Returns the downcasted uint32 from uint256, reverting on
* overflow (when the input is greater than largest uint32).
*
* Counterpart to Solidity's `uint32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*/
function toUint32(uint256 value) internal pure returns (uint32) {
require(value <= type(uint32).max, "SafeCast: value doesn't fit in 32 bits");
return uint32(value);
}
/**
* @dev Returns the downcasted uint16 from uint256, reverting on
* overflow (when the input is greater than largest uint16).
*
* Counterpart to Solidity's `uint16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*/
function toUint16(uint256 value) internal pure returns (uint16) {
require(value <= type(uint16).max, "SafeCast: value doesn't fit in 16 bits");
return uint16(value);
}
/**
* @dev Returns the downcasted uint8 from uint256, reverting on
* overflow (when the input is greater than largest uint8).
*
* Counterpart to Solidity's `uint8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*/
function toUint8(uint256 value) internal pure returns (uint8) {
require(value <= type(uint8).max, "SafeCast: value doesn't fit in 8 bits");
return uint8(value);
}
/**
* @dev Converts a signed int256 into an unsigned uint256.
*
* Requirements:
*
* - input must be greater than or equal to 0.
*/
function toUint256(int256 value) internal pure returns (uint256) {
require(value >= 0, "SafeCast: value must be positive");
return uint256(value);
}
/**
* @dev Returns the downcasted int128 from int256, reverting on
* overflow (when the input is less than smallest int128 or
* greater than largest int128).
*
* Counterpart to Solidity's `int128` operator.
*
* Requirements:
*
* - input must fit into 128 bits
*
* _Available since v3.1._
*/
function toInt128(int256 value) internal pure returns (int128) {
require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits");
return int128(value);
}
/**
* @dev Returns the downcasted int64 from int256, reverting on
* overflow (when the input is less than smallest int64 or
* greater than largest int64).
*
* Counterpart to Solidity's `int64` operator.
*
* Requirements:
*
* - input must fit into 64 bits
*
* _Available since v3.1._
*/
function toInt64(int256 value) internal pure returns (int64) {
require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits");
return int64(value);
}
/**
* @dev Returns the downcasted int32 from int256, reverting on
* overflow (when the input is less than smallest int32 or
* greater than largest int32).
*
* Counterpart to Solidity's `int32` operator.
*
* Requirements:
*
* - input must fit into 32 bits
*
* _Available since v3.1._
*/
function toInt32(int256 value) internal pure returns (int32) {
require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits");
return int32(value);
}
/**
* @dev Returns the downcasted int16 from int256, reverting on
* overflow (when the input is less than smallest int16 or
* greater than largest int16).
*
* Counterpart to Solidity's `int16` operator.
*
* Requirements:
*
* - input must fit into 16 bits
*
* _Available since v3.1._
*/
function toInt16(int256 value) internal pure returns (int16) {
require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits");
return int16(value);
}
/**
* @dev Returns the downcasted int8 from int256, reverting on
* overflow (when the input is less than smallest int8 or
* greater than largest int8).
*
* Counterpart to Solidity's `int8` operator.
*
* Requirements:
*
* - input must fit into 8 bits.
*
* _Available since v3.1._
*/
function toInt8(int256 value) internal pure returns (int8) {
require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits");
return int8(value);
}
/**
* @dev Converts an unsigned uint256 into a signed int256.
*
* Requirements:
*
* - input must be less than or equal to maxInt256.
*/
function toInt256(uint256 value) internal pure returns (int256) {
// Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive
require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256");
return int256(value);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
import "./Ownable.sol";
/**
* @title Abstract manageable contract that can be inherited by other contracts
* @notice Contract module based on Ownable which provides a basic access control mechanism, where
* there is an owner and a manager that can be granted exclusive access to specific functions.
*
* By default, the owner is the deployer of the contract.
*
* The owner account is set through a two steps process.
* 1. The current `owner` calls {transferOwnership} to set a `pendingOwner`
* 2. The `pendingOwner` calls {acceptOwnership} to accept the ownership transfer
*
* The manager account needs to be set using {setManager}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyManager`, which can be applied to your functions to restrict their use to
* the manager.
*/
abstract contract Manageable is Ownable {
address private _manager;
/**
* @dev Emitted when `_manager` has been changed.
* @param previousManager previous `_manager` address.
* @param newManager new `_manager` address.
*/
event ManagerTransferred(address indexed previousManager, address indexed newManager);
/* ============ External Functions ============ */
/**
* @notice Gets current `_manager`.
* @return Current `_manager` address.
*/
function manager() public view virtual returns (address) {
return _manager;
}
/**
* @notice Set or change of manager.
* @dev Throws if called by any account other than the owner.
* @param _newManager New _manager address.
* @return Boolean to indicate if the operation was successful or not.
*/
function setManager(address _newManager) external onlyOwner returns (bool) {
return _setManager(_newManager);
}
/* ============ Internal Functions ============ */
/**
* @notice Set or change of manager.
* @param _newManager New _manager address.
* @return Boolean to indicate if the operation was successful or not.
*/
function _setManager(address _newManager) private returns (bool) {
address _previousManager = _manager;
require(_newManager != _previousManager, "Manageable/existing-manager-address");
_manager = _newManager;
emit ManagerTransferred(_previousManager, _newManager);
return true;
}
/* ============ Modifier Functions ============ */
/**
* @dev Throws if called by any account other than the manager.
*/
modifier onlyManager() {
require(manager() == msg.sender, "Manageable/caller-not-manager");
_;
}
/**
* @dev Throws if called by any account other than the manager or the owner.
*/
modifier onlyManagerOrOwner() {
require(manager() == msg.sender || owner() == msg.sender, "Manageable/caller-not-manager-or-owner");
_;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.8.0;
/**
* @title Abstract ownable contract that can be inherited by other contracts
* @notice 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 is the deployer of the contract.
*
* The owner account is set through a two steps process.
* 1. The current `owner` calls {transferOwnership} to set a `pendingOwner`
* 2. The `pendingOwner` calls {acceptOwnership} to accept the ownership transfer
*
* The manager account needs to be set using {setManager}.
*
* 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 {
address private _owner;
address private _pendingOwner;
/**
* @dev Emitted when `_pendingOwner` has been changed.
* @param pendingOwner new `_pendingOwner` address.
*/
event OwnershipOffered(address indexed pendingOwner);
/**
* @dev Emitted when `_owner` has been changed.
* @param previousOwner previous `_owner` address.
* @param newOwner new `_owner` address.
*/
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/* ============ Deploy ============ */
/**
* @notice Initializes the contract setting `_initialOwner` as the initial owner.
* @param _initialOwner Initial owner of the contract.
*/
constructor(address _initialOwner) {
_setOwner(_initialOwner);
}
/* ============ External Functions ============ */
/**
* @notice Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @notice Gets current `_pendingOwner`.
* @return Current `_pendingOwner` address.
*/
function pendingOwner() external view virtual returns (address) {
return _pendingOwner;
}
/**
* @notice Renounce ownership of the contract.
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() external virtual onlyOwner {
_setOwner(address(0));
}
/**
* @notice Allows current owner to set the `_pendingOwner` address.
* @param _newOwner Address to transfer ownership to.
*/
function transferOwnership(address _newOwner) external onlyOwner {
require(_newOwner != address(0), "Ownable/pendingOwner-not-zero-address");
_pendingOwner = _newOwner;
emit OwnershipOffered(_newOwner);
}
/**
* @notice Allows the `_pendingOwner` address to finalize the transfer.
* @dev This function is only callable by the `_pendingOwner`.
*/
function claimOwnership() external onlyPendingOwner {
_setOwner(_pendingOwner);
_pendingOwner = address(0);
}
/* ============ Internal Functions ============ */
/**
* @notice Internal function to set the `_owner` of the contract.
* @param _newOwner New `_owner` address.
*/
function _setOwner(address _newOwner) private {
address _oldOwner = _owner;
_owner = _newOwner;
emit OwnershipTransferred(_oldOwner, _newOwner);
}
/* ============ Modifier Functions ============ */
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == msg.sender, "Ownable/caller-not-owner");
_;
}
/**
* @dev Throws if called by any account other than the `pendingOwner`.
*/
modifier onlyPendingOwner() {
require(msg.sender == _pendingOwner, "Ownable/caller-not-pendingOwner");
_;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0;
/// @title Random Number Generator Interface
/// @notice Provides an interface for requesting random numbers from 3rd-party RNG services (Chainlink VRF, Starkware VDF, etc..)
interface RNGInterface {
/// @notice Emitted when a new request for a random number has been submitted
/// @param requestId The indexed ID of the request used to get the results of the RNG service
/// @param sender The indexed address of the sender of the request
event RandomNumberRequested(uint32 indexed requestId, address indexed sender);
/// @notice Emitted when an existing request for a random number has been completed
/// @param requestId The indexed ID of the request used to get the results of the RNG service
/// @param randomNumber The random number produced by the 3rd-party service
event RandomNumberCompleted(uint32 indexed requestId, uint256 randomNumber);
/// @notice Gets the last request id used by the RNG service
/// @return requestId The last request id used in the last request
function getLastRequestId() external view returns (uint32 requestId);
/// @notice Gets the Fee for making a Request against an RNG service
/// @return feeToken The address of the token that is used to pay fees
/// @return requestFee The fee required to be paid to make a request
function getRequestFee() external view returns (address feeToken, uint256 requestFee);
/// @notice Sends a request for a random number to the 3rd-party service
/// @dev Some services will complete the request immediately, others may have a time-delay
/// @dev Some services require payment in the form of a token, such as $LINK for Chainlink VRF
/// @return requestId The ID of the request used to get the results of the RNG service
/// @return lockBlock The block number at which the RNG service will start generating time-delayed randomness. The calling contract
/// should "lock" all activity until the result is available via the `requestId`
function requestRandomNumber() external returns (uint32 requestId, uint32 lockBlock);
/// @notice Checks if the request for randomness from the 3rd-party service has completed
/// @dev For time-delayed requests, this function is used to check/confirm completion
/// @param requestId The ID of the request used to get the results of the RNG service
/// @return isCompleted True if the request has completed and a random number is available, false otherwise
function isRequestComplete(uint32 requestId) external view returns (bool isCompleted);
/// @notice Gets the random number produced by the 3rd-party service
/// @param requestId The ID of the request used to get the results of the RNG service
/// @return randomNum The random number
function randomNumber(uint32 requestId) external returns (uint256 randomNum);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "@pooltogether/owner-manager-contracts/contracts/Manageable.sol";
import "./libraries/DrawRingBufferLib.sol";
import "./interfaces/IPrizeDistributionBuffer.sol";
/**
* @title PoolTogether V4 PrizeDistributionBuffer
* @author PoolTogether Inc Team
* @notice The PrizeDistributionBuffer contract provides historical lookups of PrizeDistribution struct parameters (linked with a Draw ID) via a
circular ring buffer. Historical PrizeDistribution parameters can be accessed on-chain using a drawId to calculate
ring buffer storage slot. The PrizeDistribution parameters can be created by manager/owner and existing PrizeDistribution
parameters can only be updated the owner. When adding a new PrizeDistribution basic sanity checks will be used to
validate the incoming parameters.
*/
contract PrizeDistributionBuffer is IPrizeDistributionBuffer, Manageable {
using DrawRingBufferLib for DrawRingBufferLib.Buffer;
/// @notice The maximum cardinality of the prize distribution ring buffer.
/// @dev even with daily draws, 256 will give us over 8 months of history.
uint256 internal constant MAX_CARDINALITY = 256;
/// @notice The ceiling for prize distributions. 1e9 = 100%.
/// @dev It's fixed point 9 because 1e9 is the largest "1" that fits into 2**32
uint256 internal constant TIERS_CEILING = 1e9;
/// @notice Emitted when the contract is deployed.
/// @param cardinality The maximum number of records in the buffer before they begin to expire.
event Deployed(uint8 cardinality);
/// @notice PrizeDistribution ring buffer history.
IPrizeDistributionBuffer.PrizeDistribution[MAX_CARDINALITY]
internal prizeDistributionRingBuffer;
/// @notice Ring buffer metadata (nextIndex, lastId, cardinality)
DrawRingBufferLib.Buffer internal bufferMetadata;
/* ============ Constructor ============ */
/**
* @notice Constructor for PrizeDistributionBuffer
* @param _owner Address of the PrizeDistributionBuffer owner
* @param _cardinality Cardinality of the `bufferMetadata`
*/
constructor(address _owner, uint8 _cardinality) Ownable(_owner) {
bufferMetadata.cardinality = _cardinality;
emit Deployed(_cardinality);
}
/* ============ External Functions ============ */
/// @inheritdoc IPrizeDistributionBuffer
function getBufferCardinality() external view override returns (uint32) {
return bufferMetadata.cardinality;
}
/// @inheritdoc IPrizeDistributionBuffer
function getPrizeDistribution(uint32 _drawId)
external
view
override
returns (IPrizeDistributionBuffer.PrizeDistribution memory)
{
return _getPrizeDistribution(bufferMetadata, _drawId);
}
/// @inheritdoc IPrizeDistributionBuffer
function getPrizeDistributions(uint32[] calldata _drawIds)
external
view
override
returns (IPrizeDistributionBuffer.PrizeDistribution[] memory)
{
uint256 drawIdsLength = _drawIds.length;
DrawRingBufferLib.Buffer memory buffer = bufferMetadata;
IPrizeDistributionBuffer.PrizeDistribution[]
memory _prizeDistributions = new IPrizeDistributionBuffer.PrizeDistribution[](
drawIdsLength
);
for (uint256 i = 0; i < drawIdsLength; i++) {
_prizeDistributions[i] = _getPrizeDistribution(buffer, _drawIds[i]);
}
return _prizeDistributions;
}
/// @inheritdoc IPrizeDistributionBuffer
function getPrizeDistributionCount() external view override returns (uint32) {
DrawRingBufferLib.Buffer memory buffer = bufferMetadata;
if (buffer.lastDrawId == 0) {
return 0;
}
uint32 bufferNextIndex = buffer.nextIndex;
// If the buffer is full return the cardinality, else retun the nextIndex
if (prizeDistributionRingBuffer[bufferNextIndex].matchCardinality != 0) {
return buffer.cardinality;
} else {
return bufferNextIndex;
}
}
/// @inheritdoc IPrizeDistributionBuffer
function getNewestPrizeDistribution()
external
view
override
returns (IPrizeDistributionBuffer.PrizeDistribution memory prizeDistribution, uint32 drawId)
{
DrawRingBufferLib.Buffer memory buffer = bufferMetadata;
return (prizeDistributionRingBuffer[buffer.getIndex(buffer.lastDrawId)], buffer.lastDrawId);
}
/// @inheritdoc IPrizeDistributionBuffer
function getOldestPrizeDistribution()
external
view
override
returns (IPrizeDistributionBuffer.PrizeDistribution memory prizeDistribution, uint32 drawId)
{
DrawRingBufferLib.Buffer memory buffer = bufferMetadata;
// if the ring buffer is full, the oldest is at the nextIndex
prizeDistribution = prizeDistributionRingBuffer[buffer.nextIndex];
// The PrizeDistribution at index 0 IS by default the oldest prizeDistribution.
if (buffer.lastDrawId == 0) {
drawId = 0; // return 0 to indicate no prizeDistribution ring buffer history
} else if (prizeDistribution.bitRangeSize == 0) {
// IF the next PrizeDistribution.bitRangeSize == 0 the ring buffer HAS NOT looped around so the oldest is the first entry.
prizeDistribution = prizeDistributionRingBuffer[0];
drawId = (buffer.lastDrawId + 1) - buffer.nextIndex;
} else {
// Calculates the drawId using the ring buffer cardinality
// Sequential drawIds are gauranteed by DrawRingBufferLib.push()
drawId = (buffer.lastDrawId + 1) - buffer.cardinality;
}
}
/// @inheritdoc IPrizeDistributionBuffer
function pushPrizeDistribution(
uint32 _drawId,
IPrizeDistributionBuffer.PrizeDistribution calldata _prizeDistribution
) external override onlyManagerOrOwner returns (bool) {
return _pushPrizeDistribution(_drawId, _prizeDistribution);
}
/// @inheritdoc IPrizeDistributionBuffer
function setPrizeDistribution(
uint32 _drawId,
IPrizeDistributionBuffer.PrizeDistribution calldata _prizeDistribution
) external override onlyOwner returns (uint32) {
DrawRingBufferLib.Buffer memory buffer = bufferMetadata;
uint32 index = buffer.getIndex(_drawId);
prizeDistributionRingBuffer[index] = _prizeDistribution;
emit PrizeDistributionSet(_drawId, _prizeDistribution);
return _drawId;
}
/* ============ Internal Functions ============ */
/**
* @notice Gets the PrizeDistributionBuffer for a drawId
* @param _buffer DrawRingBufferLib.Buffer
* @param _drawId drawId
*/
function _getPrizeDistribution(DrawRingBufferLib.Buffer memory _buffer, uint32 _drawId)
internal
view
returns (IPrizeDistributionBuffer.PrizeDistribution memory)
{
return prizeDistributionRingBuffer[_buffer.getIndex(_drawId)];
}
/**
* @notice Set newest PrizeDistributionBuffer in ring buffer storage.
* @param _drawId drawId
* @param _prizeDistribution PrizeDistributionBuffer struct
*/
function _pushPrizeDistribution(
uint32 _drawId,
IPrizeDistributionBuffer.PrizeDistribution calldata _prizeDistribution
) internal returns (bool) {
require(_drawId > 0, "DrawCalc/draw-id-gt-0");
require(_prizeDistribution.matchCardinality > 0, "DrawCalc/matchCardinality-gt-0");
require(
_prizeDistribution.bitRangeSize <= 256 / _prizeDistribution.matchCardinality,
"DrawCalc/bitRangeSize-too-large"
);
require(_prizeDistribution.bitRangeSize > 0, "DrawCalc/bitRangeSize-gt-0");
require(_prizeDistribution.maxPicksPerUser > 0, "DrawCalc/maxPicksPerUser-gt-0");
require(_prizeDistribution.expiryDuration > 0, "DrawCalc/expiryDuration-gt-0");
// ensure that the sum of the tiers are not gt 100%
uint256 sumTotalTiers = 0;
uint256 tiersLength = _prizeDistribution.tiers.length;
for (uint256 index = 0; index < tiersLength; index++) {
uint256 tier = _prizeDistribution.tiers[index];
sumTotalTiers += tier;
}
// Each tier amount stored as uint32 - summed can't exceed 1e9
require(sumTotalTiers <= TIERS_CEILING, "DrawCalc/tiers-gt-100%");
DrawRingBufferLib.Buffer memory buffer = bufferMetadata;
// store the PrizeDistribution in the ring buffer
prizeDistributionRingBuffer[buffer.nextIndex] = _prizeDistribution;
// update the ring buffer data
bufferMetadata = buffer.push(_drawId);
emit PrizeDistributionSet(_drawId, _prizeDistribution);
return true;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@pooltogether/owner-manager-contracts/contracts/Ownable.sol";
import "./interfaces/IPrizeDistributor.sol";
import "./interfaces/IDrawCalculator.sol";
/**
* @title PoolTogether V4 PrizeDistributor
* @author PoolTogether Inc Team
* @notice The PrizeDistributor contract holds Tickets (captured interest) and distributes tickets to users with winning draw claims.
PrizeDistributor uses an external IDrawCalculator to validate a users draw claim, before awarding payouts. To prevent users
from reclaiming prizes, a payout history for each draw claim is mapped to user accounts. Reclaiming a draw can occur
if an "optimal" prize was not included in previous claim pick indices and the new claims updated payout is greater then
the previous prize distributor claim payout.
*/
contract PrizeDistributor is IPrizeDistributor, Ownable {
using SafeERC20 for IERC20;
/* ============ Global Variables ============ */
/// @notice DrawCalculator address
IDrawCalculator internal drawCalculator;
/// @notice Token address
IERC20 internal immutable token;
/// @notice Maps users => drawId => paid out balance
mapping(address => mapping(uint256 => uint256)) internal userDrawPayouts;
/* ============ Initialize ============ */
/**
* @notice Initialize PrizeDistributor smart contract.
* @param _owner Owner address
* @param _token Token address
* @param _drawCalculator DrawCalculator address
*/
constructor(
address _owner,
IERC20 _token,
IDrawCalculator _drawCalculator
) Ownable(_owner) {
_setDrawCalculator(_drawCalculator);
require(address(_token) != address(0), "PrizeDistributor/token-not-zero-address");
token = _token;
emit TokenSet(_token);
}
/* ============ External Functions ============ */
/// @inheritdoc IPrizeDistributor
function claim(
address _user,
uint32[] calldata _drawIds,
bytes calldata _data
) external override returns (uint256) {
uint256 totalPayout;
(uint256[] memory drawPayouts, ) = drawCalculator.calculate(_user, _drawIds, _data); // neglect the prizeCounts since we are not interested in them here
uint256 drawPayoutsLength = drawPayouts.length;
for (uint256 payoutIndex = 0; payoutIndex < drawPayoutsLength; payoutIndex++) {
uint32 drawId = _drawIds[payoutIndex];
uint256 payout = drawPayouts[payoutIndex];
uint256 oldPayout = _getDrawPayoutBalanceOf(_user, drawId);
uint256 payoutDiff = 0;
// helpfully short-circuit, in case the user screwed something up.
require(payout > oldPayout, "PrizeDistributor/zero-payout");
unchecked {
payoutDiff = payout - oldPayout;
}
_setDrawPayoutBalanceOf(_user, drawId, payout);
totalPayout += payoutDiff;
emit ClaimedDraw(_user, drawId, payoutDiff);
}
_awardPayout(_user, totalPayout);
return totalPayout;
}
/// @inheritdoc IPrizeDistributor
function withdrawERC20(
IERC20 _erc20Token,
address _to,
uint256 _amount
) external override onlyOwner returns (bool) {
require(_to != address(0), "PrizeDistributor/recipient-not-zero-address");
require(address(_erc20Token) != address(0), "PrizeDistributor/ERC20-not-zero-address");
_erc20Token.safeTransfer(_to, _amount);
emit ERC20Withdrawn(_erc20Token, _to, _amount);
return true;
}
/// @inheritdoc IPrizeDistributor
function getDrawCalculator() external view override returns (IDrawCalculator) {
return drawCalculator;
}
/// @inheritdoc IPrizeDistributor
function getDrawPayoutBalanceOf(address _user, uint32 _drawId)
external
view
override
returns (uint256)
{
return _getDrawPayoutBalanceOf(_user, _drawId);
}
/// @inheritdoc IPrizeDistributor
function getToken() external view override returns (IERC20) {
return token;
}
/// @inheritdoc IPrizeDistributor
function setDrawCalculator(IDrawCalculator _newCalculator)
external
override
onlyOwner
returns (IDrawCalculator)
{
_setDrawCalculator(_newCalculator);
return _newCalculator;
}
/* ============ Internal Functions ============ */
function _getDrawPayoutBalanceOf(address _user, uint32 _drawId)
internal
view
returns (uint256)
{
return userDrawPayouts[_user][_drawId];
}
function _setDrawPayoutBalanceOf(
address _user,
uint32 _drawId,
uint256 _payout
) internal {
userDrawPayouts[_user][_drawId] = _payout;
}
/**
* @notice Sets DrawCalculator reference for individual draw id.
* @param _newCalculator DrawCalculator address
*/
function _setDrawCalculator(IDrawCalculator _newCalculator) internal {
require(address(_newCalculator) != address(0), "PrizeDistributor/calc-not-zero");
drawCalculator = _newCalculator;
emit DrawCalculatorSet(_newCalculator);
}
/**
* @notice Transfer claimed draw(s) total payout to user.
* @param _to User address
* @param _amount Transfer amount
*/
function _awardPayout(address _to, uint256 _amount) internal {
token.safeTransfer(_to, _amount);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
/** @title IControlledToken
* @author PoolTogether Inc Team
* @notice ERC20 Tokens with a controller for minting & burning.
*/
interface IControlledToken is IERC20 {
/**
@notice Interface to the contract responsible for controlling mint/burn
*/
function controller() external view returns (address);
/**
* @notice Allows the controller to mint tokens for a user account
* @dev May be overridden to provide more granular control over minting
* @param user Address of the receiver of the minted tokens
* @param amount Amount of tokens to mint
*/
function controllerMint(address user, uint256 amount) external;
/**
* @notice Allows the controller to burn tokens from a user account
* @dev May be overridden to provide more granular control over burning
* @param user Address of the holder account to burn tokens from
* @param amount Amount of tokens to burn
*/
function controllerBurn(address user, uint256 amount) external;
/**
* @notice Allows an operator via the controller to burn tokens on behalf of a user account
* @dev May be overridden to provide more granular control over operator-burning
* @param operator Address of the operator performing the burn action via the controller contract
* @param user Address of the holder account to burn tokens from
* @param amount Amount of tokens to burn
*/
function controllerBurnFrom(
address operator,
address user,
uint256 amount
) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "@pooltogether/pooltogether-rng-contracts/contracts/RNGInterface.sol";
import "./IDrawBuffer.sol";
/** @title IDrawBeacon
* @author PoolTogether Inc Team
* @notice The DrawBeacon interface.
*/
interface IDrawBeacon {
/// @notice Draw struct created every draw
/// @param winningRandomNumber The random number returned from the RNG service
/// @param drawId The monotonically increasing drawId for each draw
/// @param timestamp Unix timestamp of the draw. Recorded when the draw is created by the DrawBeacon.
/// @param beaconPeriodStartedAt Unix timestamp of when the draw started
/// @param beaconPeriodSeconds Unix timestamp of the beacon draw period for this draw.
struct Draw {
uint256 winningRandomNumber;
uint32 drawId;
uint64 timestamp;
uint64 beaconPeriodStartedAt;
uint32 beaconPeriodSeconds;
}
/**
* @notice Emit when a new DrawBuffer has been set.
* @param newDrawBuffer The new DrawBuffer address
*/
event DrawBufferUpdated(IDrawBuffer indexed newDrawBuffer);
/**
* @notice Emit when a draw has opened.
* @param startedAt Start timestamp
*/
event BeaconPeriodStarted(uint64 indexed startedAt);
/**
* @notice Emit when a draw has started.
* @param rngRequestId draw id
* @param rngLockBlock Block when draw becomes invalid
*/
event DrawStarted(uint32 indexed rngRequestId, uint32 rngLockBlock);
/**
* @notice Emit when a draw has been cancelled.
* @param rngRequestId draw id
* @param rngLockBlock Block when draw becomes invalid
*/
event DrawCancelled(uint32 indexed rngRequestId, uint32 rngLockBlock);
/**
* @notice Emit when a draw has been completed.
* @param randomNumber Random number generated from draw
*/
event DrawCompleted(uint256 randomNumber);
/**
* @notice Emit when a RNG service address is set.
* @param rngService RNG service address
*/
event RngServiceUpdated(RNGInterface indexed rngService);
/**
* @notice Emit when a draw timeout param is set.
* @param rngTimeout draw timeout param in seconds
*/
event RngTimeoutSet(uint32 rngTimeout);
/**
* @notice Emit when the drawPeriodSeconds is set.
* @param drawPeriodSeconds Time between draw
*/
event BeaconPeriodSecondsUpdated(uint32 drawPeriodSeconds);
/**
* @notice Returns the number of seconds remaining until the beacon period can be complete.
* @return The number of seconds remaining until the beacon period can be complete.
*/
function beaconPeriodRemainingSeconds() external view returns (uint64);
/**
* @notice Returns the timestamp at which the beacon period ends
* @return The timestamp at which the beacon period ends.
*/
function beaconPeriodEndAt() external view returns (uint64);
/**
* @notice Returns whether a Draw can be started.
* @return True if a Draw can be started, false otherwise.
*/
function canStartDraw() external view returns (bool);
/**
* @notice Returns whether a Draw can be completed.
* @return True if a Draw can be completed, false otherwise.
*/
function canCompleteDraw() external view returns (bool);
/**
* @notice Calculates when the next beacon period will start.
* @param time The timestamp to use as the current time
* @return The timestamp at which the next beacon period would start
*/
function calculateNextBeaconPeriodStartTime(uint64 time) external view returns (uint64);
/**
* @notice Can be called by anyone to cancel the draw request if the RNG has timed out.
*/
function cancelDraw() external;
/**
* @notice Completes the Draw (RNG) request and pushes a Draw onto DrawBuffer.
*/
function completeDraw() external;
/**
* @notice Returns the block number that the current RNG request has been locked to.
* @return The block number that the RNG request is locked to
*/
function getLastRngLockBlock() external view returns (uint32);
/**
* @notice Returns the current RNG Request ID.
* @return The current Request ID
*/
function getLastRngRequestId() external view returns (uint32);
/**
* @notice Returns whether the beacon period is over
* @return True if the beacon period is over, false otherwise
*/
function isBeaconPeriodOver() external view returns (bool);
/**
* @notice Returns whether the random number request has completed.
* @return True if a random number request has completed, false otherwise.
*/
function isRngCompleted() external view returns (bool);
/**
* @notice Returns whether a random number has been requested
* @return True if a random number has been requested, false otherwise.
*/
function isRngRequested() external view returns (bool);
/**
* @notice Returns whether the random number request has timed out.
* @return True if a random number request has timed out, false otherwise.
*/
function isRngTimedOut() external view returns (bool);
/**
* @notice Allows the owner to set the beacon period in seconds.
* @param beaconPeriodSeconds The new beacon period in seconds. Must be greater than zero.
*/
function setBeaconPeriodSeconds(uint32 beaconPeriodSeconds) external;
/**
* @notice Allows the owner to set the RNG request timeout in seconds. This is the time that must elapsed before the RNG request can be cancelled and the pool unlocked.
* @param rngTimeout The RNG request timeout in seconds.
*/
function setRngTimeout(uint32 rngTimeout) external;
/**
* @notice Sets the RNG service that the Prize Strategy is connected to
* @param rngService The address of the new RNG service interface
*/
function setRngService(RNGInterface rngService) external;
/**
* @notice Starts the Draw process by starting random number request. The previous beacon period must have ended.
* @dev The RNG-Request-Fee is expected to be held within this contract before calling this function
*/
function startDraw() external;
/**
* @notice Set global DrawBuffer variable.
* @dev All subsequent Draw requests/completions will be pushed to the new DrawBuffer.
* @param newDrawBuffer DrawBuffer address
* @return DrawBuffer
*/
function setDrawBuffer(IDrawBuffer newDrawBuffer) external returns (IDrawBuffer);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "../interfaces/IDrawBeacon.sol";
/** @title IDrawBuffer
* @author PoolTogether Inc Team
* @notice The DrawBuffer interface.
*/
interface IDrawBuffer {
/**
* @notice Emit when a new draw has been created.
* @param drawId Draw id
* @param draw The Draw struct
*/
event DrawSet(uint32 indexed drawId, IDrawBeacon.Draw draw);
/**
* @notice Read a ring buffer cardinality
* @return Ring buffer cardinality
*/
function getBufferCardinality() external view returns (uint32);
/**
* @notice Read a Draw from the draws ring buffer.
* @dev Read a Draw using the Draw.drawId to calculate position in the draws ring buffer.
* @param drawId Draw.drawId
* @return IDrawBeacon.Draw
*/
function getDraw(uint32 drawId) external view returns (IDrawBeacon.Draw memory);
/**
* @notice Read multiple Draws from the draws ring buffer.
* @dev Read multiple Draws using each drawId to calculate position in the draws ring buffer.
* @param drawIds Array of drawIds
* @return IDrawBeacon.Draw[]
*/
function getDraws(uint32[] calldata drawIds) external view returns (IDrawBeacon.Draw[] memory);
/**
* @notice Gets the number of Draws held in the draw ring buffer.
* @dev If no Draws have been pushed, it will return 0.
* @dev If the ring buffer is full, it will return the cardinality.
* @dev Otherwise, it will return the NewestDraw index + 1.
* @return Number of Draws held in the draw ring buffer.
*/
function getDrawCount() external view returns (uint32);
/**
* @notice Read newest Draw from draws ring buffer.
* @dev Uses the nextDrawIndex to calculate the most recently added Draw.
* @return IDrawBeacon.Draw
*/
function getNewestDraw() external view returns (IDrawBeacon.Draw memory);
/**
* @notice Read oldest Draw from draws ring buffer.
* @dev Finds the oldest Draw by comparing and/or diffing totalDraws with the cardinality.
* @return IDrawBeacon.Draw
*/
function getOldestDraw() external view returns (IDrawBeacon.Draw memory);
/**
* @notice Push Draw onto draws ring buffer history.
* @dev Push new draw onto draws history via authorized manager or owner.
* @param draw IDrawBeacon.Draw
* @return Draw.drawId
*/
function pushDraw(IDrawBeacon.Draw calldata draw) external returns (uint32);
/**
* @notice Set existing Draw in draws ring buffer with new parameters.
* @dev Updating a Draw should be used sparingly and only in the event an incorrect Draw parameter has been stored.
* @param newDraw IDrawBeacon.Draw
* @return Draw.drawId
*/
function setDraw(IDrawBeacon.Draw calldata newDraw) external returns (uint32);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "./ITicket.sol";
import "./IDrawBuffer.sol";
import "../PrizeDistributionBuffer.sol";
import "../PrizeDistributor.sol";
/**
* @title PoolTogether V4 IDrawCalculator
* @author PoolTogether Inc Team
* @notice The DrawCalculator interface.
*/
interface IDrawCalculator {
struct PickPrize {
bool won;
uint8 tierIndex;
}
///@notice Emitted when the contract is initialized
event Deployed(
ITicket indexed ticket,
IDrawBuffer indexed drawBuffer,
IPrizeDistributionBuffer indexed prizeDistributionBuffer
);
///@notice Emitted when the prizeDistributor is set/updated
event PrizeDistributorSet(PrizeDistributor indexed prizeDistributor);
/**
* @notice Calculates the prize amount for a user for Multiple Draws. Typically called by a PrizeDistributor.
* @param user User for which to calculate prize amount.
* @param drawIds drawId array for which to calculate prize amounts for.
* @param data The ABI encoded pick indices for all Draws. Expected to be winning picks. Pick indices must be less than the totalUserPicks.
* @return List of awardable prize amounts ordered by drawId.
*/
function calculate(
address user,
uint32[] calldata drawIds,
bytes calldata data
) external view returns (uint256[] memory, bytes memory);
/**
* @notice Read global DrawBuffer variable.
* @return IDrawBuffer
*/
function getDrawBuffer() external view returns (IDrawBuffer);
/**
* @notice Read global DrawBuffer variable.
* @return IDrawBuffer
*/
function getPrizeDistributionBuffer() external view returns (IPrizeDistributionBuffer);
/**
* @notice Returns a users balances expressed as a fraction of the total supply over time.
* @param user The users address
* @param drawIds The drawsId to consider
* @return Array of balances
*/
function getNormalizedBalancesForDrawIds(address user, uint32[] calldata drawIds)
external
view
returns (uint256[] memory);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
/** @title IPrizeDistributionBuffer
* @author PoolTogether Inc Team
* @notice The PrizeDistributionBuffer interface.
*/
interface IPrizeDistributionBuffer {
///@notice PrizeDistribution struct created every draw
///@param bitRangeSize Decimal representation of bitRangeSize
///@param matchCardinality The number of numbers to consider in the 256 bit random number. Must be > 1 and < 256/bitRangeSize.
///@param startTimestampOffset The starting time offset in seconds from which Ticket balances are calculated.
///@param endTimestampOffset The end time offset in seconds from which Ticket balances are calculated.
///@param maxPicksPerUser Maximum number of picks a user can make in this draw
///@param expiryDuration Length of time in seconds the PrizeDistribution is valid for. Relative to the Draw.timestamp.
///@param numberOfPicks Number of picks this draw has (may vary across networks according to how much the network has contributed to the Reserve)
///@param tiers Array of prize tiers percentages, expressed in fraction form with base 1e9. Ordering: index0: grandPrize, index1: runnerUp, etc.
///@param prize Total prize amount available in this draw calculator for this draw (may vary from across networks)
struct PrizeDistribution {
uint8 bitRangeSize;
uint8 matchCardinality;
uint32 startTimestampOffset;
uint32 endTimestampOffset;
uint32 maxPicksPerUser;
uint32 expiryDuration;
uint104 numberOfPicks;
uint32[16] tiers;
uint256 prize;
}
/**
* @notice Emit when PrizeDistribution is set.
* @param drawId Draw id
* @param prizeDistribution IPrizeDistributionBuffer.PrizeDistribution
*/
event PrizeDistributionSet(
uint32 indexed drawId,
IPrizeDistributionBuffer.PrizeDistribution prizeDistribution
);
/**
* @notice Read a ring buffer cardinality
* @return Ring buffer cardinality
*/
function getBufferCardinality() external view returns (uint32);
/**
* @notice Read newest PrizeDistribution from prize distributions ring buffer.
* @dev Uses nextDrawIndex to calculate the most recently added PrizeDistribution.
* @return prizeDistribution
* @return drawId
*/
function getNewestPrizeDistribution()
external
view
returns (IPrizeDistributionBuffer.PrizeDistribution memory prizeDistribution, uint32 drawId);
/**
* @notice Read oldest PrizeDistribution from prize distributions ring buffer.
* @dev Finds the oldest Draw by buffer.nextIndex and buffer.lastDrawId
* @return prizeDistribution
* @return drawId
*/
function getOldestPrizeDistribution()
external
view
returns (IPrizeDistributionBuffer.PrizeDistribution memory prizeDistribution, uint32 drawId);
/**
* @notice Gets PrizeDistribution list from array of drawIds
* @param drawIds drawIds to get PrizeDistribution for
* @return prizeDistributionList
*/
function getPrizeDistributions(uint32[] calldata drawIds)
external
view
returns (IPrizeDistributionBuffer.PrizeDistribution[] memory);
/**
* @notice Gets the PrizeDistributionBuffer for a drawId
* @param drawId drawId
* @return prizeDistribution
*/
function getPrizeDistribution(uint32 drawId)
external
view
returns (IPrizeDistributionBuffer.PrizeDistribution memory);
/**
* @notice Gets the number of PrizeDistributions stored in the prize distributions ring buffer.
* @dev If no Draws have been pushed, it will return 0.
* @dev If the ring buffer is full, it will return the cardinality.
* @dev Otherwise, it will return the NewestPrizeDistribution index + 1.
* @return Number of PrizeDistributions stored in the prize distributions ring buffer.
*/
function getPrizeDistributionCount() external view returns (uint32);
/**
* @notice Adds new PrizeDistribution record to ring buffer storage.
* @dev Only callable by the owner or manager
* @param drawId Draw ID linked to PrizeDistribution parameters
* @param prizeDistribution PrizeDistribution parameters struct
*/
function pushPrizeDistribution(
uint32 drawId,
IPrizeDistributionBuffer.PrizeDistribution calldata prizeDistribution
) external returns (bool);
/**
* @notice Sets existing PrizeDistribution with new PrizeDistribution parameters in ring buffer storage.
* @dev Retroactively updates an existing PrizeDistribution and should be thought of as a "safety"
fallback. If the manager is setting invalid PrizeDistribution parameters the Owner can update
the invalid parameters with correct parameters.
* @return drawId
*/
function setPrizeDistribution(uint32 drawId, IPrizeDistributionBuffer.PrizeDistribution calldata draw)
external
returns (uint32);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "./IDrawBuffer.sol";
import "./IDrawCalculator.sol";
/** @title IPrizeDistributor
* @author PoolTogether Inc Team
* @notice The PrizeDistributor interface.
*/
interface IPrizeDistributor {
/**
* @notice Emit when user has claimed token from the PrizeDistributor.
* @param user User address receiving draw claim payouts
* @param drawId Draw id that was paid out
* @param payout Payout for draw
*/
event ClaimedDraw(address indexed user, uint32 indexed drawId, uint256 payout);
/**
* @notice Emit when DrawCalculator is set.
* @param calculator DrawCalculator address
*/
event DrawCalculatorSet(IDrawCalculator indexed calculator);
/**
* @notice Emit when Token is set.
* @param token Token address
*/
event TokenSet(IERC20 indexed token);
/**
* @notice Emit when ERC20 tokens are withdrawn.
* @param token ERC20 token transferred.
* @param to Address that received funds.
* @param amount Amount of tokens transferred.
*/
event ERC20Withdrawn(IERC20 indexed token, address indexed to, uint256 amount);
/**
* @notice Claim prize payout(s) by submitting valud drawId(s) and winning pick indice(s). The user address
is used as the "seed" phrase to generate random numbers.
* @dev The claim function is public and any wallet may execute claim on behalf of another user.
Prizes are always paid out to the designated user account and not the caller (msg.sender).
Claiming prizes is not limited to a single transaction. Reclaiming can be executed
subsequentially if an "optimal" prize was not included in previous claim pick indices. The
payout difference for the new claim is calculated during the award process and transfered to user.
* @param user Address of user to claim awards for. Does NOT need to be msg.sender
* @param drawIds Draw IDs from global DrawBuffer reference
* @param data The data to pass to the draw calculator
* @return Total claim payout. May include calcuations from multiple draws.
*/
function claim(
address user,
uint32[] calldata drawIds,
bytes calldata data
) external returns (uint256);
/**
* @notice Read global DrawCalculator address.
* @return IDrawCalculator
*/
function getDrawCalculator() external view returns (IDrawCalculator);
/**
* @notice Get the amount that a user has already been paid out for a draw
* @param user User address
* @param drawId Draw ID
*/
function getDrawPayoutBalanceOf(address user, uint32 drawId) external view returns (uint256);
/**
* @notice Read global Ticket address.
* @return IERC20
*/
function getToken() external view returns (IERC20);
/**
* @notice Sets DrawCalculator reference contract.
* @param newCalculator DrawCalculator address
* @return New DrawCalculator address
*/
function setDrawCalculator(IDrawCalculator newCalculator) external returns (IDrawCalculator);
/**
* @notice Transfer ERC20 tokens out of contract to recipient address.
* @dev Only callable by contract owner.
* @param token ERC20 token to transfer.
* @param to Recipient of the tokens.
* @param amount Amount of tokens to transfer.
* @return true if operation is successful.
*/
function withdrawERC20(
IERC20 token,
address to,
uint256 amount
) external returns (bool);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "../libraries/TwabLib.sol";
import "./IControlledToken.sol";
interface ITicket is IControlledToken {
/**
* @notice A struct containing details for an Account.
* @param balance The current balance for an Account.
* @param nextTwabIndex The next available index to store a new twab.
* @param cardinality The number of recorded twabs (plus one!).
*/
struct AccountDetails {
uint224 balance;
uint16 nextTwabIndex;
uint16 cardinality;
}
/**
* @notice Combines account details with their twab history.
* @param details The account details.
* @param twabs The history of twabs for this account.
*/
struct Account {
AccountDetails details;
ObservationLib.Observation[65535] twabs;
}
/**
* @notice Emitted when TWAB balance has been delegated to another user.
* @param delegator Address of the delegator.
* @param delegate Address of the delegate.
*/
event Delegated(address indexed delegator, address indexed delegate);
/**
* @notice Emitted when ticket is initialized.
* @param name Ticket name (eg: PoolTogether Dai Ticket (Compound)).
* @param symbol Ticket symbol (eg: PcDAI).
* @param decimals Ticket decimals.
* @param controller Token controller address.
*/
event TicketInitialized(string name, string symbol, uint8 decimals, address indexed controller);
/**
* @notice Emitted when a new TWAB has been recorded.
* @param delegate The recipient of the ticket power (may be the same as the user).
* @param newTwab Updated TWAB of a ticket holder after a successful TWAB recording.
*/
event NewUserTwab(
address indexed delegate,
ObservationLib.Observation newTwab
);
/**
* @notice Emitted when a new total supply TWAB has been recorded.
* @param newTotalSupplyTwab Updated TWAB of tickets total supply after a successful total supply TWAB recording.
*/
event NewTotalSupplyTwab(ObservationLib.Observation newTotalSupplyTwab);
/**
* @notice Retrieves the address of the delegate to whom `user` has delegated their tickets.
* @dev Address of the delegate will be the zero address if `user` has not delegated their tickets.
* @param user Address of the delegator.
* @return Address of the delegate.
*/
function delegateOf(address user) external view returns (address);
/**
* @notice Delegate time-weighted average balances to an alternative address.
* @dev Transfers (including mints) trigger the storage of a TWAB in delegate(s) account, instead of the
targetted sender and/or recipient address(s).
* @dev To reset the delegate, pass the zero address (0x000.000) as `to` parameter.
* @dev Current delegate address should be different from the new delegate address `to`.
* @param to Recipient of delegated TWAB.
*/
function delegate(address to) external;
/**
* @notice Allows the controller to delegate on a users behalf.
* @param user The user for whom to delegate
* @param delegate The new delegate
*/
function controllerDelegateFor(address user, address delegate) external;
/**
* @notice Allows a user to delegate via signature
* @param user The user who is delegating
* @param delegate The new delegate
* @param deadline The timestamp by which this must be submitted
* @param v The v portion of the ECDSA sig
* @param r The r portion of the ECDSA sig
* @param s The s portion of the ECDSA sig
*/
function delegateWithSignature(
address user,
address delegate,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @notice Gets a users twab context. This is a struct with their balance, next twab index, and cardinality.
* @param user The user for whom to fetch the TWAB context.
* @return The TWAB context, which includes { balance, nextTwabIndex, cardinality }
*/
function getAccountDetails(address user) external view returns (TwabLib.AccountDetails memory);
/**
* @notice Gets the TWAB at a specific index for a user.
* @param user The user for whom to fetch the TWAB.
* @param index The index of the TWAB to fetch.
* @return The TWAB, which includes the twab amount and the timestamp.
*/
function getTwab(address user, uint16 index)
external
view
returns (ObservationLib.Observation memory);
/**
* @notice Retrieves `user` TWAB balance.
* @param user Address of the user whose TWAB is being fetched.
* @param timestamp Timestamp at which we want to retrieve the TWAB balance.
* @return The TWAB balance at the given timestamp.
*/
function getBalanceAt(address user, uint64 timestamp) external view returns (uint256);
/**
* @notice Retrieves `user` TWAB balances.
* @param user Address of the user whose TWABs are being fetched.
* @param timestamps Timestamps range at which we want to retrieve the TWAB balances.
* @return `user` TWAB balances.
*/
function getBalancesAt(address user, uint64[] calldata timestamps)
external
view
returns (uint256[] memory);
/**
* @notice Retrieves the average balance held by a user for a given time frame.
* @param user The user whose balance is checked.
* @param startTime The start time of the time frame.
* @param endTime The end time of the time frame.
* @return The average balance that the user held during the time frame.
*/
function getAverageBalanceBetween(
address user,
uint64 startTime,
uint64 endTime
) external view returns (uint256);
/**
* @notice Retrieves the average balances held by a user for a given time frame.
* @param user The user whose balance is checked.
* @param startTimes The start time of the time frame.
* @param endTimes The end time of the time frame.
* @return The average balance that the user held during the time frame.
*/
function getAverageBalancesBetween(
address user,
uint64[] calldata startTimes,
uint64[] calldata endTimes
) external view returns (uint256[] memory);
/**
* @notice Retrieves the total supply TWAB balance at the given timestamp.
* @param timestamp Timestamp at which we want to retrieve the total supply TWAB balance.
* @return The total supply TWAB balance at the given timestamp.
*/
function getTotalSupplyAt(uint64 timestamp) external view returns (uint256);
/**
* @notice Retrieves the total supply TWAB balance between the given timestamps range.
* @param timestamps Timestamps range at which we want to retrieve the total supply TWAB balance.
* @return Total supply TWAB balances.
*/
function getTotalSuppliesAt(uint64[] calldata timestamps)
external
view
returns (uint256[] memory);
/**
* @notice Retrieves the average total supply balance for a set of given time frames.
* @param startTimes Array of start times.
* @param endTimes Array of end times.
* @return The average total supplies held during the time frame.
*/
function getAverageTotalSuppliesBetween(
uint64[] calldata startTimes,
uint64[] calldata endTimes
) external view returns (uint256[] memory);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "./RingBufferLib.sol";
/// @title Library for creating and managing a draw ring buffer.
library DrawRingBufferLib {
/// @notice Draw buffer struct.
struct Buffer {
uint32 lastDrawId;
uint32 nextIndex;
uint32 cardinality;
}
/// @notice Helper function to know if the draw ring buffer has been initialized.
/// @dev since draws start at 1 and are monotonically increased, we know we are uninitialized if nextIndex = 0 and lastDrawId = 0.
/// @param _buffer The buffer to check.
function isInitialized(Buffer memory _buffer) internal pure returns (bool) {
return !(_buffer.nextIndex == 0 && _buffer.lastDrawId == 0);
}
/// @notice Push a draw to the buffer.
/// @param _buffer The buffer to push to.
/// @param _drawId The drawID to push.
/// @return The new buffer.
function push(Buffer memory _buffer, uint32 _drawId) internal pure returns (Buffer memory) {
require(!isInitialized(_buffer) || _drawId == _buffer.lastDrawId + 1, "DRB/must-be-contig");
return
Buffer({
lastDrawId: _drawId,
nextIndex: uint32(RingBufferLib.nextIndex(_buffer.nextIndex, _buffer.cardinality)),
cardinality: _buffer.cardinality
});
}
/// @notice Get draw ring buffer index pointer.
/// @param _buffer The buffer to get the `nextIndex` from.
/// @param _drawId The draw id to get the index for.
/// @return The draw ring buffer index pointer.
function getIndex(Buffer memory _buffer, uint32 _drawId) internal pure returns (uint32) {
require(isInitialized(_buffer) && _drawId <= _buffer.lastDrawId, "DRB/future-draw");
uint32 indexOffset = _buffer.lastDrawId - _drawId;
require(indexOffset < _buffer.cardinality, "DRB/expired-draw");
uint256 mostRecent = RingBufferLib.newestIndex(_buffer.nextIndex, _buffer.cardinality);
return uint32(RingBufferLib.offset(uint32(mostRecent), indexOffset, _buffer.cardinality));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
/**
* @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow
* checks.
*
* Downcasting from uint256/int256 in Solidity does not revert on overflow. This can
* easily result in undesired exploitation or bugs, since developers usually
* assume that overflows raise errors. `SafeCast` restores this intuition by
* reverting the transaction when such 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.
*
* Can be combined with {SafeMath} and {SignedSafeMath} to extend it to smaller types, by performing
* all math on `uint256` and `int256` and then downcasting.
*/
library ExtendedSafeCastLib {
/**
* @dev Returns the downcasted uint208 from uint256, reverting on
* overflow (when the input is greater than largest uint208).
*
* Counterpart to Solidity's `uint208` operator.
*
* Requirements:
*
* - input must fit into 208 bits
*/
function toUint208(uint256 _value) internal pure returns (uint208) {
require(_value <= type(uint208).max, "SafeCast: value doesn't fit in 208 bits");
return uint208(_value);
}
/**
* @dev Returns the downcasted uint224 from uint256, reverting on
* overflow (when the input is greater than largest uint224).
*
* Counterpart to Solidity's `uint224` operator.
*
* Requirements:
*
* - input must fit into 224 bits
*/
function toUint224(uint256 _value) internal pure returns (uint224) {
require(_value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits");
return uint224(_value);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
import "./OverflowSafeComparatorLib.sol";
import "./RingBufferLib.sol";
/**
* @title Observation Library
* @notice This library allows one to store an array of timestamped values and efficiently binary search them.
* @dev Largely pulled from Uniswap V3 Oracle.sol: https://github.com/Uniswap/v3-core/blob/c05a0e2c8c08c460fb4d05cfdda30b3ad8deeaac/contracts/libraries/Oracle.sol
* @author PoolTogether Inc.
*/
library ObservationLib {
using OverflowSafeComparatorLib for uint32;
using SafeCast for uint256;
/// @notice The maximum number of observations
uint24 public constant MAX_CARDINALITY = 16777215; // 2**24
/**
* @notice Observation, which includes an amount and timestamp.
* @param amount `amount` at `timestamp`.
* @param timestamp Recorded `timestamp`.
*/
struct Observation {
uint224 amount;
uint32 timestamp;
}
/**
* @notice Fetches Observations `beforeOrAt` and `atOrAfter` a `_target`, eg: where [`beforeOrAt`, `atOrAfter`] is satisfied.
* The result may be the same Observation, or adjacent Observations.
* @dev The answer must be contained in the array used when the target is located within the stored Observation.
* boundaries: older than the most recent Observation and younger, or the same age as, the oldest Observation.
* @dev If `_newestObservationIndex` is less than `_oldestObservationIndex`, it means that we've wrapped around the circular buffer.
* So the most recent observation will be at `_oldestObservationIndex + _cardinality - 1`, at the beginning of the circular buffer.
* @param _observations List of Observations to search through.
* @param _newestObservationIndex Index of the newest Observation. Right side of the circular buffer.
* @param _oldestObservationIndex Index of the oldest Observation. Left side of the circular buffer.
* @param _target Timestamp at which we are searching the Observation.
* @param _cardinality Cardinality of the circular buffer we are searching through.
* @param _time Timestamp at which we perform the binary search.
* @return beforeOrAt Observation recorded before, or at, the target.
* @return atOrAfter Observation recorded at, or after, the target.
*/
function binarySearch(
Observation[MAX_CARDINALITY] storage _observations,
uint24 _newestObservationIndex,
uint24 _oldestObservationIndex,
uint32 _target,
uint24 _cardinality,
uint32 _time
) internal view returns (Observation memory beforeOrAt, Observation memory atOrAfter) {
uint256 leftSide = _oldestObservationIndex;
uint256 rightSide = _newestObservationIndex < leftSide
? leftSide + _cardinality - 1
: _newestObservationIndex;
uint256 currentIndex;
while (true) {
// We start our search in the middle of the `leftSide` and `rightSide`.
// After each iteration, we narrow down the search to the left or the right side while still starting our search in the middle.
currentIndex = (leftSide + rightSide) / 2;
beforeOrAt = _observations[uint24(RingBufferLib.wrap(currentIndex, _cardinality))];
uint32 beforeOrAtTimestamp = beforeOrAt.timestamp;
// We've landed on an uninitialized timestamp, keep searching higher (more recently).
if (beforeOrAtTimestamp == 0) {
leftSide = currentIndex + 1;
continue;
}
atOrAfter = _observations[uint24(RingBufferLib.nextIndex(currentIndex, _cardinality))];
bool targetAtOrAfter = beforeOrAtTimestamp.lte(_target, _time);
// Check if we've found the corresponding Observation.
if (targetAtOrAfter && _target.lte(atOrAfter.timestamp, _time)) {
break;
}
// If `beforeOrAtTimestamp` is greater than `_target`, then we keep searching lower. To the left of the current index.
if (!targetAtOrAfter) {
rightSide = currentIndex - 1;
} else {
// Otherwise, we keep searching higher. To the left of the current index.
leftSide = currentIndex + 1;
}
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
/// @title OverflowSafeComparatorLib library to share comparator functions between contracts
/// @dev Code taken from Uniswap V3 Oracle.sol: https://github.com/Uniswap/v3-core/blob/3e88af408132fc957e3e406f65a0ce2b1ca06c3d/contracts/libraries/Oracle.sol
/// @author PoolTogether Inc.
library OverflowSafeComparatorLib {
/// @notice 32-bit timestamps comparator.
/// @dev safe for 0 or 1 overflows, `_a` and `_b` must be chronologically before or equal to time.
/// @param _a A comparison timestamp from which to determine the relative position of `_timestamp`.
/// @param _b Timestamp to compare against `_a`.
/// @param _timestamp A timestamp truncated to 32 bits.
/// @return bool Whether `_a` is chronologically < `_b`.
function lt(
uint32 _a,
uint32 _b,
uint32 _timestamp
) internal pure returns (bool) {
// No need to adjust if there hasn't been an overflow
if (_a <= _timestamp && _b <= _timestamp) return _a < _b;
uint256 aAdjusted = _a > _timestamp ? _a : _a + 2**32;
uint256 bAdjusted = _b > _timestamp ? _b : _b + 2**32;
return aAdjusted < bAdjusted;
}
/// @notice 32-bit timestamps comparator.
/// @dev safe for 0 or 1 overflows, `_a` and `_b` must be chronologically before or equal to time.
/// @param _a A comparison timestamp from which to determine the relative position of `_timestamp`.
/// @param _b Timestamp to compare against `_a`.
/// @param _timestamp A timestamp truncated to 32 bits.
/// @return bool Whether `_a` is chronologically <= `_b`.
function lte(
uint32 _a,
uint32 _b,
uint32 _timestamp
) internal pure returns (bool) {
// No need to adjust if there hasn't been an overflow
if (_a <= _timestamp && _b <= _timestamp) return _a <= _b;
uint256 aAdjusted = _a > _timestamp ? _a : _a + 2**32;
uint256 bAdjusted = _b > _timestamp ? _b : _b + 2**32;
return aAdjusted <= bAdjusted;
}
/// @notice 32-bit timestamp subtractor
/// @dev safe for 0 or 1 overflows, where `_a` and `_b` must be chronologically before or equal to time
/// @param _a The subtraction left operand
/// @param _b The subtraction right operand
/// @param _timestamp The current time. Expected to be chronologically after both.
/// @return The difference between a and b, adjusted for overflow
function checkedSub(
uint32 _a,
uint32 _b,
uint32 _timestamp
) internal pure returns (uint32) {
// No need to adjust if there hasn't been an overflow
if (_a <= _timestamp && _b <= _timestamp) return _a - _b;
uint256 aAdjusted = _a > _timestamp ? _a : _a + 2**32;
uint256 bAdjusted = _b > _timestamp ? _b : _b + 2**32;
return uint32(aAdjusted - bAdjusted);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
library RingBufferLib {
/**
* @notice Returns wrapped TWAB index.
* @dev In order to navigate the TWAB circular buffer, we need to use the modulo operator.
* @dev For example, if `_index` is equal to 32 and the TWAB circular buffer is of `_cardinality` 32,
* it will return 0 and will point to the first element of the array.
* @param _index Index used to navigate through the TWAB circular buffer.
* @param _cardinality TWAB buffer cardinality.
* @return TWAB index.
*/
function wrap(uint256 _index, uint256 _cardinality) internal pure returns (uint256) {
return _index % _cardinality;
}
/**
* @notice Computes the negative offset from the given index, wrapped by the cardinality.
* @dev We add `_cardinality` to `_index` to be able to offset even if `_amount` is superior to `_cardinality`.
* @param _index The index from which to offset
* @param _amount The number of indices to offset. This is subtracted from the given index.
* @param _cardinality The number of elements in the ring buffer
* @return Offsetted index.
*/
function offset(
uint256 _index,
uint256 _amount,
uint256 _cardinality
) internal pure returns (uint256) {
return wrap(_index + _cardinality - _amount, _cardinality);
}
/// @notice Returns the index of the last recorded TWAB
/// @param _nextIndex The next available twab index. This will be recorded to next.
/// @param _cardinality The cardinality of the TWAB history.
/// @return The index of the last recorded TWAB
function newestIndex(uint256 _nextIndex, uint256 _cardinality)
internal
pure
returns (uint256)
{
if (_cardinality == 0) {
return 0;
}
return wrap(_nextIndex + _cardinality - 1, _cardinality);
}
/// @notice Computes the ring buffer index that follows the given one, wrapped by cardinality
/// @param _index The index to increment
/// @param _cardinality The number of elements in the Ring Buffer
/// @return The next index relative to the given index. Will wrap around to 0 if the next index == cardinality
function nextIndex(uint256 _index, uint256 _cardinality)
internal
pure
returns (uint256)
{
return wrap(_index + 1, _cardinality);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity 0.8.6;
import "./ExtendedSafeCastLib.sol";
import "./OverflowSafeComparatorLib.sol";
import "./RingBufferLib.sol";
import "./ObservationLib.sol";
/**
* @title PoolTogether V4 TwabLib (Library)
* @author PoolTogether Inc Team
* @dev Time-Weighted Average Balance Library for ERC20 tokens.
* @notice This TwabLib adds on-chain historical lookups to a user(s) time-weighted average balance.
Each user is mapped to an Account struct containing the TWAB history (ring bufffer) and
ring buffer parameters. Every token.transfer() creates a new TWAB checkpoint. The new TWAB
checkpoint is stored in the circular ring buffer, as either a new checkpoint or rewriting
a previous checkpoint with new parameters. The TwabLib (using existing blocktimes 1block/15sec)
guarantees minimum 7.4 years of search history.
*/
library TwabLib {
using OverflowSafeComparatorLib for uint32;
using ExtendedSafeCastLib for uint256;
/**
* @notice Sets max ring buffer length in the Account.twabs Observation list.
As users transfer/mint/burn tickets new Observation checkpoints are
recorded. The current max cardinality guarantees a six month minimum,
of historical accurate lookups with current estimates of 1 new block
every 15 seconds - the of course contain a transfer to trigger an
observation write to storage.
* @dev The user Account.AccountDetails.cardinality parameter can NOT exceed
the max cardinality variable. Preventing "corrupted" ring buffer lookup
pointers and new observation checkpoints.
The MAX_CARDINALITY in fact guarantees at least 7.4 years of records:
If 14 = block time in seconds
(2**24) * 14 = 234881024 seconds of history
234881024 / (365 * 24 * 60 * 60) ~= 7.44 years
*/
uint24 public constant MAX_CARDINALITY = 16777215; // 2**24
/** @notice Struct ring buffer parameters for single user Account
* @param balance Current balance for an Account
* @param nextTwabIndex Next uninitialized or updatable ring buffer checkpoint storage slot
* @param cardinality Current total "initialized" ring buffer checkpoints for single user AccountDetails.
Used to set initial boundary conditions for an efficient binary search.
*/
struct AccountDetails {
uint208 balance;
uint24 nextTwabIndex;
uint24 cardinality;
}
/// @notice Combines account details with their twab history
/// @param details The account details
/// @param twabs The history of twabs for this account
struct Account {
AccountDetails details;
ObservationLib.Observation[MAX_CARDINALITY] twabs;
}
/// @notice Increases an account's balance and records a new twab.
/// @param _account The account whose balance will be increased
/// @param _amount The amount to increase the balance by
/// @param _currentTime The current time
/// @return accountDetails The new AccountDetails
/// @return twab The user's latest TWAB
/// @return isNew Whether the TWAB is new
function increaseBalance(
Account storage _account,
uint208 _amount,
uint32 _currentTime
)
internal
returns (
AccountDetails memory accountDetails,
ObservationLib.Observation memory twab,
bool isNew
)
{
AccountDetails memory _accountDetails = _account.details;
(accountDetails, twab, isNew) = _nextTwab(_account.twabs, _accountDetails, _currentTime);
accountDetails.balance = _accountDetails.balance + _amount;
}
/** @notice Calculates the next TWAB checkpoint for an account with a decreasing balance.
* @dev With Account struct and amount decreasing calculates the next TWAB observable checkpoint.
* @param _account Account whose balance will be decreased
* @param _amount Amount to decrease the balance by
* @param _revertMessage Revert message for insufficient balance
* @return accountDetails Updated Account.details struct
* @return twab TWAB observation (with decreasing average)
* @return isNew Whether TWAB is new or calling twice in the same block
*/
function decreaseBalance(
Account storage _account,
uint208 _amount,
string memory _revertMessage,
uint32 _currentTime
)
internal
returns (
AccountDetails memory accountDetails,
ObservationLib.Observation memory twab,
bool isNew
)
{
AccountDetails memory _accountDetails = _account.details;
require(_accountDetails.balance >= _amount, _revertMessage);
(accountDetails, twab, isNew) = _nextTwab(_account.twabs, _accountDetails, _currentTime);
unchecked {
accountDetails.balance -= _amount;
}
}
/** @notice Calculates the average balance held by a user for a given time frame.
* @dev Finds the average balance between start and end timestamp epochs.
Validates the supplied end time is within the range of elapsed time i.e. less then timestamp of now.
* @param _twabs Individual user Observation recorded checkpoints passed as storage pointer
* @param _accountDetails User AccountDetails struct loaded in memory
* @param _startTime Start of timestamp range as an epoch
* @param _endTime End of timestamp range as an epoch
* @param _currentTime Block.timestamp
* @return Average balance of user held between epoch timestamps start and end
*/
function getAverageBalanceBetween(
ObservationLib.Observation[MAX_CARDINALITY] storage _twabs,
AccountDetails memory _accountDetails,
uint32 _startTime,
uint32 _endTime,
uint32 _currentTime
) internal view returns (uint256) {
uint32 endTime = _endTime > _currentTime ? _currentTime : _endTime;
return
_getAverageBalanceBetween(_twabs, _accountDetails, _startTime, endTime, _currentTime);
}
/// @notice Retrieves the oldest TWAB
/// @param _twabs The storage array of twabs
/// @param _accountDetails The TWAB account details
/// @return index The index of the oldest TWAB in the twabs array
/// @return twab The oldest TWAB
function oldestTwab(
ObservationLib.Observation[MAX_CARDINALITY] storage _twabs,
AccountDetails memory _accountDetails
) internal view returns (uint24 index, ObservationLib.Observation memory twab) {
index = _accountDetails.nextTwabIndex;
twab = _twabs[index];
// If the TWAB is not initialized we go to the beginning of the TWAB circular buffer at index 0
if (twab.timestamp == 0) {
index = 0;
twab = _twabs[0];
}
}
/// @notice Retrieves the newest TWAB
/// @param _twabs The storage array of twabs
/// @param _accountDetails The TWAB account details
/// @return index The index of the newest TWAB in the twabs array
/// @return twab The newest TWAB
function newestTwab(
ObservationLib.Observation[MAX_CARDINALITY] storage _twabs,
AccountDetails memory _accountDetails
) internal view returns (uint24 index, ObservationLib.Observation memory twab) {
index = uint24(RingBufferLib.newestIndex(_accountDetails.nextTwabIndex, MAX_CARDINALITY));
twab = _twabs[index];
}
/// @notice Retrieves amount at `_targetTime` timestamp
/// @param _twabs List of TWABs to search through.
/// @param _accountDetails Accounts details
/// @param _targetTime Timestamp at which the reserved TWAB should be for.
/// @return uint256 TWAB amount at `_targetTime`.
function getBalanceAt(
ObservationLib.Observation[MAX_CARDINALITY] storage _twabs,
AccountDetails memory _accountDetails,
uint32 _targetTime,
uint32 _currentTime
) internal view returns (uint256) {
uint32 timeToTarget = _targetTime > _currentTime ? _currentTime : _targetTime;
return _getBalanceAt(_twabs, _accountDetails, timeToTarget, _currentTime);
}
/// @notice Calculates the average balance held by a user for a given time frame.
/// @param _startTime The start time of the time frame.
/// @param _endTime The end time of the time frame.
/// @return The average balance that the user held during the time frame.
function _getAverageBalanceBetween(
ObservationLib.Observation[MAX_CARDINALITY] storage _twabs,
AccountDetails memory _accountDetails,
uint32 _startTime,
uint32 _endTime,
uint32 _currentTime
) private view returns (uint256) {
(uint24 oldestTwabIndex, ObservationLib.Observation memory oldTwab) = oldestTwab(
_twabs,
_accountDetails
);
(uint24 newestTwabIndex, ObservationLib.Observation memory newTwab) = newestTwab(
_twabs,
_accountDetails
);
ObservationLib.Observation memory startTwab = _calculateTwab(
_twabs,
_accountDetails,
newTwab,
oldTwab,
newestTwabIndex,
oldestTwabIndex,
_startTime,
_currentTime
);
ObservationLib.Observation memory endTwab = _calculateTwab(
_twabs,
_accountDetails,
newTwab,
oldTwab,
newestTwabIndex,
oldestTwabIndex,
_endTime,
_currentTime
);
// Difference in amount / time
return (endTwab.amount - startTwab.amount) / OverflowSafeComparatorLib.checkedSub(endTwab.timestamp, startTwab.timestamp, _currentTime);
}
/** @notice Searches TWAB history and calculate the difference between amount(s)/timestamp(s) to return average balance
between the Observations closes to the supplied targetTime.
* @param _twabs Individual user Observation recorded checkpoints passed as storage pointer
* @param _accountDetails User AccountDetails struct loaded in memory
* @param _targetTime Target timestamp to filter Observations in the ring buffer binary search
* @param _currentTime Block.timestamp
* @return uint256 Time-weighted average amount between two closest observations.
*/
function _getBalanceAt(
ObservationLib.Observation[MAX_CARDINALITY] storage _twabs,
AccountDetails memory _accountDetails,
uint32 _targetTime,
uint32 _currentTime
) private view returns (uint256) {
uint24 newestTwabIndex;
ObservationLib.Observation memory afterOrAt;
ObservationLib.Observation memory beforeOrAt;
(newestTwabIndex, beforeOrAt) = newestTwab(_twabs, _accountDetails);
// If `_targetTime` is chronologically after the newest TWAB, we can simply return the current balance
if (beforeOrAt.timestamp.lte(_targetTime, _currentTime)) {
return _accountDetails.balance;
}
uint24 oldestTwabIndex;
// Now, set before to the oldest TWAB
(oldestTwabIndex, beforeOrAt) = oldestTwab(_twabs, _accountDetails);
// If `_targetTime` is chronologically before the oldest TWAB, we can early return
if (_targetTime.lt(beforeOrAt.timestamp, _currentTime)) {
return 0;
}
// Otherwise, we perform the `binarySearch`
(beforeOrAt, afterOrAt) = ObservationLib.binarySearch(
_twabs,
newestTwabIndex,
oldestTwabIndex,
_targetTime,
_accountDetails.cardinality,
_currentTime
);
// Sum the difference in amounts and divide by the difference in timestamps.
// The time-weighted average balance uses time measured between two epoch timestamps as
// a constaint on the measurement when calculating the time weighted average balance.
return
(afterOrAt.amount - beforeOrAt.amount) / OverflowSafeComparatorLib.checkedSub(afterOrAt.timestamp, beforeOrAt.timestamp, _currentTime);
}
/** @notice Calculates a user TWAB for a target timestamp using the historical TWAB records.
The balance is linearly interpolated: amount differences / timestamp differences
using the simple (after.amount - before.amount / end.timestamp - start.timestamp) formula.
/** @dev Binary search in _calculateTwab fails when searching out of bounds. Thus, before
searching we exclude target timestamps out of range of newest/oldest TWAB(s).
IF a search is before or after the range we "extrapolate" a Observation from the expected state.
* @param _twabs Individual user Observation recorded checkpoints passed as storage pointer
* @param _accountDetails User AccountDetails struct loaded in memory
* @param _newestTwab Newest TWAB in history (end of ring buffer)
* @param _oldestTwab Olderst TWAB in history (end of ring buffer)
* @param _newestTwabIndex Pointer in ring buffer to newest TWAB
* @param _oldestTwabIndex Pointer in ring buffer to oldest TWAB
* @param _targetTimestamp Epoch timestamp to calculate for time (T) in the TWAB
* @param _time Block.timestamp
* @return accountDetails Updated Account.details struct
*/
function _calculateTwab(
ObservationLib.Observation[MAX_CARDINALITY] storage _twabs,
AccountDetails memory _accountDetails,
ObservationLib.Observation memory _newestTwab,
ObservationLib.Observation memory _oldestTwab,
uint24 _newestTwabIndex,
uint24 _oldestTwabIndex,
uint32 _targetTimestamp,
uint32 _time
) private view returns (ObservationLib.Observation memory) {
// If `_targetTimestamp` is chronologically after the newest TWAB, we extrapolate a new one
if (_newestTwab.timestamp.lt(_targetTimestamp, _time)) {
return _computeNextTwab(_newestTwab, _accountDetails.balance, _targetTimestamp);
}
if (_newestTwab.timestamp == _targetTimestamp) {
return _newestTwab;
}
if (_oldestTwab.timestamp == _targetTimestamp) {
return _oldestTwab;
}
// If `_targetTimestamp` is chronologically before the oldest TWAB, we create a zero twab
if (_targetTimestamp.lt(_oldestTwab.timestamp, _time)) {
return ObservationLib.Observation({ amount: 0, timestamp: _targetTimestamp });
}
// Otherwise, both timestamps must be surrounded by twabs.
(
ObservationLib.Observation memory beforeOrAtStart,
ObservationLib.Observation memory afterOrAtStart
) = ObservationLib.binarySearch(
_twabs,
_newestTwabIndex,
_oldestTwabIndex,
_targetTimestamp,
_accountDetails.cardinality,
_time
);
uint224 heldBalance = (afterOrAtStart.amount - beforeOrAtStart.amount) /
OverflowSafeComparatorLib.checkedSub(afterOrAtStart.timestamp, beforeOrAtStart.timestamp, _time);
return _computeNextTwab(beforeOrAtStart, heldBalance, _targetTimestamp);
}
/**
* @notice Calculates the next TWAB using the newestTwab and updated balance.
* @dev Storage of the TWAB obersation is managed by the calling function and not _computeNextTwab.
* @param _currentTwab Newest Observation in the Account.twabs list
* @param _currentBalance User balance at time of most recent (newest) checkpoint write
* @param _time Current block.timestamp
* @return TWAB Observation
*/
function _computeNextTwab(
ObservationLib.Observation memory _currentTwab,
uint224 _currentBalance,
uint32 _time
) private pure returns (ObservationLib.Observation memory) {
// New twab amount = last twab amount (or zero) + (current amount * elapsed seconds)
return
ObservationLib.Observation({
amount: _currentTwab.amount +
_currentBalance *
(_time.checkedSub(_currentTwab.timestamp, _time)),
timestamp: _time
});
}
/// @notice Sets a new TWAB Observation at the next available index and returns the new account details.
/// @dev Note that if _currentTime is before the last observation timestamp, it appears as an overflow
/// @param _twabs The twabs array to insert into
/// @param _accountDetails The current account details
/// @param _currentTime The current time
/// @return accountDetails The new account details
/// @return twab The newest twab (may or may not be brand-new)
/// @return isNew Whether the newest twab was created by this call
function _nextTwab(
ObservationLib.Observation[MAX_CARDINALITY] storage _twabs,
AccountDetails memory _accountDetails,
uint32 _currentTime
)
private
returns (
AccountDetails memory accountDetails,
ObservationLib.Observation memory twab,
bool isNew
)
{
(, ObservationLib.Observation memory _newestTwab) = newestTwab(_twabs, _accountDetails);
// if we're in the same block, return
if (_newestTwab.timestamp == _currentTime) {
return (_accountDetails, _newestTwab, false);
}
ObservationLib.Observation memory newTwab = _computeNextTwab(
_newestTwab,
_accountDetails.balance,
_currentTime
);
_twabs[_accountDetails.nextTwabIndex] = newTwab;
AccountDetails memory nextAccountDetails = push(_accountDetails);
return (nextAccountDetails, newTwab, true);
}
/// @notice "Pushes" a new element on the AccountDetails ring buffer, and returns the new AccountDetails
/// @param _accountDetails The account details from which to pull the cardinality and next index
/// @return The new AccountDetails
function push(AccountDetails memory _accountDetails)
internal
pure
returns (AccountDetails memory)
{
_accountDetails.nextTwabIndex = uint24(
RingBufferLib.nextIndex(_accountDetails.nextTwabIndex, MAX_CARDINALITY)
);
// Prevent the Account specific cardinality from exceeding the MAX_CARDINALITY.
// The ring buffer length is limited by MAX_CARDINALITY. IF the account.cardinality
// exceeds the max cardinality, new observations would be incorrectly set or the
// observation would be out of "bounds" of the ring buffer. Once reached the
// AccountDetails.cardinality will continue to be equal to max cardinality.
if (_accountDetails.cardinality < MAX_CARDINALITY) {
_accountDetails.cardinality += 1;
}
return _accountDetails;
}
} | @inheritdoc IPrizeDistributor | function setDrawCalculator(IDrawCalculator _newCalculator)
external
override
onlyOwner
returns (IDrawCalculator)
{
_setDrawCalculator(_newCalculator);
return _newCalculator;
}
| 623,660 |
./full_match/1/0x83599dDCcC1458a7c475d13Ed363D0E40cC4044E/sources/lib/pizza/src/Rescuable.sol | Rescue ERC20 tokens locked up in this contract. tokenContract ERC20 token contract address to Recipient address amount Amount to withdraw/ | function rescueERC20(
address tokenContract,
address to,
uint256 amount
) external onlyRescuer {
IERC20(tokenContract).transfer(to, amount);
}
| 3,042,189 |
./full_match/1/0x895dd62Fbd30e4e42df2d1108ee998f697deCADc/sources/contracts/ETH/PresaleV5.sol | To set payment wallet address _newPaymentWallet new payment wallet address/ | function changePaymentWallet(address _newPaymentWallet) external onlyOwner {
require(_newPaymentWallet != address(0), 'address cannot be zero');
paymentWallet = _newPaymentWallet;
}
| 3,130,717 |
pragma solidity ^0.5.16;
// this contract serves as feeToSetter, allowing owner to manage fees in the context of a specific feeTo implementation
contract SDFeeToSetter {
// immutables
address public factory;
uint public vestingEnd;
address public feeTo;
address public owner;
constructor(address factory_, uint vestingEnd_, address owner_, address feeTo_) public {
require(vestingEnd_ > block.timestamp, 'SDFeeToSetter::constructor: vesting must end after deployment');
factory = factory_;
vestingEnd = vestingEnd_;
owner = owner_;
feeTo = feeTo_;
}
// allows owner to change itself at any time
function setOwner(address owner_) public {
require(msg.sender == owner, 'SDFeeToSetter::setOwner: not allowed');
owner = owner_;
}
// allows owner to change feeToSetter after vesting
function setFeeToSetter(address feeToSetter_) public {
require(block.timestamp >= vestingEnd, 'SDFeeToSetter::setFeeToSetter: not time yet');
require(msg.sender == owner, 'SDFeeToSetter::setFeeToSetter: not allowed');
ISDswapV2Factory(factory).setFeeToSetter(feeToSetter_);
}
// allows owner to turn fees on/off after vesting
function toggleFees(bool on) public {
require(block.timestamp >= vestingEnd, 'SDFeeToSetter::toggleFees: not time yet');
require(msg.sender == owner, 'SDFeeToSetter::toggleFees: not allowed');
ISDswapV2Factory(factory).setFeeTo(on ? feeTo : address(0));
}
}
interface ISDswapV2Factory {
function setFeeToSetter(address) external;
function setFeeTo(address) external;
}
| allows owner to change itself at any time | function setOwner(address owner_) public {
require(msg.sender == owner, 'SDFeeToSetter::setOwner: not allowed');
owner = owner_;
}
| 12,718,484 |
./full_match/83/0x755841432F9AE4Cf5d523A970da819B8A0da993d/sources/contracts/Comptroller/UnderWriterAdmin.sol | Set the given borrow caps for the given cToken markets. Borrowing that brings total borrows to or above borrow cap will revert. Admin or borrowCapGuardian function to set the borrow caps. A borrow cap of 0 corresponds to unlimited borrowing. cTokens The addresses of the markets (tokens) to change the borrow caps for newBorrowCaps The new borrow cap values in underlying to be set. A value of 0 corresponds to unlimited borrowing./ | function _setMarketBorrowCaps(ICToken[] calldata cTokens, uint256[] calldata newBorrowCaps) external {
require(
msg.sender == admin || msg.sender == borrowCapGuardian,
'only admin or borrow cap guardian can set borrow caps'
);
uint256 numMarkets = cTokens.length;
uint256 numBorrowCaps = newBorrowCaps.length;
require(numMarkets != 0 && numMarkets == numBorrowCaps, 'invalid input');
for (uint256 i = 0; i < numMarkets; i++) {
borrowCaps[address(cTokens[i])] = newBorrowCaps[i];
emit NewBorrowCap(address(cTokens[i]), newBorrowCaps[i]);
}
}
| 9,559,089 |
// SPDX-License-Identifier: MIT
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
import "@keep-network/yearn-vaults/contracts/BaseStrategy.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/math/Math.sol";
/// @notice Interface for the CurveFi pool.
/// @dev This is an interface with just a few function signatures of the pool.
/// For more info and function description please see:
/// https://github.com/curvefi/curve-contract/tree/master/contracts/pool-templates
interface ICurvePool {
function add_liquidity(uint256[4] calldata amounts, uint256 min_mint_amount)
external
payable;
function calc_token_amount(uint256[4] calldata amounts, bool deposit)
external
view
returns (uint256);
}
/// @notice Interface for the proxy contract which allows strategies to
/// make calls to the Curve DAO through the common CurveYCRVVoter.
/// @dev This is an interface with just a few function signatures of the proxy.
/// For more info and function description please see:
/// - https://github.com/yearn/yearn-protocol/blob/develop/contracts/strategies/StrategyProxy.sol
/// - https://docs.yearn.finance/resources/guides/how-to-understand-crv-vote-locking
interface IStrategyProxy {
function balanceOf(address gauge) external view returns (uint256);
function deposit(address gauge, address token) external;
function withdraw(
address gauge,
address token,
uint256 amount
) external returns (uint256);
function withdrawAll(address gauge, address token)
external
returns (uint256);
function harvest(address gauge) external;
function claimRewards(address gauge, address token) external;
function approveStrategy(address gauge, address strategy) external;
}
/// @notice Interface for the Uniswap v2 router.
/// @dev This is an interface with just a few function signatures of the
/// router contract. For more info and function description please see:
/// https://uniswap.org/docs/v2/smart-contracts/router02
/// This interface allows to interact with Sushiswap as well.
interface IUniswapV2Router {
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external;
function getAmountsOut(uint256 amountIn, address[] memory path)
external
view
returns (uint256[] memory amounts);
}
/// @notice Interface for the optional metadata functions from the ERC20 standard.
interface IERC20Metadata {
function symbol() external view returns (string memory);
}
/// @title CurveVoterProxyStrategy
/// @notice This strategy is meant to be used with the Curve tBTC v2 pool vault.
/// The vault's underlying token (a.k.a. want token) should be the LP
/// token of the Curve tBTC v2 pool. This strategy borrows the vault's
/// underlying token up to the debt limit configured for this strategy
/// in the vault. In order to make the profit, the strategy deposits
/// the borrowed tokens into the gauge contract of the Curve tBTC v2 pool.
/// Depositing tokens in the gauge generates regular CRV rewards and
/// can provide additional rewards (denominated in another token)
/// if the gauge stakes its deposits into the Synthetix staking
/// rewards contract. The financial outcome is settled upon a call
/// of the `harvest` method (BaseStrategy.sol). Once that call is made,
/// the strategy harvests the CRV rewards from the pool's gauge. Then,
/// it takes a small portion (defined by keepCRV param) and locks it
/// into the Curve vote escrow (via CurveYCRVVoter contract) to gain CRV
/// boost and increase future gains. The rest of CRV tokens is used to
/// buy wBTC via a decentralized exchange. If the pool's gauge supports
/// additional rewards from Synthetix staking, the strategy claims
/// that reward too and uses obtained reward tokens to buy more wBTC.
/// At the end, the strategy takes acquired wBTC and deposits them
/// to the Curve tBTC v2 pool. This way it obtains new LP tokens
/// the vault is interested for, and makes the profit in result.
/// At this stage, the strategy may repay some debt back to the vault,
/// if needed. The entire cycle repeats for the strategy lifetime so
/// all gains are constantly reinvested. Worth to flag that current
/// implementation uses wBTC as the intermediary token because
/// of its liquidity and ubiquity in BTC-based Curve pools.
/// @dev Implementation is based on:
/// - General Yearn strategy template
/// https://github.com/yearn/brownie-strategy-mix
/// - Curve voter proxy strategy template
/// https://github.com/orbxball/curve-voter-proxy
/// - Curve voter proxy implementation for tBTC v1 vault
/// https://github.com/orbxball/btc-curve-voter-proxy
contract CurveVoterProxyStrategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
/// @notice Governance delay that needs to pass before any parameter change
/// initiated by the governance takes effect.
uint256 public constant GOVERNANCE_DELAY = 48 hours;
uint256 public constant DENOMINATOR = 10000;
// Address of the CurveYCRVVoter contract.
address public constant voter =
address(0xF147b8125d2ef93FB6965Db97D6746952a133934);
// Address of the StrategyProxy contract.
address public strategyProxy =
address(0xA420A63BbEFfbda3B147d0585F1852C358e2C152);
address public newStrategyProxy;
uint256 public strategyProxyChangeInitiated;
// Address of the CRV token contract.
address public constant crvToken =
address(0xD533a949740bb3306d119CC777fa900bA034cd52);
// Address of the WETH token contract.
address public constant wethToken =
address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2);
// Address of the WBTC token contract.
address public constant wbtcToken =
address(0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599);
// Address of the Uniswap V2 router contract.
address public constant uniswap =
address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Address of the depositor contract for the tBTC v2 Curve pool.
address public immutable tbtcCurvePoolDepositor;
// Address of the gauge contract for the tBTC v2 Curve pool.
address public immutable tbtcCurvePoolGauge;
// Address of the additional reward token distributed by the gauge contract
// of the tBTC v2 Curve pool. This is applicable only in case when the gauge
// stakes LP tokens into the Synthetix staking rewards contract
// (i.e. the gauge is an instance of LiquidityGaugeReward contract).
// Can be unset if additional rewards are not supported by the gauge.
address public immutable tbtcCurvePoolGaugeReward;
// Address of the DEX used to swap reward tokens back to the vault's
// underlying token. This can be Uniswap or other Uni-like DEX.
address public immutable dex;
// Determines the portion of CRV tokens which should be locked in the
// Curve vote escrow to gain a CRV boost. This is the counter of a fraction
// denominated by the DENOMINATOR constant. For example, if the value
// is `1000`, that means 10% of tokens will be locked because
// 1000/10000 = 0.1
uint256 public keepCRV;
uint256 public newKeepCRV;
uint256 public keepCRVChangeInitiated;
// Determines the slippage tolerance for price-sensitive transactions.
// If transaction's slippage is higher, transaction will be reverted.
// Default value is 100 basis points (1%).
uint256 public slippageTolerance = 100;
uint256 public newSlippageTolerance;
uint256 public slippageToleranceChangeInitiated;
event KeepCRVUpdateStarted(uint256 keepCRV, uint256 timestamp);
event KeepCRVUpdated(uint256 keepCRV);
event StrategyProxyUpdateStarted(
address indexed strategyProxy,
uint256 timestamp
);
event StrategyProxyUpdated(address indexed strategyProxy);
event SlippageToleranceUpdateStarted(
uint256 slippageTolerance,
uint256 timestamp
);
event SlippageToleranceUpdated(uint256 slippageTolerance);
/// @notice Reverts if called before the governance delay elapses.
/// @param changeInitiatedTimestamp Timestamp indicating the beginning
/// of the change.
modifier onlyAfterGovernanceDelay(uint256 changeInitiatedTimestamp) {
require(changeInitiatedTimestamp > 0, "Change not initiated");
require(
/* solhint-disable-next-line not-rely-on-time */
block.timestamp - changeInitiatedTimestamp >= GOVERNANCE_DELAY,
"Governance delay has not elapsed"
);
_;
}
constructor(
address _vault,
address _tbtcCurvePoolDepositor,
address _tbtcCurvePoolGauge,
address _tbtcCurvePoolGaugeReward // optional, zero is valid value
) public BaseStrategy(_vault) {
// Strategy settings.
minReportDelay = 6 hours;
maxReportDelay = 2 days;
profitFactor = 1;
debtThreshold = 1e24;
dex = uniswap;
keepCRV = 1000;
// tBTC-related settings.
tbtcCurvePoolDepositor = _tbtcCurvePoolDepositor;
tbtcCurvePoolGauge = _tbtcCurvePoolGauge;
tbtcCurvePoolGaugeReward = _tbtcCurvePoolGaugeReward;
}
/// @notice Begins the update of the strategy proxy contract address.
/// @dev Can be called only by the governance.
/// @param _newStrategyProxy Address of the new proxy.
function beginStrategyProxyUpdate(address _newStrategyProxy)
external
onlyGovernance
{
require(_newStrategyProxy != address(0), "Invalid address");
newStrategyProxy = _newStrategyProxy;
strategyProxyChangeInitiated = block.timestamp;
emit StrategyProxyUpdateStarted(_newStrategyProxy, block.timestamp);
}
/// @notice Finalizes the update of the strategy proxy contract address.
/// @dev Can be called only by the governance, after the governance
/// delay elapses.
function finalizeStrategyProxyUpdate()
external
onlyGovernance
onlyAfterGovernanceDelay(strategyProxyChangeInitiated)
{
strategyProxy = newStrategyProxy;
emit StrategyProxyUpdated(newStrategyProxy);
strategyProxyChangeInitiated = 0;
newStrategyProxy = address(0);
}
/// @notice Begins the update of the threshold determining the portion of
/// CRV tokens which should be locked in the Curve vote escrow to
/// gain CRV boost.
/// @dev Can be called only by the strategist and governance.
/// @param _newKeepCRV Portion as counter of a fraction denominated by the
/// DENOMINATOR constant.
function beginKeepCRVUpdate(uint256 _newKeepCRV) external onlyAuthorized {
require(_newKeepCRV <= DENOMINATOR, "Max value is 10000");
newKeepCRV = _newKeepCRV;
keepCRVChangeInitiated = block.timestamp;
emit KeepCRVUpdateStarted(_newKeepCRV, block.timestamp);
}
/// @notice Finalizes the keep CRV threshold update process.
/// @dev Can be called only by the strategist and governance, after the
/// governance delay elapses.
function finalizeKeepCRVUpdate()
external
onlyAuthorized
onlyAfterGovernanceDelay(keepCRVChangeInitiated)
{
keepCRV = newKeepCRV;
emit KeepCRVUpdated(newKeepCRV);
keepCRVChangeInitiated = 0;
newKeepCRV = 0;
}
/// @notice Begins the update of the slippage tolerance parameter.
/// @dev Can be called only by the strategist and governance.
/// @param _newSlippageTolerance Slippage tolerance as counter of a fraction
/// denominated by the DENOMINATOR constant.
function beginSlippageToleranceUpdate(uint256 _newSlippageTolerance)
external
onlyAuthorized
{
require(_newSlippageTolerance <= DENOMINATOR, "Max value is 10000");
newSlippageTolerance = _newSlippageTolerance;
slippageToleranceChangeInitiated = block.timestamp;
emit SlippageToleranceUpdateStarted(
_newSlippageTolerance,
block.timestamp
);
}
/// @notice Finalizes the update of the slippage tolerance parameter.
/// @dev Can be called only by the strategist and governance, after the the
/// governance delay elapses.
function finalizeSlippageToleranceUpdate()
external
onlyAuthorized
onlyAfterGovernanceDelay(slippageToleranceChangeInitiated)
{
slippageTolerance = newSlippageTolerance;
emit SlippageToleranceUpdated(newSlippageTolerance);
slippageToleranceChangeInitiated = 0;
newSlippageTolerance = 0;
}
/// @return Name of the Yearn vault strategy.
function name() external view override returns (string memory) {
return
string(
abi.encodePacked(
"Curve",
IERC20Metadata(address(want)).symbol(),
"VoterProxy"
)
);
}
/// @return Balance of the vault's underlying token under management.
function balanceOfWant() public view returns (uint256) {
return want.balanceOf(address(this));
}
/// @return Balance of the vault's underlying token deposited into the Curve
/// pool's gauge.
function balanceOfPool() public view returns (uint256) {
return IStrategyProxy(strategyProxy).balanceOf(tbtcCurvePoolGauge);
}
/// @return Sum of balanceOfWant and balanceOfPool.
function estimatedTotalAssets() public view override returns (uint256) {
return balanceOfWant().add(balanceOfPool());
}
/// @notice This method is defined in the BaseStrategy contract and is
/// meant to 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. All free capital in the
/// strategy after the report was made is available for reinvestment.
/// This strategy implements the aforementioned behavior by taking
/// its balance of the vault's underlying token and depositing it to
/// the Curve pool's gauge via the strategy proxy contract.
/// @param debtOutstanding Will be 0 if the strategy is not past the
/// configured debt limit, otherwise its value will be how far past
/// the debt limit the strategy is. The strategy's debt limit is
/// configured in the vault.
function adjustPosition(uint256 debtOutstanding) internal override {
uint256 wantBalance = want.balanceOf(address(this));
if (wantBalance > 0) {
want.safeTransfer(strategyProxy, wantBalance);
IStrategyProxy(strategyProxy).deposit(
tbtcCurvePoolGauge,
address(want)
);
}
}
/// @notice Withdraws a portion of the vault's underlying token from
/// the Curve pool's gauge.
/// @param amount Amount to withdraw.
/// @return Amount withdrawn.
function withdrawSome(uint256 amount) internal returns (uint256) {
amount = Math.min(amount, balanceOfPool());
return
IStrategyProxy(strategyProxy).withdraw(
tbtcCurvePoolGauge,
address(want),
amount
);
}
/// @notice This method is defined in the BaseStrategy contract and is meant
/// to liquidate up to amountNeeded of want token of this strategy's
/// positions, irregardless of slippage. Any excess will be
/// re-invested with adjustPosition. This function should return
/// the amount of want tokens made available by the liquidation.
/// If there is a difference between them, loss indicates whether
/// the difference is due to a realized loss, or if there is some
/// other situation at play (e.g. locked funds). This strategy
/// implements the aforementioned behavior by withdrawing a portion
/// of the vault's underlying token (want token) from the Curve
/// pool's gauge.
/// @dev The invariant `liquidatedAmount + loss <= amountNeeded` should
/// always be maintained.
/// @param amountNeeded Amount of the vault's underlying tokens needed by
/// the liquidation process.
/// @return liquidatedAmount Amount of vault's underlying tokens made
/// available by the liquidation.
/// @return loss Amount of the loss.
function liquidatePosition(uint256 amountNeeded)
internal
override
returns (uint256 liquidatedAmount, uint256 loss)
{
uint256 wantBalance = want.balanceOf(address(this));
if (wantBalance < amountNeeded) {
liquidatedAmount = withdrawSome(amountNeeded.sub(wantBalance));
liquidatedAmount = liquidatedAmount.add(wantBalance);
loss = amountNeeded.sub(liquidatedAmount);
} else {
liquidatedAmount = amountNeeded;
}
}
/// @notice This method is defined in the BaseStrategy contract and is meant
/// to liquidate everything and return the amount that got freed.
/// This strategy implements the aforementioned behavior by withdrawing
/// all vault's underlying tokens from the Curve pool's gauge.
/// @dev This function is used during emergency exit instead of prepareReturn
/// to liquidate all of the strategy's positions back to the vault.
/// @return Total balance of want tokens held by this strategy.
function liquidateAllPositions() internal override returns (uint256) {
IStrategyProxy(strategyProxy).withdrawAll(
tbtcCurvePoolGauge,
address(want)
);
// Yearn docs doesn't specify clear enough what exactly should be
// returned here. It may be either the total balance after withdrawAll
// or just the amount withdrawn. Currently opting for the former
// because of https://github.com/yearn/yearn-vaults/pull/311#discussion_r625588313.
// Also, usage of this result in the harvest method in the BaseStrategy
// seems to confirm that.
return want.balanceOf(address(this));
}
/// @notice This method is defined in the BaseStrategy contract and is meant
/// to do anything necessary to prepare this strategy for migration,
/// such as transferring any reserve or LP tokens, CDPs, or other
/// tokens or stores of value. This strategy implements the
/// aforementioned behavior by withdrawing all vault's underlying
/// tokens from the Curve pool's gauge.
/// @param newStrategy Address of the new strategy meant to replace the
/// current one.
function prepareMigration(address newStrategy) internal override {
// Just withdraw the vault's underlying token from the Curve pool's gauge.
// There is no need to transfer those tokens to the new strategy
// right here as this is done in the BaseStrategy's migrate() method.
IStrategyProxy(strategyProxy).withdrawAll(
tbtcCurvePoolGauge,
address(want)
);
// Harvest the CRV rewards from the Curve pool's gauge and transfer
// them to the new strategy
IStrategyProxy(strategyProxy).harvest(tbtcCurvePoolGauge);
IERC20(crvToken).safeTransfer(
newStrategy,
IERC20(crvToken).balanceOf(address(this))
);
// Claim additional reward tokens from the gauge if applicable and
// transfer them to the new strategy
if (tbtcCurvePoolGaugeReward != address(0)) {
IStrategyProxy(strategyProxy).claimRewards(
tbtcCurvePoolGauge,
tbtcCurvePoolGaugeReward
);
IERC20(tbtcCurvePoolGaugeReward).safeTransfer(
newStrategy,
IERC20(tbtcCurvePoolGaugeReward).balanceOf(address(this))
);
}
}
/// @notice Takes the keepCRV portion of the CRV balance and transfers
/// it to the CurveYCRVVoter contract in order to gain CRV boost.
/// @param crvBalance Balance of CRV tokens under management.
/// @return Amount of CRV tokens remaining under management after the
/// transfer.
function adjustCRV(uint256 crvBalance) internal returns (uint256) {
uint256 crvTransfer = crvBalance.mul(keepCRV).div(DENOMINATOR);
IERC20(crvToken).safeTransfer(voter, crvTransfer);
return crvBalance.sub(crvTransfer);
}
/// @notice This method is defined in the BaseStrategy contract and is meant
/// to perform any strategy unwinding or other calls necessary to
/// capture the free return this strategy has generated since the
/// last time its core position(s) were adjusted. Examples include
/// unwrapping extra rewards. This call is only used during normal
/// operation of a strategy, and should be optimized to minimize
/// losses as much as possible. This strategy implements the
/// aforementioned behavior by harvesting the Curve pool's gauge
/// CRV rewards, using most of the CRV tokens to buy one of the
/// Curve pool's accepted token, and depositing that token back to
/// the Curve pool. This way the strategy is gaining new vault's
/// underlying tokens thus making the profit. A small portion of
/// CRV rewards (defined by keepCRV param) is transferred to the
/// voter contract to increase CRV boost and get more CRV rewards
/// in the future. Apart from that, this strategy also sells
/// the Curve pool's gauge additional rewards, generated using the
/// Synthetix staking rewards contract.
/// @param debtOutstanding Will be 0 if the strategy is not past the
/// configured debt limit, otherwise its value will be how far past
/// the debt limit the strategy is. The strategy's debt limit is
/// configured in the vault.
/// @return profit Amount of realized profit.
/// @return loss Amount of realized loss.
/// @return debtPayment Amount of repaid debt. The value of debtPayment
/// should be less than or equal to debtOutstanding. It is okay for
/// it to be less than debtOutstanding, as that should only used as
/// a guide for how much is left to pay back. Payments should be
/// made to minimize loss from slippage, debt, withdrawal fees, etc.
function prepareReturn(uint256 debtOutstanding)
internal
override
returns (
uint256 profit,
uint256 loss,
uint256 debtPayment
)
{
// Get the initial balance of the vault's underlying token under
// strategy management.
uint256 initialWantBalance = want.balanceOf(address(this));
// Harvest the CRV rewards from the Curve pool's gauge.
IStrategyProxy(strategyProxy).harvest(tbtcCurvePoolGauge);
// Buy WBTC using harvested CRV tokens.
uint256 crvBalance = IERC20(crvToken).balanceOf(address(this));
if (crvBalance > 0) {
// Deposit a portion of CRV to the voter to gain CRV boost.
crvBalance = adjustCRV(crvBalance);
IERC20(crvToken).safeIncreaseAllowance(dex, crvBalance);
address[] memory path = new address[](3);
path[0] = crvToken;
path[1] = wethToken;
path[2] = wbtcToken;
IUniswapV2Router(dex).swapExactTokensForTokens(
crvBalance,
minSwapOutAmount(crvBalance, path),
path,
address(this),
now
);
}
// Claim additional reward tokens from the gauge if applicable.
if (tbtcCurvePoolGaugeReward != address(0)) {
IStrategyProxy(strategyProxy).claimRewards(
tbtcCurvePoolGauge,
tbtcCurvePoolGaugeReward
);
uint256 rewardBalance = IERC20(tbtcCurvePoolGaugeReward).balanceOf(
address(this)
);
if (rewardBalance > 0) {
IERC20(tbtcCurvePoolGaugeReward).safeIncreaseAllowance(
dex,
rewardBalance
);
address[] memory path = new address[](3);
path[0] = tbtcCurvePoolGaugeReward;
path[1] = wethToken;
path[2] = wbtcToken;
IUniswapV2Router(dex).swapExactTokensForTokens(
rewardBalance,
minSwapOutAmount(rewardBalance, path),
path,
address(this),
now
);
}
}
// Deposit acquired WBTC to the Curve pool to gain additional
// vault's underlying tokens.
uint256 wbtcBalance = IERC20(wbtcToken).balanceOf(address(this));
if (wbtcBalance > 0) {
IERC20(wbtcToken).safeIncreaseAllowance(
tbtcCurvePoolDepositor,
wbtcBalance
);
// TODO: When the new curve pool with tBTC v2 is deployed, verify
// that the index of wBTC in the array is correct.
uint256[4] memory amounts = [0, 0, wbtcBalance, 0];
ICurvePool(tbtcCurvePoolDepositor).add_liquidity(
amounts,
minLiquidityDepositOutAmount(amounts)
);
}
// Check the profit and loss in the context of strategy debt.
uint256 totalAssets = estimatedTotalAssets();
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
if (totalAssets < totalDebt) {
loss = totalDebt - totalAssets;
profit = 0;
} else {
profit = want.balanceOf(address(this)).sub(initialWantBalance);
}
// Repay some vault debt if needed.
if (debtOutstanding > 0) {
withdrawSome(debtOutstanding);
debtPayment = Math.min(
debtOutstanding,
balanceOfWant().sub(profit)
);
}
}
/// @notice Calculates the minimum amount of output tokens that must be
/// received for the swap transaction not to revert.
/// @param amountIn The amount of input tokens to send.
/// @param path An array of token addresses determining the swap route.
/// @return The minimum amount of output tokens that must be received for
/// the swap transaction not to revert.
function minSwapOutAmount(uint256 amountIn, address[] memory path)
internal
view
returns (uint256)
{
// Get the maximum possible amount of the output token based on
// pair reserves.
uint256 amount = IUniswapV2Router(dex).getAmountsOut(amountIn, path)[
path.length - 1
];
// Include slippage tolerance into the maximum amount of output tokens
// in order to obtain the minimum amount desired.
return (amount * (DENOMINATOR - slippageTolerance)) / DENOMINATOR;
}
/// @notice Calculates the minimum amount of LP tokens that must be
/// received for the liquidity deposit transaction not to revert.
/// @param amountsIn Amounts of each underlying coin being deposited.
/// @return The minimum amount of LP tokens that must be received for
/// the liquidity deposit transaction not to revert.
function minLiquidityDepositOutAmount(uint256[4] memory amountsIn)
internal
view
returns (uint256)
{
// Get the maximum possible amount of LP tokens received in return
// for liquidity deposit based on pool reserves.
uint256 amount = ICurvePool(tbtcCurvePoolDepositor).calc_token_amount(
amountsIn,
true
);
// Include slippage tolerance into the maximum amount of LP tokens
// in order to obtain the minimum amount desired.
return (amount * (DENOMINATOR - slippageTolerance)) / DENOMINATOR;
}
/// @notice This method is defined in the BaseStrategy contract and is meant
/// to define all tokens/tokenized positions this contract manages
/// on a persistent basis (e.g. not just for swapping back to
/// the want token ephemerally).
/// @dev Should not include want token, already included in the base contract.
/// @return Addresses of protected tokens
function protectedTokens()
internal
view
override
returns (address[] memory)
{
if (tbtcCurvePoolGaugeReward != address(0)) {
address[] memory protected = new address[](2);
protected[0] = crvToken;
protected[1] = tbtcCurvePoolGaugeReward;
return protected;
}
address[] memory protected = new address[](1);
protected[0] = crvToken;
return protected;
}
/// @notice This method is defined in the BaseStrategy contract and is meant
/// to provide an accurate conversion from amtInWei (denominated in wei)
/// to want token (using the native decimal characteristics of want token).
/// @param amtInWei The amount (in wei/1e-18 ETH) to convert to want tokens.
/// @return The amount in want tokens.
function ethToWant(uint256 amtInWei)
public
view
virtual
override
returns (uint256)
{
address[] memory path = new address[](2);
path[0] = wethToken;
path[1] = wbtcToken;
// As of writing this contract, there's no pool available that trades
// an underlying token with ETH. To overcome this, the ETH amount
// denominated in WEI should be converted into an amount denominated
// in one of the tokens accepted by the tBTC v2 Curve pool using Uniswap.
// The wBTC token was chosen arbitrarily since it is already used in this
// contract for other operations on Uniswap.
// amounts[0] -> ETH in wei
// amounts[1] -> wBTC
uint256[] memory amounts = IUniswapV2Router(dex).getAmountsOut(
amtInWei,
path
);
// Use the amount denominated in wBTC to calculate the amount of LP token
// (vault's underlying token) that could be obtained if that wBTC amount
// was deposited in the Curve pool that has tBTC v2 in it. This way we
// obtain an estimated value of the original WEI amount represented in
// the vault's underlying token.
//
// TODO: When the new curve pool with tBTC v2 is deployed, verify that
// the index of wBTC (amounts[1]) in the array is correct.
return
ICurvePool(tbtcCurvePoolDepositor).calc_token_amount(
[0, 0, amounts[1], 0],
true
);
}
}
| Withdraws a portion of the vault's underlying token from the Curve pool's gauge. amount Amount to withdraw. return Amount withdrawn. | function withdrawSome(uint256 amount) internal returns (uint256) {
amount = Math.min(amount, balanceOfPool());
return
IStrategyProxy(strategyProxy).withdraw(
tbtcCurvePoolGauge,
address(want),
amount
);
}
| 5,465,187 |
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.6;
import "remix_tests.sol"; // this import is automatically injected by Remix.
import "remix_accounts.sol";
import "../contracts/STAKEManager.sol";
// File name has to end with '_test.sol', this file can contain more than one testSuite contracts
contract testSTAKEmanager is STAKEManager {
STAKEManager internal stm;
constructor()
STAKEManager("TEST","TEST")
public{
}
/// 'beforeAll' runs before all other tests
/// More special functions are: 'beforeEach', 'beforeAll', 'afterEach' & 'afterAll'
function beforeAll() public {
// Here should instantiate tested contract
newInOwners(address(this));
stm=STAKEManager(address(this));
}
function testNewStake() public {
address acc=TestsAccounts.getAccount(1);
uint256 li=newStake(acc, 10**18,10**16,10**15,true);
Assert.equal(li,1,"FAIL to create newStake");
Assert.equal(getStakeCount(),1,"FAIL to create newStake");
}
function testAddStake() public {
address acc=TestsAccounts.getAccount(1);
addToStake(acc,10**18 );
address accr;uint256 bal;uint256 bnb;uint256 woop;bool autoc;
( accr, bal, bnb,woop,autoc)= getStake(acc);
Assert.equal(bal,10**18*2,"FAIL to create addToStake");
}
function testManageStake() public {
address acc=TestsAccounts.getAccount(1);
Assert.ok(manageStake(TestsAccounts.getAccount(2), 10**18),"FAIL manageStake new");
Assert.equal(getStakeCount(),2,"FAIL to create newStake new");
Assert.ok(manageStake(acc, 10**18),"FAIL manageStake add");
address accr;uint256 bal;uint256 bnb;uint256 woop;bool autoc;
( accr, bal, bnb,woop,autoc)= getStake(acc);
Assert.equal(bal,10**18*3,"FAIL to addToStake add");
}
function testSetAutocompoundStake() public {
address acc=TestsAccounts.getAccount(1);
setAutoCompound(acc, false);
bool autoc=getAutoCompoundStatus(acc);
Assert.ok(!autoc,"FAIL set autocompound");
}
function testChangeTokenBNB() public {
Assert.ok(changeToken(TestsAccounts.getAccount(1),10**15,1,true),"FAIL set changeToken bnb 1");
bool exist;uint256 bnb;uint256 woop;bool autoc;
( exist, bnb,woop,autoc)= getValues(TestsAccounts.getAccount(1));
Assert.equal(bnb,10**15,"FAIL to changeToken bnb 1 ");
Assert.ok(changeToken(TestsAccounts.getAccount(1),10**15,2,true),"FAIL set changeToken bnb 2");
( exist, bnb,woop,autoc)= getValues(TestsAccounts.getAccount(1));
Assert.equal(bnb,10**15*2,"FAIL to changeToken bnb 2 ");
Assert.ok(changeToken(TestsAccounts.getAccount(1),10**15,3,true),"FAIL set changeToken bnb 3");
( exist, bnb,woop,autoc)= getValues(TestsAccounts.getAccount(1));
Assert.equal(bnb,10**15,"FAIL to changeToken bnb 3 ");
}
function testChangeTokenWOOP() public {
Assert.ok(changeToken(TestsAccounts.getAccount(1),10**14,1,false),"FAIL set changeToken WOOP 1");
bool exist;uint256 bnb;uint256 woop;bool autoc;
( exist, bnb,woop,autoc)= getValues(TestsAccounts.getAccount(1));
Assert.equal(woop,10**14,"FAIL to changeToken WOOP 1 ");
Assert.ok(changeToken(TestsAccounts.getAccount(1),10**14,2,false),"FAIL set changeToken WOOP 2");
( exist, bnb,woop,autoc)= getValues(TestsAccounts.getAccount(1));
Assert.equal(woop,10**14*2,"FAIL to changeToken WOOP 2 ");
Assert.ok(changeToken(TestsAccounts.getAccount(1),10**14,3,false),"FAIL set changeToken WOOP 3");
( exist, bnb,woop,autoc)= getValues(TestsAccounts.getAccount(1));
Assert.equal(woop,10**14,"FAIL to changeToken WOOP 3 ");
}
function testRemoveStake() public {
removeStake(TestsAccounts.getAccount(2));
Assert.equal(getStakeCount(),1,"FAIL removeStake");
}
function testSubstractFromStake() public {
stm.substractFromStake(TestsAccounts.getAccount(1), 1);
address accr;uint256 bal;uint256 bnb;uint256 woop;bool autoc;
( accr, bal, bnb,woop,autoc)= getStake(TestsAccounts.getAccount(1));
Assert.equal(bal,(10**18*3)-1,"FAIL substractFromStake");
}
function testRenewStake() public {
stm.renewStake(TestsAccounts.getAccount(1), 10**18);
address accr;uint256 bal;uint256 bnb;uint256 woop;bool autoc;
( accr, bal, bnb,woop,autoc)= getStake(TestsAccounts.getAccount(1));
Assert.equal(bal,10**18,"FAIL renewStake");
}
function testTransferStake() public{
Assert.ok(stm.transferStake(TestsAccounts.getAccount(1), TestsAccounts.getAccount(3)),"FAIL transferStake");
Assert.ok(!StakeExist(TestsAccounts.getAccount(1)),"FAIL transferStake acc 1 exist");
Assert.ok(StakeExist(TestsAccounts.getAccount(3)),"FAIL transferStake acc 3 NOT exist");
}
function testAddMultiplesStakes() public {
address[] memory accounts=new address[](3);
uint256[] memory amounts=new uint256[](3);
uint256[] memory bnbs=new uint256[](3);
uint256[] memory woops=new uint256[](3);
bool[] memory autocs=new bool[](3);
accounts[0]=0xAf8C924B61924F64537338F7348000a3223F9C83;amounts[0]=10**18;bnbs[0]=10**14;woops[0]=10**10;autocs[0]=true;
accounts[1]=0x5d8154f12f5F3cC703FFeE17043DCF701E4a74C3;amounts[1]=10**17;bnbs[1]=0;woops[1]=10**10;autocs[1]=false;
accounts[2]=0xAf8C924B61924F64537338F7348000a3223F9C83;amounts[2]=10**17;bnbs[2]=10**14;woops[2]=0;autocs[2]=true;
Assert.ok( newStake( accounts, amounts,bnbs, woops, autocs),"FAIL Multiple newStake " );
address accr;uint256 bal;uint256 bnb;uint256 woop;bool autoc;
( accr, bal, bnb,woop,autoc)= getStake(0x5d8154f12f5F3cC703FFeE17043DCF701E4a74C3);
Assert.equal(accr,0x5d8154f12f5F3cC703FFeE17043DCF701E4a74C3,"FAIL Multiple newStake acc");
Assert.equal(bal,10**17,"FAIL Multiple newStake amount");
Assert.equal(bnb,0,"FAIL Multiple newStake bnb");
Assert.equal(woop,10**10,"FAIL Multiple newStake woop");
Assert.equal(autoc,false,"FAIL Multiple newStake autoc");
}
function testRemoveAllStake() public{
Assert.ok(stm.removeAllStake(),"FAIL removeAllStake");
Assert.equal(getStakeCount(),0,"FAIL removeAllStake");
}
}
| 'beforeAll' runs before all other tests More special functions are: 'beforeEach', 'beforeAll', 'afterEach' & 'afterAll' Here should instantiate tested contract | function beforeAll() public {
newInOwners(address(this));
stm=STAKEManager(address(this));
}
| 12,940,678 |
./full_match/80001/0x1fd90e5557cD183f835F06d8744b49DddDf7a43a/sources/contracts/Participate.sol | Get royalty recipient | function getFeeRecipients(uint256)
external
view
returns (address payable[] memory recipients)
{
if (_royaltyRecipient != address(0x0)) {
recipients = new address payable[](1);
recipients[0] = _royaltyRecipient;
}
return recipients;
}
| 9,490,306 |
//Address: 0x320274f5dd332cc3b617b360e8554d95a0b96978
//Contract name: ZillaCrowdsale
//Balance: 0 Ether
//Verification Date: 11/30/2017
//Transacion Count: 3034
// CODE STARTS HERE
pragma solidity ^0.4.18;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
assert(c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
uint256 public totalSupply;
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
// SafeMath.sub will throw if there is not enough balance.
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
contract ZillaToken is StandardToken, Ownable {
uint256 constant zilla = 1 ether;
string public name = 'Zilla Token';
string public symbol = 'ZLA';
uint public decimals = 18;
uint256 public initialSupply = 60000000 * zilla;
bool public tradeable;
function ZillaToken() public {
totalSupply = initialSupply;
balances[msg.sender] = initialSupply;
tradeable = false;
}
/**
* @dev modifier to determine if the token is tradeable
*/
modifier isTradeable() {
require( tradeable == true );
_;
}
/**
* @dev allow the token to be freely tradeable
*/
function allowTrading() public onlyOwner {
require( tradeable == false );
tradeable = true;
}
/**
* @dev allow the token to be freely tradeable
* @param _to the address to transfer ZLA to
* @param _value the amount of ZLA to transfer
*/
function crowdsaleTransfer(address _to, uint256 _value) public onlyOwner returns (bool) {
require( tradeable == false );
return super.transfer(_to, _value);
}
function transfer(address _to, uint256 _value) public isTradeable returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public isTradeable returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public isTradeable returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public isTradeable returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public isTradeable returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale.
* Crowdsales have a start and end timestamps, where investors can make
* token purchases and the crowdsale will assign them tokens based
* on a token per ETH rate. Funds collected are forwarded to a wallet
* as they arrive.
*/
contract ZillaCrowdsale is Ownable {
using SafeMath for uint256;
// public events
event StartCrowdsale();
event FinalizeCrowdsale();
event TokenSold(address recipient, uint eth_amount, uint zla_amount);
// crowdsale constants
uint256 constant presale_eth_to_zilla = 1200;
uint256 constant crowdsale_eth_to_zilla = 750;
// our ZillaToken contract
ZillaToken public token;
// crowdsale token limit
uint256 public zilla_remaining;
// our Zilla multisig vault address
address public vault;
// crowdsale state
enum CrowdsaleState { Waiting, Running, Ended }
CrowdsaleState public state = CrowdsaleState.Waiting;
uint256 public start;
uint256 public unlimited;
uint256 public end;
// participants state
struct Participant {
bool whitelist;
uint256 remaining;
}
mapping (address => Participant) private participants;
/**
* @dev constructs ZillaCrowdsale
*/
function ZillaCrowdsale() public {
token = new ZillaToken();
zilla_remaining = token.totalSupply();
}
/**
* @dev modifier to determine if the crowdsale has been initialized
*/
modifier isStarted() {
require( (state == CrowdsaleState.Running) );
_;
}
/**
* @dev modifier to determine if the crowdsale is active
*/
modifier isRunning() {
require( (state == CrowdsaleState.Running) && (now >= start) && (now < end) );
_;
}
/**
* @dev start the Zilla Crowdsale
* @param _start is the epoch time the crowdsale starts
* @param _end is the epoch time the crowdsale ends
* @param _vault is the multisig wallet the ethereum is transfered to
*/
function startCrowdsale(uint256 _start, uint256 _unlimited, uint256 _end, address _vault) public onlyOwner {
require(state == CrowdsaleState.Waiting);
require(_start >= now);
require(_unlimited > _start);
require(_unlimited < _end);
require(_end > _start);
require(_vault != 0x0);
start = _start;
unlimited = _unlimited;
end = _end;
vault = _vault;
state = CrowdsaleState.Running;
StartCrowdsale();
}
/**
* @dev Finalize the Zilla Crowdsale, unsold tokens are moved to the vault account
*/
function finalizeCrowdsale() public onlyOwner {
require(state == CrowdsaleState.Running);
require(end < now);
// transfer remaining tokens to vault
_transferTokens( vault, 0, zilla_remaining );
// end the crowdsale
state = CrowdsaleState.Ended;
// allow the token to be traded
token.allowTrading();
FinalizeCrowdsale();
}
/**
* @dev Allow owner to increase the end date of the crowdsale as long as the crowdsale is still running
* @param _end the new end date for the crowdsale
*/
function setEndDate(uint256 _end) public onlyOwner {
require(state == CrowdsaleState.Running);
require(_end > now);
require(_end > start);
require(_end > end);
end = _end;
}
/**
* @dev Allow owner to change the multisig wallet
* @param _vault the new address of the multisig wallet
*/
function setVault(address _vault) public onlyOwner {
require(_vault != 0x0);
vault = _vault;
}
/**
* @dev Allow owner to add to the whitelist
* @param _addresses array of addresses to add to the whitelist
*/
function whitelistAdd(address[] _addresses) public onlyOwner {
for (uint i=0; i<_addresses.length; i++) {
Participant storage p = participants[ _addresses[i] ];
p.whitelist = true;
p.remaining = 15 ether;
}
}
/**
* @dev Allow owner to remove from the whitelist
* @param _addresses array of addresses to remove from the whitelist
*/
function whitelistRemove(address[] _addresses) public onlyOwner {
for (uint i=0; i<_addresses.length; i++) {
delete participants[ _addresses[i] ];
}
}
/**
* @dev Fallback function which buys tokens when sent ether
*/
function() external payable {
buyTokens(msg.sender);
}
/**
* @dev Apply our fixed buy rate and verify we are not sold out.
* @param eth the amount of ether being used to purchase tokens.
*/
function _allocateTokens(uint256 eth) private view returns(uint256 tokens) {
tokens = crowdsale_eth_to_zilla.mul(eth);
require( zilla_remaining >= tokens );
}
/**
* @dev Apply our fixed presale rate and verify we are not sold out.
* @param eth the amount of ether used to purchase presale tokens.
*/
function _allocatePresaleTokens(uint256 eth) private view returns(uint256 tokens) {
tokens = presale_eth_to_zilla.mul(eth);
require( zilla_remaining >= tokens );
}
/**
* @dev Transfer tokens to the recipient and update our token availability.
* @param recipient the recipient to receive tokens.
* @param eth the amount of Ethereum spent.
* @param zla the amount of Zilla Tokens received.
*/
function _transferTokens(address recipient, uint256 eth, uint256 zla) private {
require( token.crowdsaleTransfer( recipient, zla ) );
zilla_remaining = zilla_remaining.sub( zla );
TokenSold(recipient, eth, zla);
}
/**
* @dev Allows the owner to grant presale participants their tokens.
* @param recipient the recipient to receive tokens.
* @param eth the amount of ether from the presale.
*/
function _grantPresaleTokens(address recipient, uint256 eth) private {
uint256 tokens = _allocatePresaleTokens(eth);
_transferTokens( recipient, eth, tokens );
}
/**
* @dev Allows anyone to create tokens by depositing ether.
* @param recipient the recipient to receive tokens.
*/
function buyTokens(address recipient) public isRunning payable {
Participant storage p = participants[ recipient ];
require( p.whitelist );
// check for the first session buy limits
if( unlimited > now ) {
require( p.remaining >= msg.value );
p.remaining.sub( msg.value );
}
uint256 tokens = _allocateTokens(msg.value);
require( vault.send(msg.value) );
_transferTokens( recipient, msg.value, tokens );
}
/**
* @dev Allows owner to transfer tokens to any address.
* @param recipient is the address to receive tokens.
* @param zla is the amount of Zilla to transfer
*/
function grantTokens(address recipient, uint256 zla) public isStarted onlyOwner {
require( zilla_remaining >= zla );
_transferTokens( recipient, 0, zla );
}
/**
* @dev Allows the owner to grant presale participants their tokens.
* @param recipients array of recipients to receive tokens.
* @param eths array of ether from the presale.
*/
function grantPresaleTokens(address[] recipients, uint256[] eths) public isStarted onlyOwner {
require( recipients.length == eths.length );
for (uint i=0; i<recipients.length; i++) {
_grantPresaleTokens( recipients[i], eths[i] );
}
}
}
| Allows the owner to grant presale participants their tokens. recipients array of recipients to receive tokens. eths array of ether from the presale./ | function grantPresaleTokens(address[] recipients, uint256[] eths) public isStarted onlyOwner {
require( recipients.length == eths.length );
for (uint i=0; i<recipients.length; i++) {
_grantPresaleTokens( recipients[i], eths[i] );
}
}
| 6,456,235 |
./full_match/1/0x6eaCC32119e988d0C1d16A1Dc493D01319998F94/sources/@tetu_io/tetu-contracts/contracts/base/governance/ControllableV2.sol | Initialize contract after setup it as proxy implementation Save block.timestamp in the "created" variable Use it only once after first logic setup __controller Controller address | function initializeControllable(address __controller) public initializer {
_setController(__controller);
_setCreated(block.timestamp);
_setCreatedBlock(block.number);
emit ContractInitialized(__controller, block.timestamp, block.number);
}
| 2,939,243 |
pragma solidity ^0.4.18;
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
/**
* @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 {
require(newOwner != address(0));
owner = newOwner;
}
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
contract 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;
}
function max64(uint64 a, uint64 b) internal constant returns (uint64) {
return a >= b ? a : b;
}
function min64(uint64 a, uint64 b) internal constant returns (uint64) {
return a < b ? a : b;
}
function max256(uint256 a, uint256 b) internal constant returns (uint256) {
return a >= b ? a : b;
}
function min256(uint256 a, uint256 b) internal constant returns (uint256) {
return a < b ? a : b;
}
}
/**
* @title RefundVault
* @dev This contract is used for storing funds while a crowdsale
* is in progress. Supports refunding the money if crowdsale fails,
* and forwarding it if crowdsale is successful.
*/
contract RefundVault is Ownable, SafeMath{
enum State { Active, Refunding, Closed }
mapping (address => uint256) public deposited;
mapping (address => uint256) public refunded;
State public state;
address[] public reserveWallet;
event Closed();
event RefundsEnabled();
event Refunded(address indexed beneficiary, uint256 weiAmount);
/**
* @dev This constructor sets the addresses of
* 10 reserve wallets.
* and forwarding it if crowdsale is successful.
* @param _reserveWallet address[5] The addresses of reserve wallet.
*/
function RefundVault(address[] _reserveWallet) {
state = State.Active;
reserveWallet = _reserveWallet;
}
/**
* @dev This function is called when user buy tokens. Only RefundVault
* contract stores the Ether user sent which forwarded from crowdsale
* contract.
* @param investor address The address who buy the token from crowdsale.
*/
function deposit(address investor) onlyOwner payable {
require(state == State.Active);
deposited[investor] = add(deposited[investor], msg.value);
}
event Transferred(address _to, uint _value);
/**
* @dev This function is called when crowdsale is successfully finalized.
*/
function close() onlyOwner {
require(state == State.Active);
state = State.Closed;
uint256 balance = this.balance;
uint256 reserveAmountForEach = div(balance, reserveWallet.length);
for(uint8 i = 0; i < reserveWallet.length; i++){
reserveWallet[i].transfer(reserveAmountForEach);
Transferred(reserveWallet[i], reserveAmountForEach);
}
Closed();
}
/**
* @dev This function is called when crowdsale is unsuccessfully finalized
* and refund is required.
*/
function enableRefunds() onlyOwner {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
/**
* @dev This function allows for user to refund Ether.
*/
function refund(address investor) returns (bool) {
require(state == State.Refunding);
if (refunded[investor] > 0) {
return false;
}
uint256 depositedValue = deposited[investor];
deposited[investor] = 0;
refunded[investor] = depositedValue;
investor.transfer(depositedValue);
Refunded(investor, depositedValue);
return true;
}
} | This function is called when crowdsale is unsuccessfully finalized and refund is required./ | function enableRefunds() onlyOwner {
require(state == State.Active);
state = State.Refunding;
RefundsEnabled();
}
| 1,015,757 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Mouth SVG generator
library MouthDetail {
/// @dev Mouth N°1 => Neutral
function item_1() public pure returns (string memory) {
return
base(
'<g display="inline" ><path d="M177.1,251.1c3.6-0.2,7.4-0.1,11,0s7.4,0.3,10.9,0.9c-3.6,0.3-7.4,0.3-11,0.2C184.4,252.1,180.7,251.8,177.1,251.1z" /></g><g display="inline" ><path d="M203.5,251.9c10.1-0.7,19.1,0.1,29.2-1.3C222.6,253.7,213.9,252.6,203.5,251.9z" /></g><g display="inline" ><path d="M196.7,261.5c0.9,0.5,2.1,0.9,2.9,1.1c0.8,0.2,2.1,0.4,2.9,0.5c0.8,0.1,2.1,0,3.1-0.1s2.1-0.5,3.1-0.9c-0.8,0.8-1.9,1.5-2.8,1.9c-1.1,0.3-2.3,0.5-3.3,0.4c-1.1-0.1-2.3-0.3-3.2-0.9C198.5,263.1,197.4,262.5,196.7,261.5z" /></g>',
"Neutral"
);
}
/// @dev Mouth N°2 => Canine
function item_2() public pure returns (string memory) {
return
base(
'<g display="inline" ><polyline fill="#FFFFFF" points="222.4,251.9 225.5,260.1 230,251.7 " /><path d="M222.4,251.9c0.6,1.4,1.1,2.6,1.8,4c0.5,1.4,1,2.7,1.6,4h-0.4c0.3-0.7,0.7-1.4,1.1-2.1l1.1-2.1c0.8-1.4,1.6-2.7,2.4-4.1c-0.6,1.5-1.4,2.9-2.1,4.3l-1,2.1c-0.4,0.7-0.7,1.5-1.1,2.1l-0.3,0.5l-0.2-0.5c-0.5-1.4-1-2.7-1.5-4.1C223.3,254.7,222.8,253.3,222.4,251.9z" /></g><g display="inline" ><polyline fill="#FFFFFF" points="187.3,252 184,259.7 180,251.5 " /><path d="M187.3,252c-0.4,1.4-0.9,2.7-1.5,4c-0.5,1.4-1,2.6-1.6,4l-0.2,0.5l-0.3-0.5c-0.3-0.6-0.6-1.4-1-2.1l-1-2.1c-0.6-1.4-1.3-2.7-1.9-4.2c0.8,1.4,1.5,2.6,2.2,4l1,2c0.3,0.7,0.7,1.4,1,2.1h-0.4c0.5-1.3,1-2.6,1.7-3.9C186.2,254.5,186.7,253.2,187.3,252z" /></g><path display="inline" d="M174.6,251c0,0,24.6,3.4,60.2,0.5" /><g display="inline" ><path d="M195.8,256.6c1.1,0.3,2.4,0.5,3.5,0.6c1.3,0.1,2.4,0.2,3.6,0.2s2.4-0.1,3.6-0.2s2.4-0.2,3.6-0.4c-0.6,0.2-1.1,0.4-1.8,0.6c-0.6,0.1-1.3,0.3-1.8,0.4c-1.3,0.2-2.5,0.3-3.8,0.3s-2.5-0.1-3.8-0.3C197.9,257.6,196.8,257.2,195.8,256.6z" /></g>',
"Canine"
);
}
/// @dev Mouth N°3 => Canine up
function item_3() public pure returns (string memory) {
return
base(
'<g display="inline" ><polyline fill="#FFFFFF" points="219.5,252.5 222.7,244.3 227.4,252.8 " /><path d="M219.5,252.5c0.6-1.4,1.1-2.6,1.9-4c0.5-1.4,1-2.7,1.7-4h-0.4c0.3,0.7,0.7,1.4,1.1,2.1l1.1,2.1c0.8,1.4,1.7,2.7,2.5,4.1c-0.6-1.5-1.5-2.9-2.2-4.3l-1-2.1c-0.4-0.7-0.7-1.5-1.1-2.1l-0.3-0.5l-0.2,0.5c-0.5,1.4-1,2.7-1.6,4.1C220.3,249.6,219.9,251,219.5,252.5z" /></g><g display="inline" ><polyline fill="#FFFFFF" points="185,252.4 181.8,244.5 177.4,252.7 " /><path d="M185,252.4c-0.4-1.4-0.9-2.7-1.5-4c-0.5-1.4-1-2.6-1.6-4l-0.2-0.5l-0.3,0.5c-0.3,0.6-0.6,1.4-1.1,2.1l-1.1,2.1c-0.6,1.4-1.4,2.7-2,4.2c0.8-1.4,1.6-2.6,2.3-4l1.1-2c0.3-0.7,0.7-1.4,1.1-2.1h-0.4c0.5,1.3,1,2.6,1.7,3.9C183.9,249.9,184.4,251.1,185,252.4z" /></g><path display="inline" d="M171.9,252.3c0,0,25.6,3.2,62.8,0" /><g display="inline" ><path d="M194.1,257.7c1.1,0.3,2.5,0.5,3.6,0.6c1.4,0.1,2.5,0.2,3.9,0.2s2.5-0.1,3.9-0.2s2.5-0.2,3.9-0.4c-0.6,0.2-1.1,0.4-1.9,0.6c-0.6,0.1-1.4,0.3-1.9,0.4c-1.4,0.2-2.6,0.3-4,0.3s-2.6-0.1-4-0.3C196.4,258.7,195.2,258.3,194.1,257.7z" /></g>',
"Canine up"
);
}
/// @dev Mouth N°4 => Poker
function item_4() public pure returns (string memory) {
return
base(
'<g id="Poker" ><path d="M174.5,253.4c2.7-0.4,5.4-0.6,8-0.7c2.7-0.1,5.4-0.2,8-0.1c2.7,0.1,5.4,0.4,8,0.5c2.7,0.1,5.4,0,8-0.2c2.7-0.2,5.4-0.3,8-0.4c2.7-0.1,5.4-0.2,8-0.1c5.4,0.1,10.7,0.3,16.1,1c0.1,0,0.1,0.1,0.1,0.1c0,0,0,0.1-0.1,0.1c-5.4,0.6-10.7,0.9-16.1,1c-2.7,0-5.4-0.1-8-0.1c-2.7,0-5.4-0.2-8-0.4c-2.7-0.2-5.4-0.3-8-0.2c-2.7,0.1-5.4,0.4-8,0.5c-2.7,0.1-5.4,0.1-8-0.1c-2.7-0.1-5.4-0.3-8-0.7C174.4,253.6,174.4,253.5,174.5,253.4C174.4,253.4,174.5,253.4,174.5,253.4z" /></g>',
"Poker"
);
}
/// @dev Mouth N°5 => Angry
function item_5() public pure returns (string memory) {
return
base(
'<g display="inline" ><path fill="#FFFFFF" d="M211.5,246.9c-7.9,1.5-19.6,0.3-23.8-0.9c-4.5-1.3-8.6,3.2-9.7,7.5c-0.5,2.6-1.4,7.7,3.9,10.5c6.7,2.5,6.4,0.1,10.4-2c3.9-2.1,11.3-1.1,17.3,2c6.1,3.1,15.1,2.3,20.2-0.4c3.2-1.8,3.8-7.9-4.8-14.7C222.5,247,220.4,245.2,211.5,246.9" /><path d="M211.5,247c-4.1,1-8.3,1.2-12.4,1.2c-2.1,0-4.2-0.2-6.3-0.4c-1-0.1-2.1-0.3-3.1-0.4c-0.5-0.1-1-0.2-1.6-0.3c-0.3-0.1-0.6-0.1-0.8-0.2c-0.2,0-0.4-0.1-0.6-0.1c-1.7-0.2-3.5,0.6-4.9,1.9c-1.4,1.3-2.5,3-3.1,4.8c-0.5,1.9-0.8,4-0.3,5.8c0.2,0.9,0.7,1.8,1.3,2.6c0.6,0.7,1.4,1.4,2.3,1.9l0,0c1.6,0.6,3.2,1.2,4.9,1c1.6-0.1,2.8-1.6,4.3-2.5c1.4-1,3.2-1.6,5-1.8c1.8-0.2,3.5-0.1,5.3,0.1c1.7,0.2,3.5,0.7,5.1,1.2c0.8,0.3,1.7,0.6,2.5,1s1.6,0.7,2.3,1c3,1.1,6.4,1.4,9.7,1.1c1.6-0.2,3.3-0.4,4.9-0.9c0.8-0.2,1.6-0.5,2.3-0.8c0.4-0.1,0.7-0.3,1.1-0.5l0.4-0.3c0.1-0.1,0.2-0.2,0.4-0.3c0.9-0.9,1.1-2.4,0.8-3.9s-1.1-2.9-2-4.3c-0.9-1.3-2.1-2.5-3.3-3.7c-0.6-0.6-1.3-1.1-1.9-1.6c-0.7-0.5-1.3-0.9-2.1-1.2c-1.5-0.6-3.2-0.8-4.9-0.8C214.9,246.6,213.2,246.8,211.5,247c-0.1,0-0.1,0-0.1-0.1s0-0.1,0.1-0.1c1.7-0.4,3.4-0.8,5.1-0.9c1.7-0.2,3.5-0.1,5.3,0.5c0.9,0.3,1.7,0.7,2.4,1.2s1.4,1,2.1,1.6c1.4,1.1,2.7,2.3,3.8,3.7s2.1,3,2.5,4.9c0.5,1.8,0.3,4.1-1.2,5.8c-0.2,0.2-0.4,0.4-0.6,0.6c-0.2,0.2-0.5,0.3-0.7,0.5c-0.4,0.2-0.8,0.4-1.2,0.6c-0.8,0.4-1.7,0.7-2.6,0.9c-1.7,0.5-3.5,0.8-5.3,0.9c-3.5,0.2-7.2-0.1-10.5-1.5c-0.8-0.4-1.7-0.8-2.4-1.1c-0.7-0.4-1.5-0.7-2.3-1c-1.6-0.6-3.2-1.1-4.8-1.4s-3.3-0.5-5-0.4s-3.2,0.5-4.7,1.4c-0.7,0.4-1.4,0.9-2.1,1.4c-0.7,0.5-1.6,1-2.5,1c-0.9,0.1-1.8-0.1-2.7-0.3c-0.9-0.2-1.7-0.5-2.5-0.8l0,0l0,0c-0.9-0.5-1.8-1.1-2.6-1.9c-0.7-0.8-1.3-1.8-1.7-2.8c-0.7-2.1-0.5-4.3-0.1-6.5c0.5-2.2,1.6-4.1,3.2-5.7c0.8-0.8,1.7-1.5,2.8-1.9c1.1-0.5,2.3-0.7,3.5-0.5c0.3,0,0.6,0.1,0.9,0.2c0.3,0.1,0.5,0.1,0.7,0.2c0.5,0.1,1,0.2,1.5,0.3c1,0.2,2,0.4,3,0.5c2,0.3,4.1,0.5,6.1,0.7c4.1,0.3,8.2,0.4,12.3,0c0.1,0,0.1,0,0.1,0.1C211.6,246.9,211.6,247,211.5,247z" /></g><g display="inline" ><path fill="#FFFFFF" d="M209.7,255.6l4.6-2.3c0,0,4.2,3,5.6,3.1s5.5-3.3,5.5-3.3l4.4,1.5" /><path d="M209.7,255.5c0.6-0.7,1.3-1.2,2-1.7s1.5-0.9,2.2-1.3l0.5-0.2l0.4,0.3c0.8,0.7,1.5,1.6,2.4,2.2c0.4,0.3,0.9,0.6,1.4,0.8s1.1,0.3,1.4,0.3c0.2-0.1,0.7-0.4,1.1-0.7c0.4-0.3,0.8-0.6,1.2-0.9c0.8-0.6,1.6-1.3,2.5-1.9l0.5-0.4l0.4,0.2c0.7,0.3,1.4,0.7,2.1,1c0.7,0.4,1.4,0.8,2,1.3c0,0,0.1,0.1,0,0.1h-0.1c-0.8,0-1.6-0.1-2.4-0.2c-0.8-0.1-1.5-0.3-2.3-0.5l1-0.2c-0.8,0.8-1.7,1.4-2.7,2c-0.5,0.3-1,0.6-1.5,0.8c-0.6,0.2-1.1,0.4-1.9,0.4c-0.8-0.2-1.1-0.6-1.6-0.8c-0.5-0.3-0.9-0.6-1.4-0.8c-1-0.5-2.1-0.7-3-1.3l0.9,0.1c-0.7,0.4-1.5,0.7-2.4,1c-0.8,0.3-1.7,0.5-2.6,0.6C209.7,255.7,209.6,255.6,209.7,255.5C209.6,255.6,209.6,255.5,209.7,255.5z" /></g><g display="inline" ><polyline fill="#FFFFFF" points="177.9,255.4 180.5,253.4 184.2,255.6 187.1,255.5 " /><path d="M177.8,255.3c0.1-0.4,0.2-0.6,0.3-0.9c0.2-0.3,0.3-0.5,0.5-0.7s0.4-0.4,0.6-0.5c0.2-0.1,0.6-0.2,0.8-0.2l0.6-0.1l0.1,0.1c0.2,0.3,0.5,0.6,0.8,0.8s0.7,0.2,1.1,0.3c0.4,0,0.7,0.1,1.1,0.3c0.3,0.1,0.7,0.3,1,0.4l-0.6-0.2c0.5,0,1,0.1,1.5,0.2c0.2,0.1,0.5,0.2,0.7,0.3s0.5,0.2,0.7,0.4c0.1,0,0.1,0.1,0,0.2l0,0c-0.2,0.2-0.5,0.3-0.7,0.5c-0.2,0.1-0.5,0.2-0.7,0.3c-0.5,0.2-1,0.3-1.4,0.3h-0.3l-0.3-0.2c-0.3-0.2-0.6-0.4-0.9-0.7c-0.3-0.2-0.5-0.5-0.8-0.8c-0.2-0.3-0.5-0.6-0.8-0.8s-0.6-0.3-1-0.3h0.6c-0.1,0.3-0.3,0.6-0.5,0.8s-0.4,0.3-0.7,0.5c-0.2,0.1-0.5,0.2-0.8,0.3s-0.6,0.1-1,0.1C177.9,255.5,177.8,255.4,177.8,255.3L177.8,255.3z" /></g>',
"Angry"
);
}
/// @dev Mouth N°6 => Sulk
function item_6() public pure returns (string memory) {
return
base(
'<path display="inline" fill="none" stroke="#000000" stroke-width="2" stroke-miterlimit="10" d="M178.5,252.7c0,0,27.4,3.6,48.5,0.1" /><g display="inline" ><path d="M175.6,245.9c0.9,0.7,1.8,1.6,2.4,2.6c0.6,1,1.1,2.2,1.1,3.4c0,0.3,0,0.6-0.1,0.9l-0.2,0.9c-0.3,0.5-0.5,1.1-1,1.6c-0.4,0.5-0.9,0.8-1.5,1.1c-0.5,0.3-1,0.5-1.7,0.7c0.4-0.4,0.9-0.7,1.4-1.1c0.4-0.4,0.8-0.7,1-1.3c0.6-0.8,1-1.9,0.9-2.9c0-1-0.3-2.1-0.8-3.1C176.9,247.9,176.4,247,175.6,245.9z" /></g><g display="inline" ><path d="M230.5,246.9c-0.6,0.9-1.3,2-1.7,3s-0.7,2.1-0.7,3.1s0.3,2.1,1,2.9c0.3,0.5,0.7,0.8,1.1,1.3c0.4,0.4,0.9,0.7,1.4,1.1c-0.5-0.2-1.1-0.4-1.7-0.7s-1-0.6-1.5-1.1c-0.5-0.4-0.7-1-1-1.6l-0.2-0.9c-0.1-0.3-0.1-0.6-0.1-0.9c0-1.3,0.4-2.5,1.1-3.5C228.7,248.5,229.5,247.6,230.5,246.9z" /></g>',
"Sulk"
);
}
/// @dev Mouth N°7 => Tongue
function item_7() public pure returns (string memory) {
return
base(
'<path display="inline" fill="#FF155D" d="M208.3,255.3c0,0,4.3,11.7,13.4,10.2c12.2-1.9,6.8-12.3,6.8-12.3L208.3,255.3z" /><line display="inline" fill="none" stroke="#73093E" stroke-miterlimit="10" x1="219.3" y1="254.7" x2="221.2" y2="259.7" /><path display="inline" fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M203.4,255.6c0,0,22.3,0.1,29.7-4.5" /><path display="inline" fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M177.9,251.6c0,0,10.6,4.4,21.3,4.1" />',
"Tongue"
);
}
/// @dev Mouth N°8 => None
function item_8() public pure returns (string memory) {
return base("", "None");
}
/// @dev Mouth N°9 => Fantom
function item_9() public pure returns (string memory) {
return
base(
'<path d="M220.3,255.4l-4.9,7.8c-.4.6-.9.6-1.3,0l-4.8-7.8a2.56,2.56,0,0,1,0-2.1l4.9-7.8c.4-.6.9-.6,1.3,0l4.8,7.8A2,2,0,0,1,220.3,255.4Zm-11.9-.1-4.9,7.8c-.4.6-.9.6-1.3,0l-4.8-7.8a2.56,2.56,0,0,1,0-2.1l4.9-7.8c.4-.6.9-.6,1.3,0l4.8,7.8A2,2,0,0,1,208.4,255.3Zm-12.3-.1-4.9,7.8c-.4.6-.9.6-1.3,0l-4.8-7.8a2.56,2.56,0,0,1,0-2.1l4.9-7.8c.4-.6.9-.6,1.3,0l4.8,7.8A2,2,0,0,1,196.1,255.2Z" transform="translate(0 0.5)" fill="none" stroke="#000" stroke-width="2"/> <path d="M190.8,244.8l23.9.2m-24,18.6,23.9.2m-17.1-9.6,11.2.1" transform="translate(0 0.5)" fill="none" stroke="#000" stroke-linecap="square" stroke-width="2"/>',
"Fantom"
);
}
/// @dev Mouth N°10 => Evil
function item_10() public pure returns (string memory) {
return
base(
'<g display="inline" ><path fill="#FFFFFF" d="M177.3,250.9c0,0,16.5-1.1,17.8-1.6c1.4-0.4,35.2,6.6,37.2,5.7c2.1-0.8,4.7-2,4.7-2s-14.4,8.3-44.5,8.2c0,0-4-0.7-4.8-1.9C186.8,258.3,179.7,251.4,177.3,250.9z" /><path d="M177.2,250.9c0.3-0.1,0.4-0.1,0.6-0.1l0.6-0.1l1.1-0.1l2.2-0.3l4.4-0.5l4.4-0.5l2.2-0.3l1.1-0.2c0.4-0.1,0.7-0.1,1-0.2h0.1c0.5-0.1,0.6,0,0.9,0l0.7,0.1l1.3,0.2l2.7,0.4c1.8,0.3,3.5,0.6,5.3,0.9c3.5,0.7,7,1.4,10.5,2.1c3.5,0.7,7,1.4,10.5,1.9c0.9,0.1,1.8,0.2,2.6,0.3c0.9,0.1,1.8,0.2,2.6,0.1c0.1,0,0.4-0.1,0.6-0.2l0.6-0.3l1.2-0.5l2.4-1.1l0.3,0.7c-3.4,1.9-7,3.2-10.7,4.3s-7.4,1.9-11.2,2.6l-2.8,0.5c-0.9,0.1-1.9,0.2-2.8,0.4c-1.9,0.3-3.8,0.4-5.7,0.5s-3.8,0.2-5.7,0.3h-5.7h-0.1l0,0c-0.9-0.2-1.8-0.4-2.6-0.7c-0.4-0.2-0.9-0.3-1.3-0.5c-0.4-0.2-0.9-0.5-1.2-1v0.1c-0.7-0.8-1.5-1.6-2.3-2.4s-1.6-1.6-2.4-2.3c-0.8-0.8-1.6-1.5-2.5-2.2c-0.4-0.4-0.9-0.7-1.3-1C178.3,251.4,177.8,251.2,177.2,250.9z M177.4,250.9c0.3,0,0.5,0,0.8,0.2c0.3,0.1,0.5,0.2,0.8,0.4c0.5,0.3,1,0.6,1.4,0.9c0.9,0.6,1.8,1.3,2.7,2s1.7,1.4,2.6,2.2c0.8,0.8,1.7,1.5,2.5,2.3v0.1c0.1,0.2,0.5,0.4,0.8,0.6c0.4,0.2,0.8,0.3,1.2,0.4c0.8,0.2,1.6,0.4,2.5,0.6h-0.1l5.7-0.2c1.9-0.1,3.8-0.2,5.7-0.4c3.8-0.3,7.5-0.7,11.3-1.3c3.7-0.6,7.4-1.3,11.1-2.3c1.8-0.5,3.6-1,5.4-1.6c1.8-0.6,3.6-1.3,5.2-2.1l0.3,0.7l-2.5,1l-1.2,0.5l-0.6,0.3c-0.2,0.1-0.4,0.2-0.7,0.2c-1,0.1-1.8-0.1-2.7-0.2c-0.9-0.1-1.8-0.2-2.7-0.4l-10.6-1.6c-3.5-0.5-7.1-1-10.6-1.6l-5.3-0.9l-2.6-0.4l-1.3-0.2l-0.6-0.1c-0.2,0-0.5,0-0.4,0h0.1c-0.5,0.1-0.9,0.2-1.2,0.2l-1.1,0.1c-0.7,0.1-1.5,0.1-2.2,0.2l-4.5,0.3c-1.5,0.1-3,0.2-4.5,0.2l-2.2,0.1h-1.1h-0.6C177.7,250.9,177.5,251,177.4,250.9z" /></g><g display="inline" ><path d="M184.2,256.2c0.5-0.5,1.2-0.9,1.8-1.1c0.3-0.1,0.7-0.1,1.1-0.2c0.4,0,0.7-0.2,1-0.3l0,0h0.1c0.3,0.1,0.7,0.1,1,0.1s0.7,0.1,1,0.2c0.7,0.1,1.3,0.4,1.9,0.7h-0.3c0.4-0.1,0.8-0.2,1.3-0.3v0.1c-0.3,0.4-0.6,0.6-0.9,0.9l-0.1,0.1h-0.2c-0.7-0.1-1.3-0.2-1.9-0.5c-0.3-0.1-0.6-0.2-0.9-0.4c-0.3-0.2-0.6-0.3-0.9-0.5h0.1c-0.3,0.1-0.7,0.2-1,0.4s-0.6,0.4-0.9,0.6C185.7,256.1,185,256.3,184.2,256.2L184.2,256.2z" /></g><g display="inline" ><path d="M201.3,256.5c1.3-0.4,2.7-0.6,4-0.8s2.7-0.4,4.1-0.4h0.1h0.1c1.1,0.6,2.2,1.3,3.3,1.8h-0.1c1.5-0.5,2.9-1.2,4.3-1.7h0.1l0.2,0.1c1.1,0.4,2.1,0.8,3.1,1.2h-0.2c1.5-0.1,3-0.2,4.5-0.2s3,0,4.5,0.1v0.1c-1.5,0.3-2.9,0.5-4.4,0.6c-1.5,0.2-3,0.3-4.4,0.3h-0.1h-0.1c-1-0.5-2-0.9-3.1-1.4h0.3c-1.5,0.4-3,0.8-4.5,1.3h-0.1h-0.1c-1.1-0.6-2.3-1-3.5-1.4h0.2c-1.3,0.3-2.7,0.4-4,0.5C204,256.6,202.7,256.6,201.3,256.5L201.3,256.5z" /></g>',
"Evil"
);
}
/// @dev Mouth N°11 => Monster
function item_11() public pure returns (string memory) {
return
base(
'<polyline display="inline" fill="none" stroke="#000000" stroke-width="0.5" stroke-linejoin="round" stroke-miterlimit="10" points="145.8,244.7 150,250.4 153.3,242.5 157.5,255 165.4,242.3 170.3,260.1 179.5,243 185.4,263.2 194.4,243.5 202.9,265.5 212.8,243.8 219.6,263.1 227.1,243.5 235.2,259.1 242.5,243 250.3,254.8 255.6,242.3 260.3,251.8 265.6,241.8 269.8,248.8 274.2,241 276.3,244.6 " />',
"Monster"
);
}
/// @dev Mouth N°12 => Drool
function item_12() public pure returns (string memory) {
return
base(
'<path display="inline" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M191.1,248c2.8,0.6,7.8,1.6,10.9,1.2l17.1-2.7c0,0,13.1-2.3,13.3,3.9c-1,6.3-2.3,10.5-5.5,11.2c0,0,3.7,10.8-3.2,10.2c-4.2-0.4-2.8-8.6-2.8-8.6s-19.9,5-40.1-1.9c-3.4-1.5-8.4-10-5.2-14.5C177.6,245.4,181.5,244.9,191.1,248z" />',
"Drool"
);
}
/// @dev Mouth N°13 => UwU Kitsune
function item_13() public pure returns (string memory) {
return
base(
'<polyline display="inline" fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" points="217.9,254.7 221.2,259.6 224.3,251.9 " /><g display="inline" ><path d="M178,246.5c1.4,2,3,3.8,4.8,5.3c0.5,0.4,0.9,0.8,1.4,1.1l0.8,0.5c0.3,0.2,0.5,0.3,0.8,0.4c1.1,0.5,2.3,0.7,3.5,0.8c2.4,0.1,4.8-0.4,7.1-0.9l3.5-1.1c1.1-0.5,2.3-0.9,3.4-1.3c0,0,0.1,0,0.1,0c0,0,0,0,0,0.1c-1,0.7-2.1,1.3-3.2,1.9c-1.1,0.5-2.3,1-3.5,1.4c-0.6,0.1-1.2,0.3-1.8,0.4l-0.9,0.2l-0.9,0.1c-0.6,0-1.3,0.1-1.9,0.1c-0.6-0.1-1.3-0.2-1.9-0.2c-0.6-0.1-1.2-0.3-1.8-0.4c-0.6-0.1-1.2-0.4-1.8-0.6c-0.6-0.2-1.2-0.4-1.7-0.7c-0.6-0.2-1.1-0.6-1.7-0.9C180.3,251.1,178.7,249,178,246.5C177.9,246.6,177.9,246.5,178,246.5C178,246.5,178,246.5,178,246.5L178,246.5z" /></g><g display="inline" ><path d="M231.1,245.2c-1.2,2.4-3.1,4.5-5.2,6.1c-1.1,0.8-2.3,1.4-3.6,1.9c-1.2,0.6-2.5,1.1-3.7,1.5c-2.6,0.8-5.4,0.9-8.1,0.2c-2.6-0.7-5.1-1.9-7.2-3.6c0,0,0,0,0-0.1c0,0,0,0,0.1,0c2.4,1.1,4.9,2.1,7.4,2.7c2.5,0.6,5.1,0.7,7.7,0.3c1.3-0.2,2.6-0.6,3.7-1.2c1.2-0.6,2.2-1.4,3.2-2.3C227.4,248.9,229.3,247.1,231.1,245.2C231.1,245.1,231.1,245.1,231.1,245.2C231.1,245.1,231.1,245.2,231.1,245.2z" /></g>',
"UwU Kitsune"
);
}
/// @dev Mouth N°14 => Stitch
function item_14() public pure returns (string memory) {
return
base(
'<g display="inline" ><path d="M146.7,249c10.6,1.8,21.4,2.9,32.1,3.9c2.7,0.2,5.3,0.5,8,0.7s5.4,0.3,8,0.5c5.4,0.2,10.7,0.2,16.2,0.1c5.4-0.1,10.7-0.5,16.2-0.7l8-0.6c1.4-0.1,2.7-0.2,4.1-0.3l4-0.4c10.7-1,21.3-2.9,31.9-4.8v0.1l-7.9,1.9l-4,0.8c-1.4,0.3-2.6,0.5-4,0.7l-8,1.4c-2.7,0.4-5.3,0.6-8,1c-5.3,0.7-10.7,0.9-16.2,1.4c-5.4,0.2-10.7,0.4-16.2,0.3c-10.7-0.1-21.6-0.3-32.3-0.9C167.9,252.9,157.1,251.5,146.7,249L146.7,249z" /></g><path display="inline" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M192.9,254.2c0,0,7.8-2.1,17.5,0.2C210.4,254.4,201.6,257.3,192.9,254.2z" /><g display="inline" ><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M215.2,250.7c0,0,1.1-3.4,2.8-1c0,0,0.5,5.3-0.7,9.9c0,0-1,2.2-1.6-0.6C215.2,256.2,216.3,255.9,215.2,250.7z" /><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M223.3,250.9c0,0,1-3.1,2.5-0.9c0,0,0.5,4.7-0.6,8.9c0,0-0.9,1.9-1.4-0.5C223.3,255.8,224.2,255.5,223.3,250.9z" /><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M229.7,250.8c0,0,0.9-2.7,2.2-0.8c0,0,0.4,4.1-0.5,7.7c0,0-0.8,1.7-1.1-0.4C229.7,255,230.6,254.8,229.7,250.8z" /><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M235.2,250.5c0,0,0.8-2.4,2-0.7c0,0,0.4,3.6-0.5,6.9c0,0-0.7,1.5-1-0.4C235.4,254.3,236,254.1,235.2,250.5z" /></g><g display="inline" ><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M188.4,250.3c0,0-1.1-3.4-2.8-1c0,0-0.5,5.3,0.7,9.9c0,0,1,2.2,1.6-0.6S187.1,255.5,188.4,250.3z" /><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M180.4,250.5c0,0-1-3.1-2.5-0.9c0,0-0.5,4.7,0.6,8.9c0,0,0.9,1.9,1.4-0.5C180.3,255.5,179.4,255,180.4,250.5z" /><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M173.8,250.4c0,0-0.9-2.7-2.2-0.8c0,0-0.4,4.1,0.5,7.7c0,0,0.8,1.7,1.1-0.4C173.6,254.7,172.9,254.4,173.8,250.4z" /><path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M168.2,250c0,0-0.8-2.4-2-0.7c0,0-0.4,3.6,0.5,6.9c0,0,0.7,1.5,1-0.4C168.2,253.9,167.5,253.7,168.2,250z" /></g>',
"Stitch"
);
}
/// @dev Mouth N°15 => Pantin
function item_15() public pure returns (string memory) {
return
base(
'<path display="inline" d="M227.4,254h-46.7c-0.5,0-0.9-0.4-0.9-0.9v-2c0-0.5,0.4-0.9,0.9-0.9h46.7c0.5,0,0.9,0.4,0.9,0.9v2C228.2,253.7,228,254,227.4,254z" /><path display="inline" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M180.4,251.1c-0.9,9.5-0.5,18.8,0.5,29.7" /><path display="inline" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M227.7,251c0.5,10.5,0.1,22.5-0.7,35.3" />',
"Pantin"
);
}
/// @dev Mouth N°16 => Akuma
function item_16() public pure returns (string memory) {
return
base(
'<path display="inline" d="M278,243.1c-8.1,1.5-18.1,4.2-26.3,5.5c-8.1,1.4-16.3,2.5-24.6,2.8l0.3-0.2l-5.6,10.9l-0.4,0.7l-0.4-0.7l-5.3-10.4l0.4,0.2c-4.8,0.3-9.6,0.6-14.4,0.5c-4.8,0-9.6-0.5-14.4-1.1l0.4-0.2l-5.7,11.3l-0.3,0.5l-0.3-0.5l-5.9-11.6l0.2,0.1l-7.6-0.6c-2.5-0.2-5.1-0.6-7.6-1.1c-1.3-0.2-2.5-0.5-3.8-0.8s-2.5-0.6-3.8-1c-2.4-0.7-4.9-1.5-7.3-2.4v-0.1c2.5,0.4,5,1,7.5,1.6c1.3,0.2,2.5,0.5,3.8,0.8l3.8,0.8c2.5,0.5,5,1.1,7.5,1.6s5,0.8,7.6,0.8h0.1l0.1,0.1l6.1,11.6h-0.5l5.5-11.3l0.1-0.2h0.3c4.8,0.5,9.5,1,14.3,1s9.6-0.2,14.4-0.5h0.3l0.1,0.2l5.3,10.4h-0.7l5.7-10.8l0.1-0.2h0.2c8.2-0.2,16.4-1.3,24.5-2.6c8-1.1,16.2-2.7,24.3-4L278,243.1z" />',
"Akuma"
);
}
/// @dev Mouth N°17 => Monster Teeth
function item_17() public pure returns (string memory) {
return
base(
'<path display="inline" fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M165.5,241.9c0,0,0.5,0.1,1.4,0.3c4.3,1.2,36.4,12.1,81.4-1c0.1,0.1-17.5,28.2-43.1,28.6C192.4,270.1,181.1,263.4,165.5,241.9z" /><polyline display="inline" fill="none" stroke="#000000" stroke-width="0.75" stroke-linejoin="round" stroke-miterlimit="10" points="168.6,245.8 171.3,243.6 173.9,252.6 177.5,245.1 181.7,260.4 188.2,246.8 192.8,267.3 198.5,247.8 204,269.9 209,247.9 215.5,268.3 219.3,247.1 225.4,264 228.2,246 234,257.8 236.7,244.5 240.4,251.4 243.1,242.7 245.9,245.1 " /><g display="inline" opacity="0.52" ><path d="M246.1,239.5c1.9-0.8,3.5-1.4,5.9-1.9l0.6-0.1l-0.2,0.6c-0.6,2.2-1.3,4.5-2.1,6.5c0.3-2.4,0.8-4.6,1.4-6.9l0.4,0.5C250.1,239,248.2,239.4,246.1,239.5z" /></g><g display="inline" opacity="0.52" ><path d="M168,240.4c-2-0.2-4-0.5-5.9-0.8l0.4-0.5c0.6,2.4,1.3,4.7,1.5,7.2c-0.9-2.2-1.6-4.6-2.2-7l-0.2-0.6l0.6,0.1C164.1,239,165.9,239.7,168,240.4z" /></g>',
"Monster Teeth"
);
}
/// @dev Mouth N°18 => Dubu
function item_18() public pure returns (string memory) {
return
base(
'<g display="inline" ><path d="M204,251.4c-2.2-1.2-4.5-2.1-6.9-2.6c-1.2-0.2-2.4-0.4-3.6-0.4c-1.1,0-2.4,0.2-3.1,0.7c-0.4,0.2-0.5,0.5-0.5,0.9s0.3,1,0.6,1.5c0.6,1,1.5,1.9,2.5,2.6c2,1.5,4.3,2.6,6.6,3.6l3.3,1.4l-3.7-0.3c-2.4-0.2-4.9-0.4-7.2-0.2c-0.6,0.1-1.1,0.2-1.5,0.4c-0.4,0.2-0.7,0.4-0.6,0.5c0,0.1,0,0.5,0.3,0.9s0.6,0.8,1,1.2c1.7,1.5,3.8,2.6,6,3.3c2.2,0.6,4.7,0.8,6.9-0.4h0.1v0.1c-0.9,0.9-2.1,1.5-3.4,1.7c-1.3,0.3-2.6,0.2-3.9,0c-2.6-0.4-5-1.5-7.1-3.2c-0.5-0.4-1-1-1.4-1.6s-0.8-1.5-0.6-2.6c0.1-0.5,0.5-1,0.8-1.3c0.2-0.2,0.4-0.3,0.5-0.4c0.2-0.1,0.4-0.2,0.6-0.3c0.7-0.3,1.4-0.4,2.1-0.4c2.7-0.2,5.1,0.3,7.5,0.9l-0.4,1.1l-1.6-1c-0.5-0.3-1.1-0.7-1.6-1l-1.6-1c-0.5-0.4-1.1-0.7-1.6-1.1c-1-0.7-2.1-1.5-3-2.5c-0.4-0.5-0.9-1.1-1.1-1.9c-0.1-0.4-0.1-0.9,0.1-1.3c0.2-0.4,0.4-0.8,0.8-1.1c1.3-1,2.8-1.1,4.1-1.2c1.4,0,2.7,0.2,3.9,0.6c2.5,0.8,4.9,2.1,6.6,4v0.1C204.1,251.4,204.1,251.4,204,251.4z" /></g>',
"Dubu"
);
}
/// @notice Return the skin name of the given id
/// @param id The skin Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Neutral";
} else if (id == 2) {
name = "Canine";
} else if (id == 3) {
name = "Canine up";
} else if (id == 4) {
name = "Poker";
} else if (id == 5) {
name = "Angry";
} else if (id == 6) {
name = "Sulk";
} else if (id == 7) {
name = "Tongue";
} else if (id == 8) {
name = "None";
} else if (id == 9) {
name = "Fantom";
} else if (id == 10) {
name = "Evil";
} else if (id == 11) {
name = "Monster";
} else if (id == 12) {
name = "Drool";
} else if (id == 13) {
name = "UwU Kitsune";
} else if (id == 14) {
name = "Stitch";
} else if (id == 15) {
name = "Pantin";
} else if (id == 16) {
name = "Akuma";
} else if (id == 17) {
name = "Monster Teeth";
} else if (id == 18) {
name = "Dubu";
}
}
/// @dev The base SVG for the body
function base(string memory children, string memory name) private pure returns (string memory) {
return string(abi.encodePacked('<g id="mouth"><g id="', name, '">', children, "</g></g>"));
}
}
| Mouth N°6 => Sulk | function item_6() public pure returns (string memory) {
return
base(
'<path display="inline" fill="none" stroke="#000000" stroke-width="2" stroke-miterlimit="10" d="M178.5,252.7c0,0,27.4,3.6,48.5,0.1" /><g display="inline" ><path d="M175.6,245.9c0.9,0.7,1.8,1.6,2.4,2.6c0.6,1,1.1,2.2,1.1,3.4c0,0.3,0,0.6-0.1,0.9l-0.2,0.9c-0.3,0.5-0.5,1.1-1,1.6c-0.4,0.5-0.9,0.8-1.5,1.1c-0.5,0.3-1,0.5-1.7,0.7c0.4-0.4,0.9-0.7,1.4-1.1c0.4-0.4,0.8-0.7,1-1.3c0.6-0.8,1-1.9,0.9-2.9c0-1-0.3-2.1-0.8-3.1C176.9,247.9,176.4,247,175.6,245.9z" /></g><g display="inline" ><path d="M230.5,246.9c-0.6,0.9-1.3,2-1.7,3s-0.7,2.1-0.7,3.1s0.3,2.1,1,2.9c0.3,0.5,0.7,0.8,1.1,1.3c0.4,0.4,0.9,0.7,1.4,1.1c-0.5-0.2-1.1-0.4-1.7-0.7s-1-0.6-1.5-1.1c-0.5-0.4-0.7-1-1-1.6l-0.2-0.9c-0.1-0.3-0.1-0.6-0.1-0.9c0-1.3,0.4-2.5,1.1-3.5C228.7,248.5,229.5,247.6,230.5,246.9z" /></g>',
"Sulk"
);
}
| 13,025,657 |
/**
*Submitted for verification at Etherscan.io on 2021-07-10
*/
// SPDX-License-Identifier: ISC
pragma solidity ^0.8.4;
/* ----------------------------------------------------------------------------
'GToken' contract
* Symbol : GTO
* Name : GToken
* Total supply: 1 trillion
* Decimals : 18
---------------------------------------------------------------------------- */
interface IGtoken {
/**
* @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 decimal places of a token
*/
function decimals() external view returns (uint8);
/**
* @dev returns the total tokens in existence
*/
function totalSupply() external view returns (uint256);
/**
* @dev returns the tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev transfers the `amount` of tokens from caller's account
* to the `recipient` account.
*
* returns boolean value indicating the operation status.
*
* Emits a {Transfer} event
*/
function transfer(address recipient, uint256 amount)
external
returns (bool);
/**
* @dev returns the remaining number of tokens the `spender' can spend
* on behalf of the owner.
*
* This value changes when {approve} or {transferFrom} is executed.
*/
function allowance(address owner, address spender)
external
view
returns (uint256);
/**
* @dev sets `amount` as the `allowance` of the `spender`.
*
* returns a boolean value indicating the operation status.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev transfers the `amount` on behalf of `spender` to the `recipient` account.
*
* returns a boolean indicating the operation status.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address spender,
address recipient,
uint256 amount
) external returns (bool);
/**
* @dev Emitted from tokens are moved from one account('from') to another account ('to)
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when allowance of a `spender` is set by the `owner`
*/
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
abstract contract Context {
function msgSender() internal view virtual returns(address) {
return msg.sender;
}
function msgData() internal view virtual returns(bytes calldata) {
this;
return msg.data;
}
function msgValue() internal view virtual returns(uint256) {
return msg.value;
}
}
contract GToken is IGtoken, Context {
mapping(address => uint256) private balances;
mapping(address => mapping(address => uint256)) private allowances;
address private _governor;
uint256 private _totalSupply;
uint256 public feeFraction = 10;
string private _name;
string private _symbol;
// allowedAddresses will be able to transfer even when locked
mapping(address => bool) public allowedAddresses;
// lockedAddresses will *not* be able to transfer even when *not locked*
mapping(address => bool) public lockedAddresses;
mapping (address => mapping (address => uint256)) allowed;
bool public freezed = false;
/**
* @dev checks whether `caller` is governor;
*/
modifier onlyGovernor() {
require(msgSender() == _governor, "ERC20: caller not governor");
_;
}
/**
* @dev adds the address to the list of allowedAddresses
*/
function allowAddress(address _addr, bool _allowed) public onlyGovernor {
require(_addr != _governor);
allowedAddresses[_addr] = _allowed;
}
/**
* @dev adds the address to the list of lockedAddresses
*/
function lockAddress(address _addr, bool _locked) public onlyGovernor {
require(_addr != _governor);
lockedAddresses[_addr] = _locked;
}
/**
* @dev freezes the contract
*/
function freeze() public onlyGovernor {
freezed = true;
}
/**
* @dev unfreezes the contract
*/
function unfreeze() public onlyGovernor {
freezed = false;
}
/**
* @dev validates the transfer
*/
function validateTransfer(address _addr) internal view returns (bool) {
if(freezed){
if(!allowedAddresses[_addr]&&_addr!=_governor)
return false;
}
else if(lockedAddresses[_addr])
return false;
return true;
}
/**
* @dev sets the {name}, {symbol} and {governor wallet} of the token.
*
* All the two variables are immutable and cannot be changed
* and set only in the constructor.
*/
constructor(string memory name_, string memory symbol_, address _governorAddress) {
_name = name_;
_symbol = symbol_;
_governor = _governorAddress;
}
/**
* @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.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev returns the decimals of the token
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev returns the total supply of the token
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev returns the number of tokens owned by `account`
*/
function balanceOf(address account)
public
view
virtual
override
returns (uint256)
{
return balances[account];
}
/**
* @dev returns the amount the `spender` can spend on behalf of the `owner`.
*/
function allowance(address owner, address spender)
public
view
virtual
override
returns (uint256)
{
return allowances[owner][spender];
}
/**
* @dev Approve a `spender` to spend tokens on behalf of the `owner`.
*/
function approve(address spender, uint256 value)
public
virtual
override
returns (bool)
{
_approve(msgSender(), spender, value);
return true;
}
/**
* @dev to increase the allowance of `spender` over the `owner` account.
*
* Requirements
* `spender` cannot be zero address
*/
function increaseAllowance(address spender, uint256 addedValue)
public
virtual
returns (bool)
{
_approve(
msgSender(),
spender,
allowances[msgSender()][spender] + addedValue
);
return true;
}
/**
* @dev to decrease the allowance of `spender` over the `owner` account.
*
* Requirements
* `spender` allowance shoule be greater than the `reducedValue`
* `spender` cannot be a zero address
*/
function decreaseAllowance(address spender, uint256 reducedValue)
public
virtual
returns (bool)
{
uint256 currentAllowance = allowances[msgSender()][spender];
require(
currentAllowance >= reducedValue,
"ERC20: ReducedValue greater than allowance"
);
_approve(msgSender(), spender, currentAllowance - reducedValue);
return true;
}
/**
* @dev sets the amount as the allowance of `spender` over the `owner` address
*
* Requirements:
* `owner` cannot be zero address
* `spender` cannot be zero address
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from zero address");
require(spender != address(0), "ERC20: approve to zero address");
allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev transfers the `amount` of tokens to `recipient`
*/
function transfer(address recipient, uint256 amount)
public
virtual
override
returns (bool)
{
require(validateTransfer(msgSender()),"ERC20: Transfer reverted");
_transfer(msgSender(), recipient, amount);
emit Transfer(msgSender(), recipient, amount);
return true;
}
/**
* @dev transfers the 'amount` from the `sender` to the `recipient`
* on behalf of the `sender`.
*
* Requirements
* `sender` and `recipient` should be non zero addresses
* `sender` should have balance of more than `amount`
* `caller` must have allowance greater than `amount`
*/
function transferFrom(
address sender,
address recipient,
uint256 amount
) public virtual override returns (bool) {
require(validateTransfer(sender),"ERC20: Transfer reverted");
_transfer(sender, recipient, amount);
uint256 currentAllowance = allowances[sender][msgSender()];
require(currentAllowance >= amount, "ERC20: amount exceeds allowance");
_approve(sender, msgSender(), currentAllowance - amount);
emit Transfer(sender, recipient, amount);
return true;
}
/**
* @dev mints the amount of tokens to the `recipient` wallet.
*
* Requirements :
*
* The caller must be the `governor` of the contract.
* Governor can be an DAO smart contract.
*/
function mint(address recipient, uint256 amount)
public
virtual
onlyGovernor
returns (bool)
{
require(recipient != address(0), "ERC20: mint to a zero address");
_totalSupply += amount;
balances[recipient] += amount;
emit Transfer(address(0), recipient, amount);
return true;
}
/**
* @dev burns the `amount` tokens from `supply`.
*
* Requirements
* `caller` address balance should be greater than `amount`
*/
function burn(uint256 amount) public virtual onlyGovernor returns (bool) {
uint256 currentBalance = balances[msgSender()];
require(
currentBalance >= amount,
"ERC20: burning amount exceeds balance"
);
balances[msgSender()] = currentBalance - amount;
_totalSupply -= amount;
return true;
}
/**
* @dev transfers the `amount` of tokens from `sender` to `recipient`.
*
* Requirements:
* `sender` is not a zero address
* `recipient` is also not a zero address
* `amount` is less than or equal to balance of the sender.
*/
function _transfer(
address sender,
address recipient,
uint256 amount
) internal virtual {
require(sender != address(0), "ERC20: transfer from zero address");
require(recipient != address(0), "ERC20: transfer to zero address");
uint256 senderBalance = balances[sender];
require(
senderBalance >= amount,
"ERC20: transfer amount exceeds balance"
);
balances[sender] = senderBalance - amount;
// Transfer the spread to the admin
uint256 fee = amount * feeFraction / 10**4;
uint256 receiverAmount = amount - fee;
balances[recipient] += receiverAmount;
balances[_governor] +=fee;
emit Transfer(sender, recipient, amount);
}
/**
* @dev returns the current `governor` address.
*
* `governors` can mint / burn Gtokens
*/
function governor() public view virtual returns (address) {
return _governor;
}
/**
* @dev transfers the governance of the contract.
*
* Requirements :
* `caller` should be the current governor.
* `newGovernor` cannot be a zero address.
*/
function transferGovernance(address newGovernor)
public
virtual
onlyGovernor
returns (bool)
{
require(newGovernor != address(0), "ERC20: zero address cannot govern");
_governor = newGovernor;
return true;
}
/**
* @dev changes the transaction fee.
*
* Requirements :
* `caller` should be the current governor.
* `transactionFee` cannot be less than zero.
*/
function setTransactionFee(uint256 _newFeeFraction)
public
virtual
onlyGovernor
returns (bool)
{
require(_newFeeFraction >= 0, "ERC20: fee must not be negative");
feeFraction = _newFeeFraction;
return true;
}
} | freezes the contract/ | function freeze() public onlyGovernor {
freezed = true;
}
| 15,056,952 |
pragma solidity ^0.4.24;
import "./VPC.sol";
import "./ILibSignatures.sol";
contract MSContract {
event EventInitializing(address addressAlice, address addressBob);
event EventInitialized(uint cashAlice, uint cashBob);
event EventRefunded();
event EventStateRegistering();
event EventStateRegistered(uint blockedAlice, uint blockedBob);
event EventClosing();
event EventClosed();
event EventNotClosed();
modifier AliceOrBob { require(msg.sender == alice.id || msg.sender == bob.id); _;}
//Data type for Internal Contract
struct Party {
address id;
uint cash;
bool waitForInput;
}
//Data type for Internal Contract
struct InternalContract {
bool active;
address vpc;
uint sid;
uint blockedA;
uint blockedB;
uint version;
}
// State options
enum ChannelStatus {Init, Open, InConflict, Settled, WaitingToClose, ReadyToClose}
// MSContract variables
Party public alice;
Party public bob;
uint public timeout;
InternalContract public c;
ChannelStatus public status;
ILibSignatures libSig;
/*
* Constructor for setting initial variables takes as input
* addresses of the parties of the basic channel
*/
constructor(address _libSig, address _addressAlice, address _addressBob) public {
// set addresses
alice.id = _addressAlice;
bob.id = _addressBob;
// set limit until which Alice and Bob need to respond
timeout = now + 100 minutes;
alice.waitForInput = true;
bob.waitForInput = true;
libSig = ILibSignatures(_libSig);
// set other initial values
status = ChannelStatus.Init;
c.active = false;
emit EventInitializing(_addressAlice, _addressBob);
}
/*
* This functionality is used to send funds to the contract during 100 minutes after channel creation
*/
function confirm() public AliceOrBob payable {
require(status == ChannelStatus.Init && now < timeout);
// Response (in time) from Player A
if (alice.waitForInput && msg.sender == alice.id) {
alice.cash = msg.value;
alice.waitForInput = false;
}
// Response (in time) from Player B
if (bob.waitForInput && msg.sender == bob.id) {
bob.cash = msg.value;
bob.waitForInput = false;
}
// execute if both players responded
if (!alice.waitForInput && !bob.waitForInput) {
status = ChannelStatus.Open;
timeout = 0;
emit EventInitialized(alice.cash, bob.cash);
}
}
/*
* This function is used in case one of the players did not confirm the MSContract in time
*/
function refund() public AliceOrBob {
require(status == ChannelStatus.Init && now > timeout);
// refund money
if (alice.waitForInput && alice.cash > 0) {
require(alice.id.send(alice.cash));
}
if (bob.waitForInput && bob.cash > 0) {
require(bob.id.send(bob.cash));
}
emit EventRefunded();
// terminate contract
selfdestruct(alice.id);
}
/*
* This functionality is called whenever the channel state needs to be established
* it is called by both, alice and bob
* Afterwards the parties have to interact directly with the VPC
* and at the end they should call the execute function
* @param contract address: vpc, _sid,
blocked funds from A and B: blockedA and blockedB,
version parameter: version,
* signature parameter (from A and B): sigA, sigB
*/
function stateRegister(address _vpc, // vulnerable?
uint _sid,
uint _blockedA,
uint _blockedB,
uint _version,
bytes sigA,
bytes sigB) public AliceOrBob {
// check if the parties have enough funds in the contract
require(alice.cash >= _blockedA && bob.cash >= _blockedB);
// verfify correctness of the signatures
bytes32 msgHash = keccak256(abi.encodePacked(_vpc,_sid, _blockedA, _blockedB, _version));
bytes32 gethPrefixHash = keccak256(abi.encodePacked("\u0019Ethereum Signed Message:\n32", msgHash));
require(libSig.verify(alice.id, gethPrefixHash, sigA)
&& libSig.verify(bob.id, gethPrefixHash, sigB));
// execute on first call
if (status == ChannelStatus.Open || status == ChannelStatus.WaitingToClose) {
status = ChannelStatus.InConflict;
alice.waitForInput = true;
bob.waitForInput = true;
timeout = now + 100 minutes;
emit EventStateRegistering();
}
if (status != ChannelStatus.InConflict) return;
// record if message is sent by alice and bob
if (msg.sender == alice.id) alice.waitForInput = false;
if (msg.sender == bob.id) bob.waitForInput = false;
// set values of InternalContract
if (_version > c.version) {
c.active = true;
c.vpc = _vpc;
c.sid = _sid;
c.blockedA = _blockedA;
c.blockedB = _blockedB;
c.version = _version;
}
// execute if both players responded
if (!alice.waitForInput && !bob.waitForInput) {
status = ChannelStatus.Settled;
alice.waitForInput = false;
bob.waitForInput = false;
alice.cash -= c.blockedA;
bob.cash -= c.blockedB;
emit EventStateRegistered(c.blockedA, c.blockedB);
}
}
/*
* This function is used in case one of the players did not confirm the state
*/
function finalizeRegister() public AliceOrBob {
require(status == ChannelStatus.InConflict && now > timeout);
status = ChannelStatus.Settled;
alice.waitForInput = false;
bob.waitForInput = false;
alice.cash -= c.blockedA;
bob.cash -= c.blockedB;
emit EventStateRegistered(c.blockedA, c.blockedB);
}
/*
* This functionality executes the internal VPC Machine when its state is settled
* The function takes as input addresses of the parties of the virtual channel
*/
function execute(address _alice,
address _bob) public AliceOrBob {
require(status == ChannelStatus.Settled);
// call virtual payment machine on the params
bool v; uint a; uint b;
VPC cntr = VPC(c.vpc);
(v, a, b) = cntr.finalize(_alice, _bob, c.sid);
// check if the result makes sense
if (!v) return;
// update balances only if they make sense
if (a + b == c.blockedA + c.blockedB) {
alice.cash += a;
c.blockedA -= a;
bob.cash += b;
c.blockedB -= b;
}
// send funds to A and B
if (alice.id.send(alice.cash)) alice.cash = 0;
if (bob.id.send(bob.cash)) bob.cash = 0;
// terminate channel
if (alice.cash == 0 && bob.cash == 0) {
emit EventClosed();
selfdestruct(alice.id);
}
emit EventNotClosed();
}
/*
* This functionality closes the channel when there is no internal machine
*/
function close() public AliceOrBob {
if (status == ChannelStatus.Open) {
status = ChannelStatus.WaitingToClose;
timeout = now + 300 minutes;
alice.waitForInput = true;
bob.waitForInput = true;
emit EventClosing();
}
if (status != ChannelStatus.WaitingToClose) return;
// Response (in time) from Player A
if (alice.waitForInput && msg.sender == alice.id)
alice.waitForInput = false;
// Response (in time) from Player B
if (bob.waitForInput && msg.sender == bob.id)
bob.waitForInput = false;
if (!alice.waitForInput && !bob.waitForInput) {
// send funds to A and B
if (alice.id.send(alice.cash)) alice.cash = 0;
if (bob.id.send(bob.cash)) bob.cash = 0;
// terminate channel
if (alice.cash == 0 && bob.cash == 0) {
emit EventClosed();
selfdestruct(alice.id);
}
}
}
function finalizeClose() public AliceOrBob {
if (status != ChannelStatus.WaitingToClose) {
emit EventNotClosed();
return;
}
// execute if timeout passed
if (now > timeout) {
// send funds to A and B
if (alice.id.send(alice.cash)) alice.cash = 0;
if (bob.id.send(bob.cash)) bob.cash = 0;
// terminate channel
if (alice.cash == 0 && bob.cash == 0) {
emit EventClosed();
selfdestruct(alice.id);
}
}
}
}
| This functionality executes the internal VPC Machine when its state is settled The function takes as input addresses of the parties of the virtual channel/ call virtual payment machine on the params check if the result makes sense update balances only if they make sense terminate channel | function execute(address _alice,
address _bob) public AliceOrBob {
require(status == ChannelStatus.Settled);
bool v; uint a; uint b;
VPC cntr = VPC(c.vpc);
(v, a, b) = cntr.finalize(_alice, _bob, c.sid);
if (!v) return;
if (a + b == c.blockedA + c.blockedB) {
alice.cash += a;
c.blockedA -= a;
bob.cash += b;
c.blockedB -= b;
}
if (bob.id.send(bob.cash)) bob.cash = 0;
if (alice.cash == 0 && bob.cash == 0) {
emit EventClosed();
selfdestruct(alice.id);
}
emit EventNotClosed();
}
| 1,036,997 |
./full_match/1/0x6c9829e5aF58E993daC721e3c2de6A1d32e3b37C/sources/contracts/ERC721/ERC721KODAEditions.sol | Update Edition Creator allows the contact owner to provide edition attribution to another address _editionId the ID of the edition to set a creator for _creator the address of the creator associated with the works of an edition Emits {EditionCreatorUpdated}/ | function updateEditionCreator(
uint256 _editionId,
address _creator
) public override onlyOwner {
_updateEditionCreator(_editionId, _creator);
}
| 9,815,212 |
./partial_match/1/0x4F1982dcbB37021eA9F8Ed5dFa1C5a4b73f92665/sources/contracts/governance/monetary/InflationRootHashProposal.sol | Verifies that the account specified is associated with the provided cumulative sum in the approved Merkle tree for the current generation. _who address of the account attempting to claim _proof the “other nodes” in the merkle tree. _sum cumulative sum of a claiming account _index index of the account/ | function verifyClaimSubmission(
address _who,
bytes32[] calldata _proof,
uint256 _sum,
uint256 _index
) external view returns (bool) {
require(
acceptedRootHash != 0,
"Can't claim before root hash established"
);
uint256 balance = ecoToken.getPastVotes(_who, blockNumber);
return
verifyMerkleProof(
_proof,
acceptedRootHash,
keccak256(abi.encodePacked(_who, balance, _sum, _index)),
_index,
acceptedAmountOfAccounts
);
}
| 15,926,164 |
pragma solidity ^0.4.18;
contract ERC20Token{
//ERC20 base standard
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);
}
// From https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/ownership/Ownable.sol
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable{
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
function Ownable() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// Put the additional safe module here, safe math and pausable
// From https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/lifecycle/Pausable.sol
// And https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol
contract Safe is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
// Check if it is safe to add two numbers
function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
// Check if it is safe to subtract two numbers
function safeSubtract(uint256 a, uint256 b) internal pure returns (uint256) {
uint c = a - b;
assert(b <= a && c <= a);
return c;
}
// Check if it is safe to multiply two numbers
function safeMultiply(uint256 a, uint256 b) internal pure returns (uint256) {
uint c = a * b;
assert(a == 0 || (c / a) == b);
return c;
}
// reject any ether
function () public payable {
require(msg.value == 0);
}
}
// Adapted from zeppelin-solidity's BasicToken, StandardToken and BurnableToken contracts
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/BasicToken.sol
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/StandardToken.sol
// https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/token/ERC20/BurnableToken.sol
contract imaxChainToken is Safe, ERC20Token {
string public constant name = 'Inverstment Management Asset Exchange'; // Set the token name for display
string public constant symbol = 'IMAX'; // Set the token symbol for display
uint8 public constant decimals = 18; // Set the number of decimals for display
uint256 public constant INITIAL_SUPPLY = 1e9 * 10**uint256(decimals);
uint256 public totalSupply;
string public version = '1';
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) allowed;
mapping (address => uint256) freeze;
event Burn(address indexed burner, uint256 value);
modifier whenNotFreeze() {
require(freeze[msg.sender]==0);
_;
}
function imaxChainToken() public {
totalSupply = INITIAL_SUPPLY; // Set the total supply
balances[msg.sender] = INITIAL_SUPPLY; // Creator address is assigned all
Transfer(0x0, msg.sender, INITIAL_SUPPLY);
}
function transfer(address _to, uint256 _value) whenNotPaused whenNotFreeze public returns (bool success) {
require(_to != address(this));
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = safeSubtract(balances[msg.sender], _value);
balances[_to] = safeAdd(balances[_to], _value);
Transfer(msg.sender, _to, _value);
return true;
}
function transferFrom(address _from, address _to, uint256 _value) whenNotPaused whenNotFreeze public returns (bool success) {
require(_to != address(this));
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = safeSubtract(balances[_from],_value);
balances[_to] = safeAdd(balances[_to],_value);
allowed[_from][msg.sender] = safeSubtract(allowed[_from][msg.sender],_value);
Transfer(_from, _to, _value);
return true;
}
function approve(address _spender, uint256 _value) whenNotFreeze public returns (bool success) {
require((_value == 0) || (allowed[msg.sender][_spender] == 0));
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) whenNotFreeze public returns (bool) {
allowed[msg.sender][_spender] = safeAdd(allowed[msg.sender][_spender],_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) whenNotFreeze public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = safeSubtract(oldValue,_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function updateFreeze(address account) onlyOwner public returns(bool success){
if (freeze[account]==0){
freeze[account]=1;
}else{
freeze[account]=0;
}
return true;
}
function freezeOf(address account) public view returns (uint256 status) {
return freeze[account];
}
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = safeSubtract(balances[burner],_value);
totalSupply = safeSubtract(totalSupply, _value);
Burn(burner, _value);
}
function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
//call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this.
//receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData)
//it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead.
if(!_spender.call(bytes4(bytes32(keccak256("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { revert(); }
return true;
}
} | Check if it is safe to add two numbers | function safeAdd(uint256 a, uint256 b) internal pure returns (uint256) {
uint c = a + b;
assert(c >= a && c >= b);
return c;
}
| 5,936,299 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.