file_name
stringlengths 71
779k
| comments
stringlengths 0
29.4k
| code_string
stringlengths 20
7.69M
| __index_level_0__
int64 2
17.2M
|
---|---|---|---|
// File: @openzeppelin/contracts/utils/math/SafeMath.sol
// OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol)
pragma solidity 0.8.11;
// 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;
}
}
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol)
pragma solidity ^0.8.0;
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721 is IERC165 {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `to`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address to, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `from` to `to` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 amount
) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/token/ERC20/extensions/IERC20Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// File: @openzeppelin/contracts/token/ERC20/ERC20.sol
// OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/ERC20.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin Contracts guidelines: functions revert
* instead returning `false` on failure. This behavior is nonetheless
* conventional and does not conflict with the expectations of ERC20
* applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The default value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5.05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address to, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_transfer(owner, to, 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}.
*
* NOTE: If `amount` is the maximum `uint256`, the allowance is not updated on
* `transferFrom`. This is semantically equivalent to an infinite approval.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
address owner = _msgSender();
_approve(owner, 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}.
*
* NOTE: Does not update the allowance if the current allowance
* is the maximum `uint256`.
*
* Requirements:
*
* - `from` and `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
* - the caller must have allowance for ``from``'s tokens of at least
* `amount`.
*/
function transferFrom(
address from,
address to,
uint256 amount
) public virtual override returns (bool) {
address spender = _msgSender();
_spendAllowance(from, spender, amount);
_transfer(from, to, 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) {
address owner = _msgSender();
_approve(owner, spender, _allowances[owner][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) {
address owner = _msgSender();
uint256 currentAllowance = _allowances[owner][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
unchecked {
_approve(owner, spender, currentAllowance - subtractedValue);
}
return true;
}
/**
* @dev Moves `amount` of tokens from `sender` to `recipient`.
*
* This internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `from` must have a balance of at least `amount`.
*/
function _transfer(
address from,
address to,
uint256 amount
) internal virtual {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(from, to, amount);
uint256 fromBalance = _balances[from];
require(fromBalance >= amount, "ERC20: transfer amount exceeds balance");
unchecked {
_balances[from] = fromBalance - amount;
}
_balances[to] += amount;
emit Transfer(from, to, amount);
_afterTokenTransfer(from, to, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(0), account, amount);
_afterTokenTransfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
uint256 accountBalance = _balances[account];
require(accountBalance >= amount, "ERC20: burn amount exceeds balance");
unchecked {
_balances[account] = accountBalance - amount;
}
_totalSupply -= amount;
emit Transfer(account, address(0), amount);
_afterTokenTransfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(
address owner,
address spender,
uint256 amount
) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Spend `amount` form the allowance of `owner` toward `spender`.
*
* Does not update the allowance amount in case of infinite allowance.
* Revert if not enough allowance is available.
*
* Might emit an {Approval} event.
*/
function _spendAllowance(
address owner,
address spender,
uint256 amount
) internal virtual {
uint256 currentAllowance = allowance(owner, spender);
if (currentAllowance != type(uint256).max) {
require(currentAllowance >= amount, "ERC20: insufficient allowance");
unchecked {
_approve(owner, spender, currentAllowance - amount);
}
}
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
/**
* @dev Hook that is called after any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* has been transferred to `to`.
* - when `from` is zero, `amount` tokens have been minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens have been burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _afterTokenTransfer(
address from,
address to,
uint256 amount
) internal virtual {}
}
// File: YieldBones.sol
pragma solidity 0.8.11;
interface IBone20 {
// updated_amount = (balanceOf(user) * base_rate * delta / rewardPeroid)
function updateRewardOnMint(address _user) external;
// called on transfer
function updateReward(address _from, address _to) external;
function getReward(address _to) external;
function burn(address _from, uint256 _amount) external;
function getTotalClaimable(address _user) external view returns(uint256);
}
contract YieldBones is IBone20, ERC20, Ownable {
using SafeMath for uint256;
//----Variable--------
uint256 constant public BASE_RATE = 10 * 10**18;
uint256 public rewardPeroid = 1 days;
// January 11, 2027 9:04:09 PM GMT+05:45
uint256 constant public END = 1799680749;
mapping(address => uint256) public rewards;
mapping(address => uint256) public lastUpdate;
address public dinoContract;
//----Event---
event RewardPaid(address indexed user, uint256 reward);
constructor(address _dino, uint256 _initialSupply) ERC20("YeildBones", "$BONES"){
dinoContract = _dino;
_mint(msg.sender, _initialSupply);
}
//----Pure-----
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
//-------User-------
///@notice called when NFT minting
/// updated_amount = (balanceOf(user) * base_rate * delta / rewardPeroid)
///@param _user address to give reward to
function updateRewardOnMint(address _user) external override {
require(msg.sender == address(dinoContract), "Can't call this");
uint256 time = min(block.timestamp, END);
uint256 timerUser = lastUpdate[_user];
if(timerUser == 0){
timerUser = time;
}
rewards[_user] = rewards[_user].add(IERC721(dinoContract).balanceOf(_user).mul(BASE_RATE.mul((time.sub(timerUser)))).div(rewardPeroid));
lastUpdate[_user] = time;
}
///@notice called on transfers that updates the reward time to the nft address receiving the nft
///@param _from from account
///@param _to to account
function updateReward(address _from, address _to) external override{
require(msg.sender == address(dinoContract));
uint256 time = min(block.timestamp, END);
uint256 timerFrom = lastUpdate[_from];
if (timerFrom > 0)
rewards[_from] += IERC721(dinoContract).balanceOf(_from).mul(BASE_RATE.mul((time.sub(timerFrom)))).div(rewardPeroid);
if (timerFrom != END)
lastUpdate[_from] = time;
if (_to != address(0)) {
uint256 timerTo = lastUpdate[_to];
if (timerTo > 0)
rewards[_to] += IERC721(dinoContract).balanceOf(_to).mul(BASE_RATE.mul((time.sub(timerTo)))).div(rewardPeroid);
if (timerTo != END)
lastUpdate[_to] = time;
}
}
///@notice get the reward for every user
///@param _to address that withdraw rewards to
function getReward(address _to) external override {
require(msg.sender == address(dinoContract));
uint256 reward = rewards[_to];
if (reward > 0) {
rewards[_to] = 0;
_mint(_to, reward);
emit RewardPaid(_to, reward);
}
}
///@notice get the total claimable token for any users
///@param _user user address for checking the claimable rewards
function getTotalClaimable(address _user) external override view returns(uint256) {
uint256 time = min(block.timestamp, END);
uint256 timerUser = lastUpdate[_user];
if(timerUser == 0){
timerUser = time;
}
uint256 pending = IERC721(dinoContract).balanceOf(_user).mul(BASE_RATE.mul((time.sub(timerUser)))).div(rewardPeroid);
return rewards[_user] + pending;
}
//---Admin-------
///@notice update reward peroid
///@param _newPeroid new peroid to distribute the token on in seconds
function updateRewardPeroid(uint256 _newPeroid) external onlyOwner{
rewardPeroid = _newPeroid;
}
///@notice update dino nft contract
///@param _newDino new dino nft contract
function updateDinoContract(address _newDino) external onlyOwner{
dinoContract = _newDino;
}
//---Verbose----
function burn(address _from, uint256 _amount) external override{
require(msg.sender == address(dinoContract));
_burn(_from, _amount);
}
}
|
get the reward for every user _to address that withdraw rewards to
|
function getReward(address _to) external override {
require(msg.sender == address(dinoContract));
uint256 reward = rewards[_to];
if (reward > 0) {
rewards[_to] = 0;
_mint(_to, reward);
emit RewardPaid(_to, reward);
}
}
| 523,420 |
./partial_match/1/0xf05Dc4B57fB161015FDDA8749A8c56C6e3D962Ff/sources/KFICrowdsale.sol
|
The `escapeHatch()` should only be called as a last resort if a security issue is uncovered or something unexpected happened _token to transfer, use 0x0 for ether Logic for ether
|
function escapeHatch(address _token, address payable _escapeHatchDestination) external onlyOwner nonReentrant {
require(_escapeHatchDestination != address(0x0));
uint256 balance;
if (_token == address(0x0)) {
balance = address(this).balance;
_escapeHatchDestination.transfer(balance);
emit EscapeHatchCalled(_token, balance);
return;
}
balance = token.balanceOf(address(this));
token.safeTransfer(_escapeHatchDestination, balance);
emit EscapeHatchCalled(_token, balance);
}
event EscapeHatchCalled(address token, uint256 amount);
| 2,797,295 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.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 ECDSAUpgradeable {
/**
* @dev Returns the address that signed a hashed message (`hash`) with
* `signature`. This address can then be used for verification purposes.
*
* The `ecrecover` EVM opcode allows for malleable (non-unique) signatures:
* this function rejects them by requiring the `s` value to be in the lower
* half order, and the `v` value to be either 27 or 28.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Check the signature length
if (signature.length != 65) {
revert("ECDSA: invalid signature length");
}
// 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)))
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// 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.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* replicates the behavior of the
* https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`]
* JSON-RPC method.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal initializer {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version) internal initializer {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
_getChainId(),
address(this)
)
);
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal virtual view returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal virtual view returns (bytes32) {
return _HASHED_VERSION;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.5 <0.8.0;
import "../token/ERC20/ERC20Upgradeable.sol";
import "./IERC20PermitUpgradeable.sol";
import "../cryptography/ECDSAUpgradeable.sol";
import "../utils/CountersUpgradeable.sol";
import "./EIP712Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20PermitUpgradeable is Initializable, ERC20Upgradeable, IERC20PermitUpgradeable, EIP712Upgradeable {
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping (address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal initializer {
__Context_init_unchained();
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory name) internal initializer {
_PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_nonces[owner].current(),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSAUpgradeable.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_nonces[owner].increment();
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165CheckerUpgradeable {
// 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 a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) {
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
// success determines whether the staticcall succeeded and result determines
// whether the contract at account indicates support of _interfaceId
(bool success, bool result) = _callERC165SupportsInterface(account, interfaceId);
return (success && result);
}
/**
* @notice Calls the function with selector 0x01ffc9a7 (ERC165) and suppresses throw
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return success true if the STATICCALL succeeded, false otherwise
* @return result true if the STATICCALL succeeded and the contract at account
* indicates support of the interface with identifier interfaceId, false otherwise
*/
function _callERC165SupportsInterface(address account, bytes4 interfaceId)
private
view
returns (bool, bool)
{
bytes memory encodedParams = abi.encodeWithSelector(_INTERFACE_ID_ERC165, interfaceId);
(bool success, bytes memory result) = account.staticcall{ gas: 30000 }(encodedParams);
if (result.length < 32) return (false, false);
return (success, abi.decode(result, (bool)));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820RegistryUpgradeable {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as ``account``'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 _interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 _interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../utils/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal virtual {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20Upgradeable {
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20Upgradeable token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20Upgradeable token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20Upgradeable token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20Upgradeable token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
import "../../introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(address indexed from, address indexed to, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(address indexed owner, address indexed operator, bool approved);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(address from, address to, uint256 tokenId) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes calldata data) external;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMathUpgradeable.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library CountersUpgradeable {
using SafeMathUpgradeable for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuardUpgradeable is Initializable {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
function __ReentrancyGuard_init() internal initializer {
__ReentrancyGuard_init_unchained();
}
function __ReentrancyGuard_init_unchained() internal initializer {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <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 SafeCastUpgradeable {
/**
* @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 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 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);
}
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity >=0.6.0 <0.8.0;
import "./external/openzeppelin/OpenZeppelinSafeMath_V3_3_0.sol";
/**
* @author Brendan Asselstine
* @notice Provides basic fixed point math calculations.
*
* This library calculates integer fractions by scaling values by 1e18 then performing standard integer math.
*/
library FixedPoint {
using OpenZeppelinSafeMath_V3_3_0 for uint256;
// The scale to use for fixed point numbers. Same as Ether for simplicity.
uint256 internal constant SCALE = 1e18;
/**
* Calculates a Fixed18 mantissa given the numerator and denominator
*
* The mantissa = (numerator * 1e18) / denominator
*
* @param numerator The mantissa numerator
* @param denominator The mantissa denominator
* @return The mantissa of the fraction
*/
function calculateMantissa(uint256 numerator, uint256 denominator) internal pure returns (uint256) {
uint256 mantissa = numerator.mul(SCALE);
mantissa = mantissa.div(denominator);
return mantissa;
}
/**
* Multiplies a Fixed18 number by an integer.
*
* @param b The whole integer to multiply
* @param mantissa The Fixed18 number
* @return An integer that is the result of multiplying the params.
*/
function multiplyUintByMantissa(uint256 b, uint256 mantissa) internal pure returns (uint256) {
uint256 result = mantissa.mul(b);
result = result.div(SCALE);
return result;
}
/**
* Divides an integer by a fixed point 18 mantissa
*
* @param dividend The integer to divide
* @param mantissa The fixed point 18 number to serve as the divisor
* @return An integer that is the result of dividing an integer by a fixed point 18 mantissa
*/
function divideUintByMantissa(uint256 dividend, uint256 mantissa) internal pure returns (uint256) {
uint256 result = SCALE.mul(dividend);
result = result.div(mantissa);
return result;
}
}
// SPDX-License-Identifier: MIT
// NOTE: Copied from OpenZeppelin Contracts version 3.3.0
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 OpenZeppelinSafeMath_V3_3_0 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: 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.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/introspection/IERC1820RegistryUpgradeable.sol";
library Constants {
IERC1820RegistryUpgradeable public constant REGISTRY = IERC1820RegistryUpgradeable(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// keccak256("ERC777TokensSender")
bytes32 public constant TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 public constant TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// keccak256(abi.encodePacked("ERC1820_ACCEPT_MAGIC"));
bytes32 public constant ACCEPT_MAGIC =
0xa2ef4600d742022d532d4747cb3547474667d6f13804902513b2ec01c848f4b4;
bytes4 public constant ERC165_INTERFACE_ID_ERC165 = 0x01ffc9a7;
bytes4 public constant ERC165_INTERFACE_ID_ERC721 = 0x80ac58cd;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
interface ICompLike is IERC20Upgradeable {
function getCurrentVotes(address account) external view returns (uint96);
function delegate(address delegatee) external;
}
pragma solidity >=0.6.0 <0.7.0;
// solium-disable security/no-inline-assembly
// solium-disable security/no-low-level-calls
contract ProxyFactory {
event ProxyCreated(address proxy);
function deployMinimal(address _logic, bytes memory _data) public returns (address proxy) {
// Adapted from https://github.com/optionality/clone-factory/blob/32782f82dfc5a00d103a7e61a17a5dedbd1e8e9d/contracts/CloneFactory.sol
bytes20 targetBytes = bytes20(_logic);
assembly {
let clone := mload(0x40)
mstore(clone, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000)
mstore(add(clone, 0x14), targetBytes)
mstore(add(clone, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000)
proxy := create(0, clone, 0x37)
}
emit ProxyCreated(address(proxy));
if(_data.length > 0) {
(bool success,) = proxy.call(_data);
require(success, "ProxyFactory/constructor-call-failed");
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/introspection/ERC165CheckerUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@pooltogether/fixed-point/contracts/FixedPoint.sol";
import "../external/compound/ICompLike.sol";
import "../registry/RegistryInterface.sol";
import "../reserve/ReserveInterface.sol";
import "../token/TokenListenerInterface.sol";
import "../token/TokenListenerLibrary.sol";
import "../token/ControlledToken.sol";
import "../token/TokenControllerInterface.sol";
import "../utils/MappedSinglyLinkedList.sol";
import "./PrizePoolInterface.sol";
/// @title Escrows assets and deposits them into a yield source. Exposes interest to Prize Strategy. Users deposit and withdraw from this contract to participate in Prize Pool.
/// @notice Accounting is managed using Controlled Tokens, whose mint and burn functions can only be called by this contract.
/// @dev Must be inherited to provide specific yield-bearing asset control, such as Compound cTokens
abstract contract PrizePool is PrizePoolInterface, OwnableUpgradeable, ReentrancyGuardUpgradeable, TokenControllerInterface {
using SafeMathUpgradeable for uint256;
using SafeCastUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping;
using ERC165CheckerUpgradeable for address;
/// @dev Emitted when an instance is initialized
event Initialized(
address reserveRegistry,
uint256 maxExitFeeMantissa,
uint256 maxTimelockDuration
);
/// @dev Event emitted when controlled token is added
event ControlledTokenAdded(
ControlledTokenInterface indexed token
);
/// @dev Emitted when reserve is captured.
event ReserveFeeCaptured(
uint256 amount
);
event AwardCaptured(
uint256 amount
);
/// @dev Event emitted when assets are deposited
event Deposited(
address indexed operator,
address indexed to,
address indexed token,
uint256 amount,
address referrer
);
/// @dev Event emitted when timelocked funds are re-deposited
event TimelockDeposited(
address indexed operator,
address indexed to,
address indexed token,
uint256 amount
);
/// @dev Event emitted when interest is awarded to a winner
event Awarded(
address indexed winner,
address indexed token,
uint256 amount
);
/// @dev Event emitted when external ERC20s are awarded to a winner
event AwardedExternalERC20(
address indexed winner,
address indexed token,
uint256 amount
);
/// @dev Event emitted when external ERC20s are transferred out
event TransferredExternalERC20(
address indexed to,
address indexed token,
uint256 amount
);
/// @dev Event emitted when external ERC721s are awarded to a winner
event AwardedExternalERC721(
address indexed winner,
address indexed token,
uint256[] tokenIds
);
/// @dev Event emitted when assets are withdrawn instantly
event InstantWithdrawal(
address indexed operator,
address indexed from,
address indexed token,
uint256 amount,
uint256 redeemed,
uint256 exitFee
);
/// @dev Event emitted upon a withdrawal with timelock
event TimelockedWithdrawal(
address indexed operator,
address indexed from,
address indexed token,
uint256 amount,
uint256 unlockTimestamp
);
event ReserveWithdrawal(
address indexed to,
uint256 amount
);
/// @dev Event emitted when timelocked funds are swept back to a user
event TimelockedWithdrawalSwept(
address indexed operator,
address indexed from,
uint256 amount,
uint256 redeemed
);
/// @dev Event emitted when the Liquidity Cap is set
event LiquidityCapSet(
uint256 liquidityCap
);
/// @dev Event emitted when the Credit plan is set
event CreditPlanSet(
address token,
uint128 creditLimitMantissa,
uint128 creditRateMantissa
);
/// @dev Event emitted when the Prize Strategy is set
event PrizeStrategySet(
address indexed prizeStrategy
);
/// @dev Emitted when credit is minted
event CreditMinted(
address indexed user,
address indexed token,
uint256 amount
);
/// @dev Emitted when credit is burned
event CreditBurned(
address indexed user,
address indexed token,
uint256 amount
);
struct CreditPlan {
uint128 creditLimitMantissa;
uint128 creditRateMantissa;
}
struct CreditBalance {
uint192 balance;
uint32 timestamp;
bool initialized;
}
/// @dev Reserve to which reserve fees are sent
RegistryInterface public reserveRegistry;
/// @dev A linked list of all the controlled tokens
MappedSinglyLinkedList.Mapping internal _tokens;
/// @dev The Prize Strategy that this Prize Pool is bound to.
TokenListenerInterface public prizeStrategy;
/// @dev The maximum possible exit fee fraction as a fixed point 18 number.
/// For example, if the maxExitFeeMantissa is "0.1 ether", then the maximum exit fee for a withdrawal of 100 Dai will be 10 Dai
uint256 public maxExitFeeMantissa;
/// @dev The maximum possible timelock duration for a timelocked withdrawal (in seconds).
uint256 public maxTimelockDuration;
/// @dev The total funds that are timelocked.
uint256 public timelockTotalSupply;
/// @dev The total funds that have been allocated to the reserve
uint256 public reserveTotalSupply;
/// @dev The total amount of funds that the prize pool can hold.
uint256 public liquidityCap;
/// @dev the The awardable balance
uint256 internal _currentAwardBalance;
/// @dev The timelocked balances for each user
mapping(address => uint256) internal _timelockBalances;
/// @dev The unlock timestamps for each user
mapping(address => uint256) internal _unlockTimestamps;
/// @dev Stores the credit plan for each token.
mapping(address => CreditPlan) internal _tokenCreditPlans;
/// @dev Stores each users balance of credit per token.
mapping(address => mapping(address => CreditBalance)) internal _tokenCreditBalances;
/// @notice Initializes the Prize Pool
/// @param _controlledTokens Array of ControlledTokens that are controlled by this Prize Pool.
/// @param _maxExitFeeMantissa The maximum exit fee size
/// @param _maxTimelockDuration The maximum length of time the withdraw timelock
function initialize (
RegistryInterface _reserveRegistry,
ControlledTokenInterface[] memory _controlledTokens,
uint256 _maxExitFeeMantissa,
uint256 _maxTimelockDuration
)
public
initializer
{
require(address(_reserveRegistry) != address(0), "PrizePool/reserveRegistry-not-zero");
_tokens.initialize();
for (uint256 i = 0; i < _controlledTokens.length; i++) {
_addControlledToken(_controlledTokens[i]);
}
__Ownable_init();
__ReentrancyGuard_init();
_setLiquidityCap(uint256(-1));
reserveRegistry = _reserveRegistry;
maxExitFeeMantissa = _maxExitFeeMantissa;
maxTimelockDuration = _maxTimelockDuration;
emit Initialized(
address(_reserveRegistry),
maxExitFeeMantissa,
maxTimelockDuration
);
}
/// @dev Returns the address of the underlying ERC20 asset
/// @return The address of the asset
function token() external override view returns (address) {
return address(_token());
}
/// @dev Returns the total underlying balance of all assets. This includes both principal and interest.
/// @return The underlying balance of assets
function balance() external returns (uint256) {
return _balance();
}
/// @dev Checks with the Prize Pool if a specific token type may be awarded as an external prize
/// @param _externalToken The address of the token to check
/// @return True if the token may be awarded, false otherwise
function canAwardExternal(address _externalToken) external view returns (bool) {
return _canAwardExternal(_externalToken);
}
/// @notice Deposits timelocked tokens for a user back into the Prize Pool as another asset.
/// @param to The address receiving the tokens
/// @param amount The amount of timelocked assets to re-deposit
/// @param controlledToken The type of token to be minted in exchange (i.e. tickets or sponsorship)
function timelockDepositTo(
address to,
uint256 amount,
address controlledToken
)
external
onlyControlledToken(controlledToken)
canAddLiquidity(amount)
nonReentrant
{
address operator = _msgSender();
_mint(to, amount, controlledToken, address(0));
_timelockBalances[operator] = _timelockBalances[operator].sub(amount);
timelockTotalSupply = timelockTotalSupply.sub(amount);
emit TimelockDeposited(operator, to, controlledToken, amount);
}
/// @notice Deposit assets into the Prize Pool in exchange for tokens
/// @param to The address receiving the newly minted tokens
/// @param amount The amount of assets to deposit
/// @param controlledToken The address of the type of token the user is minting
/// @param referrer The referrer of the deposit
function depositTo(
address to,
uint256 amount,
address controlledToken,
address referrer
)
external override
onlyControlledToken(controlledToken)
canAddLiquidity(amount)
nonReentrant
{
address operator = _msgSender();
_mint(to, amount, controlledToken, referrer);
_token().safeTransferFrom(operator, address(this), amount);
_supply(amount);
emit Deposited(operator, to, controlledToken, amount, referrer);
}
/// @notice Withdraw assets from the Prize Pool instantly. A fairness fee may be charged for an early exit.
/// @param from The address to redeem tokens from.
/// @param amount The amount of tokens to redeem for assets.
/// @param controlledToken The address of the token to redeem (i.e. ticket or sponsorship)
/// @param maximumExitFee The maximum exit fee the caller is willing to pay. This should be pre-calculated by the calculateExitFee() fxn.
/// @return The actual exit fee paid
function withdrawInstantlyFrom(
address from,
uint256 amount,
address controlledToken,
uint256 maximumExitFee
)
external override
nonReentrant
onlyControlledToken(controlledToken)
returns (uint256)
{
(uint256 exitFee, uint256 burnedCredit) = _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount);
require(exitFee <= maximumExitFee, "PrizePool/exit-fee-exceeds-user-maximum");
// burn the credit
_burnCredit(from, controlledToken, burnedCredit);
// burn the tickets
ControlledToken(controlledToken).controllerBurnFrom(_msgSender(), from, amount);
// redeem the tickets less the fee
uint256 amountLessFee = amount.sub(exitFee);
uint256 redeemed = _redeem(amountLessFee);
_token().safeTransfer(from, redeemed);
emit InstantWithdrawal(_msgSender(), from, controlledToken, amount, redeemed, exitFee);
return exitFee;
}
/// @notice Limits the exit fee to the maximum as hard-coded into the contract
/// @param withdrawalAmount The amount that is attempting to be withdrawn
/// @param exitFee The exit fee to check against the limit
/// @return The passed exit fee if it is less than the maximum, otherwise the maximum fee is returned.
function _limitExitFee(uint256 withdrawalAmount, uint256 exitFee) internal view returns (uint256) {
uint256 maxFee = FixedPoint.multiplyUintByMantissa(withdrawalAmount, maxExitFeeMantissa);
if (exitFee > maxFee) {
exitFee = maxFee;
}
return exitFee;
}
/// @notice Withdraw assets from the Prize Pool by placing them into the timelock.
/// The timelock is used to ensure that the tickets have contributed their fair share of the prize.
/// @dev Note that if the user has previously timelocked funds then this contract will try to sweep them.
/// If the existing timelocked funds are still locked, then the incoming
/// balance is added to their existing balance and the new timelock unlock timestamp will overwrite the old one.
/// @param from The address to withdraw from
/// @param amount The amount to withdraw
/// @param controlledToken The type of token being withdrawn
/// @return The timestamp from which the funds can be swept
function withdrawWithTimelockFrom(
address from,
uint256 amount,
address controlledToken
)
external override
nonReentrant
onlyControlledToken(controlledToken)
returns (uint256)
{
uint256 blockTime = _currentTime();
(uint256 lockDuration, uint256 burnedCredit) = _calculateTimelockDuration(from, controlledToken, amount);
uint256 unlockTimestamp = blockTime.add(lockDuration);
_burnCredit(from, controlledToken, burnedCredit);
ControlledToken(controlledToken).controllerBurnFrom(_msgSender(), from, amount);
_mintTimelock(from, amount, unlockTimestamp);
emit TimelockedWithdrawal(_msgSender(), from, controlledToken, amount, unlockTimestamp);
// return the block at which the funds will be available
return unlockTimestamp;
}
/// @notice Adds to a user's timelock balance. It will attempt to sweep before updating the balance.
/// Note that this will overwrite the previous unlock timestamp.
/// @param user The user whose timelock balance should increase
/// @param amount The amount to increase by
/// @param timestamp The new unlock timestamp
function _mintTimelock(address user, uint256 amount, uint256 timestamp) internal {
// Sweep the old balance, if any
address[] memory users = new address[](1);
users[0] = user;
_sweepTimelockBalances(users);
timelockTotalSupply = timelockTotalSupply.add(amount);
_timelockBalances[user] = _timelockBalances[user].add(amount);
_unlockTimestamps[user] = timestamp;
// if the funds should already be unlocked
if (timestamp <= _currentTime()) {
_sweepTimelockBalances(users);
}
}
/// @notice Updates the Prize Strategy when tokens are transferred between holders.
/// @param from The address the tokens are being transferred from (0 if minting)
/// @param to The address the tokens are being transferred to (0 if burning)
/// @param amount The amount of tokens being trasferred
function beforeTokenTransfer(address from, address to, uint256 amount) external override onlyControlledToken(msg.sender) {
if (from != address(0)) {
uint256 fromBeforeBalance = IERC20Upgradeable(msg.sender).balanceOf(from);
// first accrue credit for their old balance
uint256 newCreditBalance = _calculateCreditBalance(from, msg.sender, fromBeforeBalance, 0);
if (from != to) {
// if they are sending funds to someone else, we need to limit their accrued credit to their new balance
newCreditBalance = _applyCreditLimit(msg.sender, fromBeforeBalance.sub(amount), newCreditBalance);
}
_updateCreditBalance(from, msg.sender, newCreditBalance);
}
if (to != address(0) && to != from) {
_accrueCredit(to, msg.sender, IERC20Upgradeable(msg.sender).balanceOf(to), 0);
}
// if we aren't minting
if (from != address(0) && address(prizeStrategy) != address(0)) {
prizeStrategy.beforeTokenTransfer(from, to, amount, msg.sender);
}
}
/// @notice Returns the balance that is available to award.
/// @dev captureAwardBalance() should be called first
/// @return The total amount of assets to be awarded for the current prize
function awardBalance() external override view returns (uint256) {
return _currentAwardBalance;
}
/// @notice Captures any available interest as award balance.
/// @dev This function also captures the reserve fees.
/// @return The total amount of assets to be awarded for the current prize
function captureAwardBalance() external override nonReentrant returns (uint256) {
uint256 tokenTotalSupply = _tokenTotalSupply();
// it's possible for the balance to be slightly less due to rounding errors in the underlying yield source
uint256 currentBalance = _balance();
uint256 totalInterest = (currentBalance > tokenTotalSupply) ? currentBalance.sub(tokenTotalSupply) : 0;
uint256 unaccountedPrizeBalance = (totalInterest > _currentAwardBalance) ? totalInterest.sub(_currentAwardBalance) : 0;
if (unaccountedPrizeBalance > 0) {
uint256 reserveFee = calculateReserveFee(unaccountedPrizeBalance);
if (reserveFee > 0) {
reserveTotalSupply = reserveTotalSupply.add(reserveFee);
unaccountedPrizeBalance = unaccountedPrizeBalance.sub(reserveFee);
emit ReserveFeeCaptured(reserveFee);
}
_currentAwardBalance = _currentAwardBalance.add(unaccountedPrizeBalance);
emit AwardCaptured(unaccountedPrizeBalance);
}
return _currentAwardBalance;
}
function withdrawReserve(address to) external override onlyReserve returns (uint256) {
uint256 amount = reserveTotalSupply;
reserveTotalSupply = 0;
uint256 redeemed = _redeem(amount);
_token().safeTransfer(address(to), redeemed);
emit ReserveWithdrawal(to, amount);
return redeemed;
}
/// @notice Called by the prize strategy to award prizes.
/// @dev The amount awarded must be less than the awardBalance()
/// @param to The address of the winner that receives the award
/// @param amount The amount of assets to be awarded
/// @param controlledToken The address of the asset token being awarded
function award(
address to,
uint256 amount,
address controlledToken
)
external override
onlyPrizeStrategy
onlyControlledToken(controlledToken)
{
if (amount == 0) {
return;
}
require(amount <= _currentAwardBalance, "PrizePool/award-exceeds-avail");
_currentAwardBalance = _currentAwardBalance.sub(amount);
_mint(to, amount, controlledToken, address(0));
uint256 extraCredit = _calculateEarlyExitFeeNoCredit(controlledToken, amount);
_accrueCredit(to, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(to), extraCredit);
emit Awarded(to, controlledToken, amount);
}
/// @notice Called by the Prize-Strategy to transfer out external ERC20 tokens
/// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything.
/// @param to The address of the winner that receives the award
/// @param amount The amount of external assets to be awarded
/// @param externalToken The address of the external asset token being awarded
function transferExternalERC20(
address to,
address externalToken,
uint256 amount
)
external override
onlyPrizeStrategy
{
if (_transferOut(to, externalToken, amount)) {
emit TransferredExternalERC20(to, externalToken, amount);
}
}
/// @notice Called by the Prize-Strategy to award external ERC20 prizes
/// @dev Used to award any arbitrary tokens held by the Prize Pool
/// @param to The address of the winner that receives the award
/// @param amount The amount of external assets to be awarded
/// @param externalToken The address of the external asset token being awarded
function awardExternalERC20(
address to,
address externalToken,
uint256 amount
)
external override
onlyPrizeStrategy
{
if (_transferOut(to, externalToken, amount)) {
emit AwardedExternalERC20(to, externalToken, amount);
}
}
function _transferOut(
address to,
address externalToken,
uint256 amount
)
internal
returns (bool)
{
require(_canAwardExternal(externalToken), "PrizePool/invalid-external-token");
if (amount == 0) {
return false;
}
IERC20Upgradeable(externalToken).safeTransfer(to, amount);
return true;
}
/// @notice Called to mint controlled tokens. Ensures that token listener callbacks are fired.
/// @param to The user who is receiving the tokens
/// @param amount The amount of tokens they are receiving
/// @param controlledToken The token that is going to be minted
/// @param referrer The user who referred the minting
function _mint(address to, uint256 amount, address controlledToken, address referrer) internal {
if (address(prizeStrategy) != address(0)) {
prizeStrategy.beforeTokenMint(to, amount, controlledToken, referrer);
}
ControlledToken(controlledToken).controllerMint(to, amount);
}
/// @notice Called by the prize strategy to award external ERC721 prizes
/// @dev Used to award any arbitrary NFTs held by the Prize Pool
/// @param to The address of the winner that receives the award
/// @param externalToken The address of the external NFT token being awarded
/// @param tokenIds An array of NFT Token IDs to be transferred
function awardExternalERC721(
address to,
address externalToken,
uint256[] calldata tokenIds
)
external override
onlyPrizeStrategy
{
require(_canAwardExternal(externalToken), "PrizePool/invalid-external-token");
if (tokenIds.length == 0) {
return;
}
for (uint256 i = 0; i < tokenIds.length; i++) {
IERC721Upgradeable(externalToken).transferFrom(address(this), to, tokenIds[i]);
}
emit AwardedExternalERC721(to, externalToken, tokenIds);
}
/// @notice Calculates the reserve portion of the given amount of funds. If there is no reserve address, the portion will be zero.
/// @param amount The prize amount
/// @return The size of the reserve portion of the prize
function calculateReserveFee(uint256 amount) public view returns (uint256) {
ReserveInterface reserve = ReserveInterface(reserveRegistry.lookup());
if (address(reserve) == address(0)) {
return 0;
}
uint256 reserveRateMantissa = reserve.reserveRateMantissa(address(this));
if (reserveRateMantissa == 0) {
return 0;
}
return FixedPoint.multiplyUintByMantissa(amount, reserveRateMantissa);
}
/// @notice Sweep all timelocked balances and transfer unlocked assets to owner accounts
/// @param users An array of account addresses to sweep balances for
/// @return The total amount of assets swept from the Prize Pool
function sweepTimelockBalances(
address[] calldata users
)
external override
nonReentrant
returns (uint256)
{
return _sweepTimelockBalances(users);
}
/// @notice Sweep available timelocked balances to their owners. The full balances will be swept to the owners.
/// @param users An array of owner addresses
/// @return The total amount of assets swept from the Prize Pool
function _sweepTimelockBalances(
address[] memory users
)
internal
returns (uint256)
{
address operator = _msgSender();
uint256[] memory balances = new uint256[](users.length);
uint256 totalWithdrawal;
uint256 i;
for (i = 0; i < users.length; i++) {
address user = users[i];
if (_unlockTimestamps[user] <= _currentTime()) {
totalWithdrawal = totalWithdrawal.add(_timelockBalances[user]);
balances[i] = _timelockBalances[user];
delete _timelockBalances[user];
}
}
// if there is nothing to do, just quit
if (totalWithdrawal == 0) {
return 0;
}
timelockTotalSupply = timelockTotalSupply.sub(totalWithdrawal);
uint256 redeemed = _redeem(totalWithdrawal);
IERC20Upgradeable underlyingToken = IERC20Upgradeable(_token());
for (i = 0; i < users.length; i++) {
if (balances[i] > 0) {
delete _unlockTimestamps[users[i]];
uint256 shareMantissa = FixedPoint.calculateMantissa(balances[i], totalWithdrawal);
uint256 transferAmount = FixedPoint.multiplyUintByMantissa(redeemed, shareMantissa);
underlyingToken.safeTransfer(users[i], transferAmount);
emit TimelockedWithdrawalSwept(operator, users[i], balances[i], transferAmount);
}
}
return totalWithdrawal;
}
/// @notice Calculates a timelocked withdrawal duration and credit consumption.
/// @param from The user who is withdrawing
/// @param amount The amount the user is withdrawing
/// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship)
/// @return durationSeconds The duration of the timelock in seconds
function calculateTimelockDuration(
address from,
address controlledToken,
uint256 amount
)
external override
returns (
uint256 durationSeconds,
uint256 burnedCredit
)
{
return _calculateTimelockDuration(from, controlledToken, amount);
}
/// @dev Calculates a timelocked withdrawal duration and credit consumption.
/// @param from The user who is withdrawing
/// @param amount The amount the user is withdrawing
/// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship)
/// @return durationSeconds The duration of the timelock in seconds
/// @return burnedCredit The credit that was burned
function _calculateTimelockDuration(
address from,
address controlledToken,
uint256 amount
)
internal
returns (
uint256 durationSeconds,
uint256 burnedCredit
)
{
(uint256 exitFee, uint256 _burnedCredit) = _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount);
uint256 duration = _estimateCreditAccrualTime(controlledToken, amount, exitFee);
if (duration > maxTimelockDuration) {
duration = maxTimelockDuration;
}
return (duration, _burnedCredit);
}
/// @notice Calculates the early exit fee for the given amount
/// @param from The user who is withdrawing
/// @param controlledToken The type of collateral being withdrawn
/// @param amount The amount of collateral to be withdrawn
/// @return exitFee The exit fee
/// @return burnedCredit The user's credit that was burned
function calculateEarlyExitFee(
address from,
address controlledToken,
uint256 amount
)
external override
returns (
uint256 exitFee,
uint256 burnedCredit
)
{
return _calculateEarlyExitFeeLessBurnedCredit(from, controlledToken, amount);
}
/// @dev Calculates the early exit fee for the given amount
/// @param amount The amount of collateral to be withdrawn
/// @return Exit fee
function _calculateEarlyExitFeeNoCredit(address controlledToken, uint256 amount) internal view returns (uint256) {
return _limitExitFee(
amount,
FixedPoint.multiplyUintByMantissa(amount, _tokenCreditPlans[controlledToken].creditLimitMantissa)
);
}
/// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit.
/// @param _principal The principal amount on which interest is accruing
/// @param _interest The amount of interest that must accrue
/// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds.
function estimateCreditAccrualTime(
address _controlledToken,
uint256 _principal,
uint256 _interest
)
external override
view
returns (uint256 durationSeconds)
{
return _estimateCreditAccrualTime(
_controlledToken,
_principal,
_interest
);
}
/// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit
/// @param _principal The principal amount on which interest is accruing
/// @param _interest The amount of interest that must accrue
/// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds.
function _estimateCreditAccrualTime(
address _controlledToken,
uint256 _principal,
uint256 _interest
)
internal
view
returns (uint256 durationSeconds)
{
// interest = credit rate * principal * time
// => time = interest / (credit rate * principal)
uint256 accruedPerSecond = FixedPoint.multiplyUintByMantissa(_principal, _tokenCreditPlans[_controlledToken].creditRateMantissa);
if (accruedPerSecond == 0) {
return 0;
}
return _interest.div(accruedPerSecond);
}
/// @notice Burns a users credit.
/// @param user The user whose credit should be burned
/// @param credit The amount of credit to burn
function _burnCredit(address user, address controlledToken, uint256 credit) internal {
_tokenCreditBalances[controlledToken][user].balance = uint256(_tokenCreditBalances[controlledToken][user].balance).sub(credit).toUint128();
emit CreditBurned(user, controlledToken, credit);
}
/// @notice Accrues ticket credit for a user assuming their current balance is the passed balance. May burn credit if they exceed their limit.
/// @param user The user for whom to accrue credit
/// @param controlledToken The controlled token whose balance we are checking
/// @param controlledTokenBalance The balance to use for the user
/// @param extra Additional credit to be added
function _accrueCredit(address user, address controlledToken, uint256 controlledTokenBalance, uint256 extra) internal {
_updateCreditBalance(
user,
controlledToken,
_calculateCreditBalance(user, controlledToken, controlledTokenBalance, extra)
);
}
function _calculateCreditBalance(address user, address controlledToken, uint256 controlledTokenBalance, uint256 extra) internal view returns (uint256) {
uint256 newBalance;
CreditBalance storage creditBalance = _tokenCreditBalances[controlledToken][user];
if (!creditBalance.initialized) {
newBalance = 0;
} else {
uint256 credit = _calculateAccruedCredit(user, controlledToken, controlledTokenBalance);
newBalance = _applyCreditLimit(controlledToken, controlledTokenBalance, uint256(creditBalance.balance).add(credit).add(extra));
}
return newBalance;
}
function _updateCreditBalance(address user, address controlledToken, uint256 newBalance) internal {
uint256 oldBalance = _tokenCreditBalances[controlledToken][user].balance;
_tokenCreditBalances[controlledToken][user] = CreditBalance({
balance: newBalance.toUint128(),
timestamp: _currentTime().toUint32(),
initialized: true
});
if (oldBalance < newBalance) {
emit CreditMinted(user, controlledToken, newBalance.sub(oldBalance));
} else {
emit CreditBurned(user, controlledToken, oldBalance.sub(newBalance));
}
}
/// @notice Applies the credit limit to a credit balance. The balance cannot exceed the credit limit.
/// @param controlledToken The controlled token that the user holds
/// @param controlledTokenBalance The users ticket balance (used to calculate credit limit)
/// @param creditBalance The new credit balance to be checked
/// @return The users new credit balance. Will not exceed the credit limit.
function _applyCreditLimit(address controlledToken, uint256 controlledTokenBalance, uint256 creditBalance) internal view returns (uint256) {
uint256 creditLimit = FixedPoint.multiplyUintByMantissa(
controlledTokenBalance,
_tokenCreditPlans[controlledToken].creditLimitMantissa
);
if (creditBalance > creditLimit) {
creditBalance = creditLimit;
}
return creditBalance;
}
/// @notice Calculates the accrued interest for a user
/// @param user The user whose credit should be calculated.
/// @param controlledToken The controlled token that the user holds
/// @param controlledTokenBalance The user's current balance of the controlled tokens.
/// @return The credit that has accrued since the last credit update.
function _calculateAccruedCredit(address user, address controlledToken, uint256 controlledTokenBalance) internal view returns (uint256) {
uint256 userTimestamp = _tokenCreditBalances[controlledToken][user].timestamp;
if (!_tokenCreditBalances[controlledToken][user].initialized) {
return 0;
}
uint256 deltaTime = _currentTime().sub(userTimestamp);
uint256 creditPerSecond = FixedPoint.multiplyUintByMantissa(controlledTokenBalance, _tokenCreditPlans[controlledToken].creditRateMantissa);
return deltaTime.mul(creditPerSecond);
}
/// @notice Returns the credit balance for a given user. Not that this includes both minted credit and pending credit.
/// @param user The user whose credit balance should be returned
/// @return The balance of the users credit
function balanceOfCredit(address user, address controlledToken) external override onlyControlledToken(controlledToken) returns (uint256) {
_accrueCredit(user, controlledToken, IERC20Upgradeable(controlledToken).balanceOf(user), 0);
return _tokenCreditBalances[controlledToken][user].balance;
}
/// @notice Sets the rate at which credit accrues per second. The credit rate is a fixed point 18 number (like Ether).
/// @param _controlledToken The controlled token for whom to set the credit plan
/// @param _creditRateMantissa The credit rate to set. Is a fixed point 18 decimal (like Ether).
/// @param _creditLimitMantissa The credit limit to set. Is a fixed point 18 decimal (like Ether).
function setCreditPlanOf(
address _controlledToken,
uint128 _creditRateMantissa,
uint128 _creditLimitMantissa
)
external override
onlyControlledToken(_controlledToken)
onlyOwner
{
_tokenCreditPlans[_controlledToken] = CreditPlan({
creditLimitMantissa: _creditLimitMantissa,
creditRateMantissa: _creditRateMantissa
});
emit CreditPlanSet(_controlledToken, _creditLimitMantissa, _creditRateMantissa);
}
/// @notice Returns the credit rate of a controlled token
/// @param controlledToken The controlled token to retrieve the credit rates for
/// @return creditLimitMantissa The credit limit fraction. This number is used to calculate both the credit limit and early exit fee.
/// @return creditRateMantissa The credit rate. This is the amount of tokens that accrue per second.
function creditPlanOf(
address controlledToken
)
external override
view
returns (
uint128 creditLimitMantissa,
uint128 creditRateMantissa
)
{
creditLimitMantissa = _tokenCreditPlans[controlledToken].creditLimitMantissa;
creditRateMantissa = _tokenCreditPlans[controlledToken].creditRateMantissa;
}
/// @notice Calculate the early exit for a user given a withdrawal amount. The user's credit is taken into account.
/// @param from The user who is withdrawing
/// @param controlledToken The token they are withdrawing
/// @param amount The amount of funds they are withdrawing
/// @return earlyExitFee The additional exit fee that should be charged.
/// @return creditBurned The amount of credit that will be burned
function _calculateEarlyExitFeeLessBurnedCredit(
address from,
address controlledToken,
uint256 amount
)
internal
returns (
uint256 earlyExitFee,
uint256 creditBurned
)
{
uint256 controlledTokenBalance = IERC20Upgradeable(controlledToken).balanceOf(from);
require(controlledTokenBalance >= amount, "PrizePool/insuff-funds");
_accrueCredit(from, controlledToken, controlledTokenBalance, 0);
/*
The credit is used *last*. Always charge the fees up-front.
How to calculate:
Calculate their remaining exit fee. I.e. full exit fee of their balance less their credit.
If the exit fee on their withdrawal is greater than the remaining exit fee, then they'll have to pay the difference.
*/
// Determine available usable credit based on withdraw amount
uint256 remainingExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, controlledTokenBalance.sub(amount));
uint256 availableCredit;
if (_tokenCreditBalances[controlledToken][from].balance >= remainingExitFee) {
availableCredit = uint256(_tokenCreditBalances[controlledToken][from].balance).sub(remainingExitFee);
}
// Determine amount of credit to burn and amount of fees required
uint256 totalExitFee = _calculateEarlyExitFeeNoCredit(controlledToken, amount);
creditBurned = (availableCredit > totalExitFee) ? totalExitFee : availableCredit;
earlyExitFee = totalExitFee.sub(creditBurned);
return (earlyExitFee, creditBurned);
}
/// @notice Allows the Governor to set a cap on the amount of liquidity that he pool can hold
/// @param _liquidityCap The new liquidity cap for the prize pool
function setLiquidityCap(uint256 _liquidityCap) external override onlyOwner {
_setLiquidityCap(_liquidityCap);
}
function _setLiquidityCap(uint256 _liquidityCap) internal {
liquidityCap = _liquidityCap;
emit LiquidityCapSet(_liquidityCap);
}
/// @notice Adds a new controlled token
/// @param _controlledToken The controlled token to add. Cannot be a duplicate.
function _addControlledToken(ControlledTokenInterface _controlledToken) internal {
require(_controlledToken.controller() == this, "PrizePool/token-ctrlr-mismatch");
_tokens.addAddress(address(_controlledToken));
emit ControlledTokenAdded(_controlledToken);
}
/// @notice Sets the prize strategy of the prize pool. Only callable by the owner.
/// @param _prizeStrategy The new prize strategy
function setPrizeStrategy(TokenListenerInterface _prizeStrategy) external override onlyOwner {
_setPrizeStrategy(_prizeStrategy);
}
/// @notice Sets the prize strategy of the prize pool. Only callable by the owner.
/// @param _prizeStrategy The new prize strategy
function _setPrizeStrategy(TokenListenerInterface _prizeStrategy) internal {
require(address(_prizeStrategy) != address(0), "PrizePool/prizeStrategy-not-zero");
require(address(_prizeStrategy).supportsInterface(TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER), "PrizePool/prizeStrategy-invalid");
prizeStrategy = _prizeStrategy;
emit PrizeStrategySet(address(_prizeStrategy));
}
/// @notice An array of the Tokens controlled by the Prize Pool (ie. Tickets, Sponsorship)
/// @return An array of controlled token addresses
function tokens() external override view returns (address[] memory) {
return _tokens.addressArray();
}
/// @dev Gets the current time as represented by the current block
/// @return The timestamp of the current block
function _currentTime() internal virtual view returns (uint256) {
return block.timestamp;
}
/// @notice The timestamp at which an account's timelocked balance will be made available to sweep
/// @param user The address of an account with timelocked assets
/// @return The timestamp at which the locked assets will be made available
function timelockBalanceAvailableAt(address user) external override view returns (uint256) {
return _unlockTimestamps[user];
}
/// @notice The balance of timelocked assets for an account
/// @param user The address of an account with timelocked assets
/// @return The amount of assets that have been timelocked
function timelockBalanceOf(address user) external override view returns (uint256) {
return _timelockBalances[user];
}
/// @notice The total of all controlled tokens and timelock.
/// @return The current total of all tokens and timelock.
function accountedBalance() external override view returns (uint256) {
return _tokenTotalSupply();
}
/// @notice Delegate the votes for a Compound COMP-like token held by the prize pool
/// @param compLike The COMP-like token held by the prize pool that should be delegated
/// @param to The address to delegate to
function compLikeDelegate(ICompLike compLike, address to) external onlyOwner {
if (compLike.balanceOf(address(this)) > 0) {
compLike.delegate(to);
}
}
/// @notice The total of all controlled tokens and timelock.
/// @return The current total of all tokens and timelock.
function _tokenTotalSupply() internal view returns (uint256) {
uint256 total = timelockTotalSupply.add(reserveTotalSupply);
address currentToken = _tokens.start();
while (currentToken != address(0) && currentToken != _tokens.end()) {
total = total.add(IERC20Upgradeable(currentToken).totalSupply());
currentToken = _tokens.next(currentToken);
}
return total;
}
/// @dev Checks if the Prize Pool can receive liquidity based on the current cap
/// @param _amount The amount of liquidity to be added to the Prize Pool
/// @return True if the Prize Pool can receive the specified amount of liquidity
function _canAddLiquidity(uint256 _amount) internal view returns (bool) {
uint256 tokenTotalSupply = _tokenTotalSupply();
return (tokenTotalSupply.add(_amount) <= liquidityCap);
}
/// @dev Checks if a specific token is controlled by the Prize Pool
/// @param controlledToken The address of the token to check
/// @return True if the token is a controlled token, false otherwise
function _isControlled(address controlledToken) internal view returns (bool) {
return _tokens.contains(controlledToken);
}
/// @notice Determines whether the passed token can be transferred out as an external award.
/// @dev Different yield sources will hold the deposits as another kind of token: such a Compound's cToken. The
/// prize strategy should not be allowed to move those tokens.
/// @param _externalToken The address of the token to check
/// @return True if the token may be awarded, false otherwise
function _canAwardExternal(address _externalToken) internal virtual view returns (bool);
/// @notice Returns the ERC20 asset token used for deposits.
/// @return The ERC20 asset token
function _token() internal virtual view returns (IERC20Upgradeable);
/// @notice Returns the total balance (in asset tokens). This includes the deposits and interest.
/// @return The underlying balance of asset tokens
function _balance() internal virtual returns (uint256);
/// @notice Supplies asset tokens to the yield source.
/// @param mintAmount The amount of asset tokens to be supplied
function _supply(uint256 mintAmount) internal virtual;
/// @notice Redeems asset tokens from the yield source.
/// @param redeemAmount The amount of yield-bearing tokens to be redeemed
/// @return The actual amount of tokens that were redeemed.
function _redeem(uint256 redeemAmount) internal virtual returns (uint256);
/// @dev Function modifier to ensure usage of tokens controlled by the Prize Pool
/// @param controlledToken The address of the token to check
modifier onlyControlledToken(address controlledToken) {
require(_isControlled(controlledToken), "PrizePool/unknown-token");
_;
}
/// @dev Function modifier to ensure caller is the prize-strategy
modifier onlyPrizeStrategy() {
require(_msgSender() == address(prizeStrategy), "PrizePool/only-prizeStrategy");
_;
}
/// @dev Function modifier to ensure the deposit amount does not exceed the liquidity cap (if set)
modifier canAddLiquidity(uint256 _amount) {
require(_canAddLiquidity(_amount), "PrizePool/exceeds-liquidity-cap");
_;
}
modifier onlyReserve() {
ReserveInterface reserve = ReserveInterface(reserveRegistry.lookup());
require(address(reserve) == msg.sender, "PrizePool/only-reserve");
_;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "../token/TokenListenerInterface.sol";
import "../token/ControlledTokenInterface.sol";
/// @title Escrows assets and deposits them into a yield source. Exposes interest to Prize Strategy. Users deposit and withdraw from this contract to participate in Prize Pool.
/// @notice Accounting is managed using Controlled Tokens, whose mint and burn functions can only be called by this contract.
/// @dev Must be inherited to provide specific yield-bearing asset control, such as Compound cTokens
interface PrizePoolInterface {
/// @notice Deposit assets into the Prize Pool in exchange for tokens
/// @param to The address receiving the newly minted tokens
/// @param amount The amount of assets to deposit
/// @param controlledToken The address of the type of token the user is minting
/// @param referrer The referrer of the deposit
function depositTo(
address to,
uint256 amount,
address controlledToken,
address referrer
)
external;
/// @notice Withdraw assets from the Prize Pool instantly. A fairness fee may be charged for an early exit.
/// @param from The address to redeem tokens from.
/// @param amount The amount of tokens to redeem for assets.
/// @param controlledToken The address of the token to redeem (i.e. ticket or sponsorship)
/// @param maximumExitFee The maximum exit fee the caller is willing to pay. This should be pre-calculated by the calculateExitFee() fxn.
/// @return The actual exit fee paid
function withdrawInstantlyFrom(
address from,
uint256 amount,
address controlledToken,
uint256 maximumExitFee
) external returns (uint256);
/// @notice Withdraw assets from the Prize Pool by placing them into the timelock.
/// The timelock is used to ensure that the tickets have contributed their fair share of the prize.
/// @dev Note that if the user has previously timelocked funds then this contract will try to sweep them.
/// If the existing timelocked funds are still locked, then the incoming
/// balance is added to their existing balance and the new timelock unlock timestamp will overwrite the old one.
/// @param from The address to withdraw from
/// @param amount The amount to withdraw
/// @param controlledToken The type of token being withdrawn
/// @return The timestamp from which the funds can be swept
function withdrawWithTimelockFrom(
address from,
uint256 amount,
address controlledToken
) external returns (uint256);
function withdrawReserve(address to) external returns (uint256);
/// @notice Returns the balance that is available to award.
/// @dev captureAwardBalance() should be called first
/// @return The total amount of assets to be awarded for the current prize
function awardBalance() external view returns (uint256);
/// @notice Captures any available interest as award balance.
/// @dev This function also captures the reserve fees.
/// @return The total amount of assets to be awarded for the current prize
function captureAwardBalance() external returns (uint256);
/// @notice Called by the prize strategy to award prizes.
/// @dev The amount awarded must be less than the awardBalance()
/// @param to The address of the winner that receives the award
/// @param amount The amount of assets to be awarded
/// @param controlledToken The address of the asset token being awarded
function award(
address to,
uint256 amount,
address controlledToken
)
external;
/// @notice Called by the Prize-Strategy to transfer out external ERC20 tokens
/// @dev Used to transfer out tokens held by the Prize Pool. Could be liquidated, or anything.
/// @param to The address of the winner that receives the award
/// @param amount The amount of external assets to be awarded
/// @param externalToken The address of the external asset token being awarded
function transferExternalERC20(
address to,
address externalToken,
uint256 amount
)
external;
/// @notice Called by the Prize-Strategy to award external ERC20 prizes
/// @dev Used to award any arbitrary tokens held by the Prize Pool
/// @param to The address of the winner that receives the award
/// @param amount The amount of external assets to be awarded
/// @param externalToken The address of the external asset token being awarded
function awardExternalERC20(
address to,
address externalToken,
uint256 amount
)
external;
/// @notice Called by the prize strategy to award external ERC721 prizes
/// @dev Used to award any arbitrary NFTs held by the Prize Pool
/// @param to The address of the winner that receives the award
/// @param externalToken The address of the external NFT token being awarded
/// @param tokenIds An array of NFT Token IDs to be transferred
function awardExternalERC721(
address to,
address externalToken,
uint256[] calldata tokenIds
)
external;
/// @notice Sweep all timelocked balances and transfer unlocked assets to owner accounts
/// @param users An array of account addresses to sweep balances for
/// @return The total amount of assets swept from the Prize Pool
function sweepTimelockBalances(
address[] calldata users
)
external
returns (uint256);
/// @notice Calculates a timelocked withdrawal duration and credit consumption.
/// @param from The user who is withdrawing
/// @param amount The amount the user is withdrawing
/// @param controlledToken The type of collateral the user is withdrawing (i.e. ticket or sponsorship)
/// @return durationSeconds The duration of the timelock in seconds
function calculateTimelockDuration(
address from,
address controlledToken,
uint256 amount
)
external
returns (
uint256 durationSeconds,
uint256 burnedCredit
);
/// @notice Calculates the early exit fee for the given amount
/// @param from The user who is withdrawing
/// @param controlledToken The type of collateral being withdrawn
/// @param amount The amount of collateral to be withdrawn
/// @return exitFee The exit fee
/// @return burnedCredit The user's credit that was burned
function calculateEarlyExitFee(
address from,
address controlledToken,
uint256 amount
)
external
returns (
uint256 exitFee,
uint256 burnedCredit
);
/// @notice Estimates the amount of time it will take for a given amount of funds to accrue the given amount of credit.
/// @param _principal The principal amount on which interest is accruing
/// @param _interest The amount of interest that must accrue
/// @return durationSeconds The duration of time it will take to accrue the given amount of interest, in seconds.
function estimateCreditAccrualTime(
address _controlledToken,
uint256 _principal,
uint256 _interest
)
external
view
returns (uint256 durationSeconds);
/// @notice Returns the credit balance for a given user. Not that this includes both minted credit and pending credit.
/// @param user The user whose credit balance should be returned
/// @return The balance of the users credit
function balanceOfCredit(address user, address controlledToken) external returns (uint256);
/// @notice Sets the rate at which credit accrues per second. The credit rate is a fixed point 18 number (like Ether).
/// @param _controlledToken The controlled token for whom to set the credit plan
/// @param _creditRateMantissa The credit rate to set. Is a fixed point 18 decimal (like Ether).
/// @param _creditLimitMantissa The credit limit to set. Is a fixed point 18 decimal (like Ether).
function setCreditPlanOf(
address _controlledToken,
uint128 _creditRateMantissa,
uint128 _creditLimitMantissa
)
external;
/// @notice Returns the credit rate of a controlled token
/// @param controlledToken The controlled token to retrieve the credit rates for
/// @return creditLimitMantissa The credit limit fraction. This number is used to calculate both the credit limit and early exit fee.
/// @return creditRateMantissa The credit rate. This is the amount of tokens that accrue per second.
function creditPlanOf(
address controlledToken
)
external
view
returns (
uint128 creditLimitMantissa,
uint128 creditRateMantissa
);
/// @notice Allows the Governor to set a cap on the amount of liquidity that he pool can hold
/// @param _liquidityCap The new liquidity cap for the prize pool
function setLiquidityCap(uint256 _liquidityCap) external;
/// @notice Sets the prize strategy of the prize pool. Only callable by the owner.
/// @param _prizeStrategy The new prize strategy. Must implement TokenListenerInterface
function setPrizeStrategy(TokenListenerInterface _prizeStrategy) external;
/// @dev Returns the address of the underlying ERC20 asset
/// @return The address of the asset
function token() external view returns (address);
/// @notice An array of the Tokens controlled by the Prize Pool (ie. Tickets, Sponsorship)
/// @return An array of controlled token addresses
function tokens() external view returns (address[] memory);
/// @notice The timestamp at which an account's timelocked balance will be made available to sweep
/// @param user The address of an account with timelocked assets
/// @return The timestamp at which the locked assets will be made available
function timelockBalanceAvailableAt(address user) external view returns (uint256);
/// @notice The balance of timelocked assets for an account
/// @param user The address of an account with timelocked assets
/// @return The amount of assets that have been timelocked
function timelockBalanceOf(address user) external view returns (uint256);
/// @notice The total of all controlled tokens and timelock.
/// @return The current total of all tokens and timelock.
function accountedBalance() external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
import "./BeforeAwardListenerInterface.sol";
import "../Constants.sol";
import "./BeforeAwardListenerLibrary.sol";
abstract contract BeforeAwardListener is BeforeAwardListenerInterface {
function supportsInterface(bytes4 interfaceId) external override view returns (bool) {
return (
interfaceId == Constants.ERC165_INTERFACE_ID_ERC165 ||
interfaceId == BeforeAwardListenerLibrary.ERC165_INTERFACE_ID_BEFORE_AWARD_LISTENER
);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol";
/// @notice The interface for the Periodic Prize Strategy before award listener. This listener will be called immediately before the award is distributed.
interface BeforeAwardListenerInterface is IERC165Upgradeable {
/// @notice Called immediately before the award is distributed
function beforePrizePoolAwarded(uint256 randomNumber, uint256 prizePeriodStartedAt) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
library BeforeAwardListenerLibrary {
/*
* bytes4(keccak256('beforePrizePoolAwarded(uint256,uint256)')) == 0x4cdf9c3e
*/
bytes4 public constant ERC165_INTERFACE_ID_BEFORE_AWARD_LISTENER = 0x4cdf9c3e;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/SafeCastUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/introspection/ERC165CheckerUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol";
import "@pooltogether/pooltogether-rng-contracts/contracts/RNGInterface.sol";
import "@pooltogether/fixed-point/contracts/FixedPoint.sol";
import "../token/TokenListener.sol";
import "../token/TokenControllerInterface.sol";
import "../token/ControlledToken.sol";
import "../token/TicketInterface.sol";
import "../prize-pool/PrizePool.sol";
import "../Constants.sol";
import "./PeriodicPrizeStrategyListenerInterface.sol";
import "./PeriodicPrizeStrategyListenerLibrary.sol";
import "./BeforeAwardListener.sol";
/* solium-disable security/no-block-members */
abstract contract PeriodicPrizeStrategy is Initializable,
OwnableUpgradeable,
TokenListener {
using SafeMathUpgradeable for uint256;
using SafeCastUpgradeable for uint256;
using SafeERC20Upgradeable for IERC20Upgradeable;
using MappedSinglyLinkedList for MappedSinglyLinkedList.Mapping;
using AddressUpgradeable for address;
using ERC165CheckerUpgradeable for address;
uint256 internal constant ETHEREUM_BLOCK_TIME_ESTIMATE_MANTISSA = 13.4 ether;
event PrizePoolOpened(
address indexed operator,
uint256 indexed prizePeriodStartedAt
);
event RngRequestFailed();
event PrizePoolAwardStarted(
address indexed operator,
address indexed prizePool,
uint32 indexed rngRequestId,
uint32 rngLockBlock
);
event PrizePoolAwardCancelled(
address indexed operator,
address indexed prizePool,
uint32 indexed rngRequestId,
uint32 rngLockBlock
);
event PrizePoolAwarded(
address indexed operator,
uint256 randomNumber
);
event RngServiceUpdated(
RNGInterface indexed rngService
);
event TokenListenerUpdated(
TokenListenerInterface indexed tokenListener
);
event RngRequestTimeoutSet(
uint32 rngRequestTimeout
);
event PrizePeriodSecondsUpdated(
uint256 prizePeriodSeconds
);
event BeforeAwardListenerSet(
BeforeAwardListenerInterface indexed beforeAwardListener
);
event PeriodicPrizeStrategyListenerSet(
PeriodicPrizeStrategyListenerInterface indexed periodicPrizeStrategyListener
);
event ExternalErc721AwardAdded(
IERC721Upgradeable indexed externalErc721,
uint256[] tokenIds
);
event ExternalErc20AwardAdded(
IERC20Upgradeable indexed externalErc20
);
event ExternalErc721AwardRemoved(
IERC721Upgradeable indexed externalErc721Award
);
event ExternalErc20AwardRemoved(
IERC20Upgradeable indexed externalErc20Award
);
event Initialized(
uint256 prizePeriodStart,
uint256 prizePeriodSeconds,
PrizePool indexed prizePool,
TicketInterface ticket,
IERC20Upgradeable sponsorship,
RNGInterface rng,
IERC20Upgradeable[] externalErc20Awards
);
struct RngRequest {
uint32 id;
uint32 lockBlock;
uint32 requestedAt;
}
// Comptroller
TokenListenerInterface public tokenListener;
// Contract Interfaces
PrizePool public prizePool;
TicketInterface public ticket;
IERC20Upgradeable public sponsorship;
RNGInterface public rng;
// Current RNG Request
RngRequest internal rngRequest;
/// @notice RNG Request Timeout. In fact, this is really a "complete award" timeout.
/// If the rng completes the award can still be cancelled.
uint32 public rngRequestTimeout;
// Prize period
uint256 public prizePeriodSeconds;
uint256 public prizePeriodStartedAt;
// External tokens awarded as part of prize
MappedSinglyLinkedList.Mapping internal externalErc20s;
MappedSinglyLinkedList.Mapping internal externalErc721s;
// External NFT token IDs to be awarded
// NFT Address => TokenIds
mapping (IERC721Upgradeable => uint256[]) internal externalErc721TokenIds;
/// @notice A listener that is called before the prize is awarded
BeforeAwardListenerInterface public beforeAwardListener;
/// @notice A listener that is called after the prize is awarded
PeriodicPrizeStrategyListenerInterface public periodicPrizeStrategyListener;
/// @notice Initializes a new strategy
/// @param _prizePeriodStart The starting timestamp of the prize period.
/// @param _prizePeriodSeconds The duration of the prize period in seconds
/// @param _prizePool The prize pool to award
/// @param _ticket The ticket to use to draw winners
/// @param _sponsorship The sponsorship token
/// @param _rng The RNG service to use
function initialize (
uint256 _prizePeriodStart,
uint256 _prizePeriodSeconds,
PrizePool _prizePool,
TicketInterface _ticket,
IERC20Upgradeable _sponsorship,
RNGInterface _rng,
IERC20Upgradeable[] memory externalErc20Awards
) public initializer {
require(address(_prizePool) != address(0), "PeriodicPrizeStrategy/prize-pool-not-zero");
require(address(_ticket) != address(0), "PeriodicPrizeStrategy/ticket-not-zero");
require(address(_sponsorship) != address(0), "PeriodicPrizeStrategy/sponsorship-not-zero");
require(address(_rng) != address(0), "PeriodicPrizeStrategy/rng-not-zero");
prizePool = _prizePool;
ticket = _ticket;
rng = _rng;
sponsorship = _sponsorship;
_setPrizePeriodSeconds(_prizePeriodSeconds);
__Ownable_init();
Constants.REGISTRY.setInterfaceImplementer(address(this), Constants.TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
externalErc20s.initialize();
for (uint256 i = 0; i < externalErc20Awards.length; i++) {
_addExternalErc20Award(externalErc20Awards[i]);
}
prizePeriodSeconds = _prizePeriodSeconds;
prizePeriodStartedAt = _prizePeriodStart;
externalErc721s.initialize();
// 30 min timeout
_setRngRequestTimeout(1800);
emit Initialized(
_prizePeriodStart,
_prizePeriodSeconds,
_prizePool,
_ticket,
_sponsorship,
_rng,
externalErc20Awards
);
emit PrizePoolOpened(_msgSender(), prizePeriodStartedAt);
}
function _distribute(uint256 randomNumber) internal virtual;
/// @notice Calculates and returns the currently accrued prize
/// @return The current prize size
function currentPrize() public view returns (uint256) {
return prizePool.awardBalance();
}
/// @notice Allows the owner to set the token listener
/// @param _tokenListener A contract that implements the token listener interface.
function setTokenListener(TokenListenerInterface _tokenListener) external onlyOwner requireAwardNotInProgress {
require(address(0) == address(_tokenListener) || address(_tokenListener).supportsInterface(TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER), "PeriodicPrizeStrategy/token-listener-invalid");
tokenListener = _tokenListener;
emit TokenListenerUpdated(tokenListener);
}
/// @notice Estimates the remaining blocks until the prize given a number of seconds per block
/// @param secondsPerBlockMantissa The number of seconds per block to use for the calculation. Should be a fixed point 18 number like Ether.
/// @return The estimated number of blocks remaining until the prize can be awarded.
function estimateRemainingBlocksToPrize(uint256 secondsPerBlockMantissa) public view returns (uint256) {
return FixedPoint.divideUintByMantissa(
_prizePeriodRemainingSeconds(),
secondsPerBlockMantissa
);
}
/// @notice Returns the number of seconds remaining until the prize can be awarded.
/// @return The number of seconds remaining until the prize can be awarded.
function prizePeriodRemainingSeconds() external view returns (uint256) {
return _prizePeriodRemainingSeconds();
}
/// @notice Returns the number of seconds remaining until the prize can be awarded.
/// @return The number of seconds remaining until the prize can be awarded.
function _prizePeriodRemainingSeconds() internal view returns (uint256) {
uint256 endAt = _prizePeriodEndAt();
uint256 time = _currentTime();
if (time > endAt) {
return 0;
}
return endAt.sub(time);
}
/// @notice Returns whether the prize period is over
/// @return True if the prize period is over, false otherwise
function isPrizePeriodOver() external view returns (bool) {
return _isPrizePeriodOver();
}
/// @notice Returns whether the prize period is over
/// @return True if the prize period is over, false otherwise
function _isPrizePeriodOver() internal view returns (bool) {
return _currentTime() >= _prizePeriodEndAt();
}
/// @notice Awards collateral as tickets to a user
/// @param user The user to whom the tickets are minted
/// @param amount The amount of interest to mint as tickets.
function _awardTickets(address user, uint256 amount) internal {
prizePool.award(user, amount, address(ticket));
}
/// @notice Awards all external tokens with non-zero balances to the given user. The external tokens must be held by the PrizePool contract.
/// @param winner The user to transfer the tokens to
function _awardAllExternalTokens(address winner) internal {
_awardExternalErc20s(winner);
_awardExternalErc721s(winner);
}
/// @notice Awards all external ERC20 tokens with non-zero balances to the given user.
/// The external tokens must be held by the PrizePool contract.
/// @param winner The user to transfer the tokens to
function _awardExternalErc20s(address winner) internal {
address currentToken = externalErc20s.start();
while (currentToken != address(0) && currentToken != externalErc20s.end()) {
uint256 balance = IERC20Upgradeable(currentToken).balanceOf(address(prizePool));
if (balance > 0) {
prizePool.awardExternalERC20(winner, currentToken, balance);
}
currentToken = externalErc20s.next(currentToken);
}
}
/// @notice Awards all external ERC721 tokens to the given user.
/// The external tokens must be held by the PrizePool contract.
/// @dev The list of ERC721s is reset after every award
/// @param winner The user to transfer the tokens to
function _awardExternalErc721s(address winner) internal {
address currentToken = externalErc721s.start();
while (currentToken != address(0) && currentToken != externalErc721s.end()) {
uint256 balance = IERC721Upgradeable(currentToken).balanceOf(address(prizePool));
if (balance > 0) {
prizePool.awardExternalERC721(winner, currentToken, externalErc721TokenIds[IERC721Upgradeable(currentToken)]);
_removeExternalErc721AwardTokens(IERC721Upgradeable(currentToken));
}
currentToken = externalErc721s.next(currentToken);
}
externalErc721s.clearAll();
}
/// @notice Returns the timestamp at which the prize period ends
/// @return The timestamp at which the prize period ends.
function prizePeriodEndAt() external view returns (uint256) {
// current prize started at is non-inclusive, so add one
return _prizePeriodEndAt();
}
/// @notice Returns the timestamp at which the prize period ends
/// @return The timestamp at which the prize period ends.
function _prizePeriodEndAt() internal view returns (uint256) {
// current prize started at is non-inclusive, so add one
return prizePeriodStartedAt.add(prizePeriodSeconds);
}
/// @notice Called by the PrizePool for transfers of controlled tokens
/// @dev Note that this is only for *transfers*, not mints or burns
/// @param controlledToken The type of collateral that is being sent
function beforeTokenTransfer(address from, address to, uint256 amount, address controlledToken) external override onlyPrizePool {
require(from != to, "PeriodicPrizeStrategy/transfer-to-self");
if (controlledToken == address(ticket)) {
_requireAwardNotInProgress();
}
if (address(tokenListener) != address(0)) {
tokenListener.beforeTokenTransfer(from, to, amount, controlledToken);
}
}
/// @notice Called by the PrizePool when minting controlled tokens
/// @param controlledToken The type of collateral that is being minted
function beforeTokenMint(
address to,
uint256 amount,
address controlledToken,
address referrer
)
external
override
onlyPrizePool
{
if (controlledToken == address(ticket)) {
_requireAwardNotInProgress();
}
if (address(tokenListener) != address(0)) {
tokenListener.beforeTokenMint(to, amount, controlledToken, referrer);
}
}
/// @notice returns the current time. Used for testing.
/// @return The current time (block.timestamp)
function _currentTime() internal virtual view returns (uint256) {
return block.timestamp;
}
/// @notice returns the current time. Used for testing.
/// @return The current time (block.timestamp)
function _currentBlock() internal virtual view returns (uint256) {
return block.number;
}
/// @notice Starts the award process by starting random number request. The prize period must have ended.
/// @dev The RNG-Request-Fee is expected to be held within this contract before calling this function
function startAward() external requireCanStartAward {
(address feeToken, uint256 requestFee) = rng.getRequestFee();
if (feeToken != address(0) && requestFee > 0) {
IERC20Upgradeable(feeToken).approve(address(rng), requestFee);
}
(uint32 requestId, uint32 lockBlock) = rng.requestRandomNumber();
rngRequest.id = requestId;
rngRequest.lockBlock = lockBlock;
rngRequest.requestedAt = _currentTime().toUint32();
emit PrizePoolAwardStarted(_msgSender(), address(prizePool), requestId, lockBlock);
}
/// @notice Can be called by anyone to unlock the tickets if the RNG has timed out.
function cancelAward() public {
require(isRngTimedOut(), "PeriodicPrizeStrategy/rng-not-timedout");
uint32 requestId = rngRequest.id;
uint32 lockBlock = rngRequest.lockBlock;
delete rngRequest;
emit RngRequestFailed();
emit PrizePoolAwardCancelled(msg.sender, address(prizePool), requestId, lockBlock);
}
/// @notice Completes the award process and awards the winners. The random number must have been requested and is now available.
function completeAward() external requireCanCompleteAward {
uint256 randomNumber = rng.randomNumber(rngRequest.id);
delete rngRequest;
if (address(beforeAwardListener) != address(0)) {
beforeAwardListener.beforePrizePoolAwarded(randomNumber, prizePeriodStartedAt);
}
_distribute(randomNumber);
if (address(periodicPrizeStrategyListener) != address(0)) {
periodicPrizeStrategyListener.afterPrizePoolAwarded(randomNumber, prizePeriodStartedAt);
}
// to avoid clock drift, we should calculate the start time based on the previous period start time.
prizePeriodStartedAt = _calculateNextPrizePeriodStartTime(_currentTime());
emit PrizePoolAwarded(_msgSender(), randomNumber);
emit PrizePoolOpened(_msgSender(), prizePeriodStartedAt);
}
/// @notice Allows the owner to set a listener that is triggered immediately before the award is distributed
/// @dev The listener must implement ERC165 and the BeforeAwardListenerInterface
/// @param _beforeAwardListener The address of the listener contract
function setBeforeAwardListener(BeforeAwardListenerInterface _beforeAwardListener) external onlyOwner requireAwardNotInProgress {
require(
address(0) == address(_beforeAwardListener) || address(_beforeAwardListener).supportsInterface(BeforeAwardListenerLibrary.ERC165_INTERFACE_ID_BEFORE_AWARD_LISTENER),
"PeriodicPrizeStrategy/beforeAwardListener-invalid"
);
beforeAwardListener = _beforeAwardListener;
emit BeforeAwardListenerSet(_beforeAwardListener);
}
/// @notice Allows the owner to set a listener for prize strategy callbacks.
/// @param _periodicPrizeStrategyListener The address of the listener contract
function setPeriodicPrizeStrategyListener(PeriodicPrizeStrategyListenerInterface _periodicPrizeStrategyListener) external onlyOwner requireAwardNotInProgress {
require(
address(0) == address(_periodicPrizeStrategyListener) || address(_periodicPrizeStrategyListener).supportsInterface(PeriodicPrizeStrategyListenerLibrary.ERC165_INTERFACE_ID_PERIODIC_PRIZE_STRATEGY_LISTENER),
"PeriodicPrizeStrategy/prizeStrategyListener-invalid"
);
periodicPrizeStrategyListener = _periodicPrizeStrategyListener;
emit PeriodicPrizeStrategyListenerSet(_periodicPrizeStrategyListener);
}
function _calculateNextPrizePeriodStartTime(uint256 currentTime) internal view returns (uint256) {
uint256 elapsedPeriods = currentTime.sub(prizePeriodStartedAt).div(prizePeriodSeconds);
return prizePeriodStartedAt.add(elapsedPeriods.mul(prizePeriodSeconds));
}
/// @notice Calculates when the next prize period will start
/// @param currentTime The timestamp to use as the current time
/// @return The timestamp at which the next prize period would start
function calculateNextPrizePeriodStartTime(uint256 currentTime) external view returns (uint256) {
return _calculateNextPrizePeriodStartTime(currentTime);
}
/// @notice Returns whether an award process can be started
/// @return True if an award can be started, false otherwise.
function canStartAward() external view returns (bool) {
return _isPrizePeriodOver() && !isRngRequested();
}
/// @notice Returns whether an award process can be completed
/// @return True if an award can be completed, false otherwise.
function canCompleteAward() external view returns (bool) {
return isRngRequested() && isRngCompleted();
}
/// @notice Returns whether a random number has been requested
/// @return True if a random number has been requested, false otherwise.
function isRngRequested() public view returns (bool) {
return rngRequest.id != 0;
}
/// @notice Returns whether the random number request has completed.
/// @return True if a random number request has completed, false otherwise.
function isRngCompleted() public view returns (bool) {
return rng.isRequestComplete(rngRequest.id);
}
/// @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) {
return rngRequest.lockBlock;
}
/// @notice Returns the current RNG Request ID
/// @return The current Request ID
function getLastRngRequestId() external view returns (uint32) {
return rngRequest.id;
}
/// @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 onlyOwner requireAwardNotInProgress {
require(!isRngRequested(), "PeriodicPrizeStrategy/rng-in-flight");
rng = rngService;
emit RngServiceUpdated(rngService);
}
/// @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 _rngRequestTimeout The RNG request timeout in seconds.
function setRngRequestTimeout(uint32 _rngRequestTimeout) external onlyOwner requireAwardNotInProgress {
_setRngRequestTimeout(_rngRequestTimeout);
}
/// @notice Sets 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 _rngRequestTimeout The RNG request timeout in seconds.
function _setRngRequestTimeout(uint32 _rngRequestTimeout) internal {
require(_rngRequestTimeout > 60, "PeriodicPrizeStrategy/rng-timeout-gt-60-secs");
rngRequestTimeout = _rngRequestTimeout;
emit RngRequestTimeoutSet(rngRequestTimeout);
}
/// @notice Allows the owner to set the prize period in seconds.
/// @param _prizePeriodSeconds The new prize period in seconds. Must be greater than zero.
function setPrizePeriodSeconds(uint256 _prizePeriodSeconds) external onlyOwner requireAwardNotInProgress {
_setPrizePeriodSeconds(_prizePeriodSeconds);
}
/// @notice Sets the prize period in seconds.
/// @param _prizePeriodSeconds The new prize period in seconds. Must be greater than zero.
function _setPrizePeriodSeconds(uint256 _prizePeriodSeconds) internal {
require(_prizePeriodSeconds > 0, "PeriodicPrizeStrategy/prize-period-greater-than-zero");
prizePeriodSeconds = _prizePeriodSeconds;
emit PrizePeriodSecondsUpdated(prizePeriodSeconds);
}
/// @notice Gets the current list of External ERC20 tokens that will be awarded with the current prize
/// @return An array of External ERC20 token addresses
function getExternalErc20Awards() external view returns (address[] memory) {
return externalErc20s.addressArray();
}
/// @notice Adds an external ERC20 token type as an additional prize that can be awarded
/// @dev Only the Prize-Strategy owner/creator can assign external tokens,
/// and they must be approved by the Prize-Pool
/// @param _externalErc20 The address of an ERC20 token to be awarded
function addExternalErc20Award(IERC20Upgradeable _externalErc20) external onlyOwnerOrListener requireAwardNotInProgress {
_addExternalErc20Award(_externalErc20);
}
function _addExternalErc20Award(IERC20Upgradeable _externalErc20) internal {
require(address(_externalErc20).isContract(), "PeriodicPrizeStrategy/erc20-null");
require(prizePool.canAwardExternal(address(_externalErc20)), "PeriodicPrizeStrategy/cannot-award-external");
(bool succeeded, bytes memory returnValue) = address(_externalErc20).staticcall(abi.encodeWithSignature("totalSupply()"));
require(succeeded, "PeriodicPrizeStrategy/erc20-invalid");
externalErc20s.addAddress(address(_externalErc20));
emit ExternalErc20AwardAdded(_externalErc20);
}
function addExternalErc20Awards(IERC20Upgradeable[] calldata _externalErc20s) external onlyOwnerOrListener requireAwardNotInProgress {
for (uint256 i = 0; i < _externalErc20s.length; i++) {
_addExternalErc20Award(_externalErc20s[i]);
}
}
/// @notice Removes an external ERC20 token type as an additional prize that can be awarded
/// @dev Only the Prize-Strategy owner/creator can remove external tokens
/// @param _externalErc20 The address of an ERC20 token to be removed
/// @param _prevExternalErc20 The address of the previous ERC20 token in the `externalErc20s` list.
/// If the ERC20 is the first address, then the previous address is the SENTINEL address: 0x0000000000000000000000000000000000000001
function removeExternalErc20Award(IERC20Upgradeable _externalErc20, IERC20Upgradeable _prevExternalErc20) external onlyOwner requireAwardNotInProgress {
externalErc20s.removeAddress(address(_prevExternalErc20), address(_externalErc20));
emit ExternalErc20AwardRemoved(_externalErc20);
}
/// @notice Gets the current list of External ERC721 tokens that will be awarded with the current prize
/// @return An array of External ERC721 token addresses
function getExternalErc721Awards() external view returns (address[] memory) {
return externalErc721s.addressArray();
}
/// @notice Gets the current list of External ERC721 tokens that will be awarded with the current prize
/// @return An array of External ERC721 token addresses
function getExternalErc721AwardTokenIds(IERC721Upgradeable _externalErc721) external view returns (uint256[] memory) {
return externalErc721TokenIds[_externalErc721];
}
/// @notice Adds an external ERC721 token as an additional prize that can be awarded
/// @dev Only the Prize-Strategy owner/creator can assign external tokens,
/// and they must be approved by the Prize-Pool
/// NOTE: The NFT must already be owned by the Prize-Pool
/// @param _externalErc721 The address of an ERC721 token to be awarded
/// @param _tokenIds An array of token IDs of the ERC721 to be awarded
function addExternalErc721Award(IERC721Upgradeable _externalErc721, uint256[] calldata _tokenIds) external onlyOwnerOrListener requireAwardNotInProgress {
require(prizePool.canAwardExternal(address(_externalErc721)), "PeriodicPrizeStrategy/cannot-award-external");
require(address(_externalErc721).supportsInterface(Constants.ERC165_INTERFACE_ID_ERC721), "PeriodicPrizeStrategy/erc721-invalid");
if (!externalErc721s.contains(address(_externalErc721))) {
externalErc721s.addAddress(address(_externalErc721));
}
for (uint256 i = 0; i < _tokenIds.length; i++) {
_addExternalErc721Award(_externalErc721, _tokenIds[i]);
}
emit ExternalErc721AwardAdded(_externalErc721, _tokenIds);
}
function _addExternalErc721Award(IERC721Upgradeable _externalErc721, uint256 _tokenId) internal {
require(IERC721Upgradeable(_externalErc721).ownerOf(_tokenId) == address(prizePool), "PeriodicPrizeStrategy/unavailable-token");
for (uint256 i = 0; i < externalErc721TokenIds[_externalErc721].length; i++) {
if (externalErc721TokenIds[_externalErc721][i] == _tokenId) {
revert("PeriodicPrizeStrategy/erc721-duplicate");
}
}
externalErc721TokenIds[_externalErc721].push(_tokenId);
}
/// @notice Removes an external ERC721 token as an additional prize that can be awarded
/// @dev Only the Prize-Strategy owner/creator can remove external tokens
/// @param _externalErc721 The address of an ERC721 token to be removed
/// @param _prevExternalErc721 The address of the previous ERC721 token in the list.
/// If no previous, then pass the SENTINEL address: 0x0000000000000000000000000000000000000001
function removeExternalErc721Award(
IERC721Upgradeable _externalErc721,
IERC721Upgradeable _prevExternalErc721
)
external
onlyOwner
requireAwardNotInProgress
{
externalErc721s.removeAddress(address(_prevExternalErc721), address(_externalErc721));
_removeExternalErc721AwardTokens(_externalErc721);
}
function _removeExternalErc721AwardTokens(
IERC721Upgradeable _externalErc721
)
internal
{
delete externalErc721TokenIds[_externalErc721];
emit ExternalErc721AwardRemoved(_externalErc721);
}
function _requireAwardNotInProgress() internal view {
uint256 currentBlock = _currentBlock();
require(rngRequest.lockBlock == 0 || currentBlock < rngRequest.lockBlock, "PeriodicPrizeStrategy/rng-in-flight");
}
function isRngTimedOut() public view returns (bool) {
if (rngRequest.requestedAt == 0) {
return false;
} else {
return _currentTime() > uint256(rngRequestTimeout).add(rngRequest.requestedAt);
}
}
modifier onlyOwnerOrListener() {
require(_msgSender() == owner() ||
_msgSender() == address(periodicPrizeStrategyListener) ||
_msgSender() == address(beforeAwardListener),
"PeriodicPrizeStrategy/only-owner-or-listener");
_;
}
modifier requireAwardNotInProgress() {
_requireAwardNotInProgress();
_;
}
modifier requireCanStartAward() {
require(_isPrizePeriodOver(), "PeriodicPrizeStrategy/prize-period-not-over");
require(!isRngRequested(), "PeriodicPrizeStrategy/rng-already-requested");
_;
}
modifier requireCanCompleteAward() {
require(isRngRequested(), "PeriodicPrizeStrategy/rng-not-requested");
require(isRngCompleted(), "PeriodicPrizeStrategy/rng-not-complete");
_;
}
modifier onlyPrizePool() {
require(_msgSender() == address(prizePool), "PeriodicPrizeStrategy/only-prize-pool");
_;
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol";
/* solium-disable security/no-block-members */
interface PeriodicPrizeStrategyListenerInterface is IERC165Upgradeable {
function afterPrizePoolAwarded(uint256 randomNumber, uint256 prizePeriodStartedAt) external;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity ^0.6.12;
library PeriodicPrizeStrategyListenerLibrary {
/*
* bytes4(keccak256('afterPrizePoolAwarded(uint256,uint256)')) == 0x575072c6
*/
bytes4 public constant ERC165_INTERFACE_ID_PERIODIC_PRIZE_STRATEGY_LISTENER = 0x575072c6;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
import "../PeriodicPrizeStrategy.sol";
contract MultipleWinners is PeriodicPrizeStrategy {
uint256 internal __numberOfWinners;
bool public splitExternalErc20Awards;
event SplitExternalErc20AwardsSet(bool splitExternalErc20Awards);
event NumberOfWinnersSet(uint256 numberOfWinners);
event NoWinners();
function initializeMultipleWinners (
uint256 _prizePeriodStart,
uint256 _prizePeriodSeconds,
PrizePool _prizePool,
TicketInterface _ticket,
IERC20Upgradeable _sponsorship,
RNGInterface _rng,
uint256 _numberOfWinners
) public initializer {
IERC20Upgradeable[] memory _externalErc20Awards;
PeriodicPrizeStrategy.initialize(
_prizePeriodStart,
_prizePeriodSeconds,
_prizePool,
_ticket,
_sponsorship,
_rng,
_externalErc20Awards
);
_setNumberOfWinners(_numberOfWinners);
}
function setSplitExternalErc20Awards(bool _splitExternalErc20Awards) external onlyOwner requireAwardNotInProgress {
splitExternalErc20Awards = _splitExternalErc20Awards;
emit SplitExternalErc20AwardsSet(splitExternalErc20Awards);
}
function setNumberOfWinners(uint256 count) external onlyOwner requireAwardNotInProgress {
_setNumberOfWinners(count);
}
function _setNumberOfWinners(uint256 count) internal {
require(count > 0, "MultipleWinners/winners-gte-one");
__numberOfWinners = count;
emit NumberOfWinnersSet(count);
}
function numberOfWinners() external view returns (uint256) {
return __numberOfWinners;
}
function _distribute(uint256 randomNumber) internal override {
uint256 prize = prizePool.captureAwardBalance();
// main winner is simply the first that is drawn
address mainWinner = ticket.draw(randomNumber);
// If drawing yields no winner, then there is no one to pick
if (mainWinner == address(0)) {
emit NoWinners();
return;
}
// main winner gets all external ERC721 tokens
_awardExternalErc721s(mainWinner);
address[] memory winners = new address[](__numberOfWinners);
winners[0] = mainWinner;
uint256 nextRandom = randomNumber;
for (uint256 winnerCount = 1; winnerCount < __numberOfWinners; winnerCount++) {
// add some arbitrary numbers to the previous random number to ensure no matches with the UniformRandomNumber lib
bytes32 nextRandomHash = keccak256(abi.encodePacked(nextRandom + 499 + winnerCount*521));
nextRandom = uint256(nextRandomHash);
winners[winnerCount] = ticket.draw(nextRandom);
}
// yield prize is split up among all winners
uint256 prizeShare = prize.div(winners.length);
if (prizeShare > 0) {
for (uint i = 0; i < winners.length; i++) {
_awardTickets(winners[i], prizeShare);
}
}
if (splitExternalErc20Awards) {
address currentToken = externalErc20s.start();
while (currentToken != address(0) && currentToken != externalErc20s.end()) {
uint256 balance = IERC20Upgradeable(currentToken).balanceOf(address(prizePool));
uint256 split = balance.div(__numberOfWinners);
if (split > 0) {
for (uint256 i = 0; i < winners.length; i++) {
prizePool.awardExternalERC20(winners[i], currentToken, split);
}
}
currentToken = externalErc20s.next(currentToken);
}
} else {
_awardExternalErc20s(mainWinner);
}
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "./MultipleWinners.sol";
import "../../external/openzeppelin/ProxyFactory.sol";
/// @title Creates a minimal proxy to the MultipleWinners prize strategy. Very cheap to deploy.
contract MultipleWinnersProxyFactory is ProxyFactory {
MultipleWinners public instance;
constructor () public {
instance = new MultipleWinners();
}
function create() external returns (MultipleWinners) {
return MultipleWinners(deployMinimal(address(instance), ""));
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.7.0;
/// @title Interface that allows a user to draw an address using an index
interface RegistryInterface {
function lookup() external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.7.0;
/// @title Interface that allows a user to draw an address using an index
interface ReserveInterface {
function reserveRateMantissa(address prizePool) external view returns (uint256);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/drafts/ERC20PermitUpgradeable.sol";
import "./TokenControllerInterface.sol";
import "./ControlledTokenInterface.sol";
/// @title Controlled ERC20 Token
/// @notice ERC20 Tokens with a controller for minting & burning
contract ControlledToken is ERC20PermitUpgradeable, ControlledTokenInterface {
/// @notice Interface to the contract responsible for controlling mint/burn
TokenControllerInterface public override controller;
/// @notice Initializes the Controlled Token with Token Details and the Controller
/// @param _name The name of the Token
/// @param _symbol The symbol for the Token
/// @param _decimals The number of decimals for the Token
/// @param _controller Address of the Controller contract for minting & burning
function initialize(
string memory _name,
string memory _symbol,
uint8 _decimals,
TokenControllerInterface _controller
)
public
virtual
initializer
{
__ERC20_init(_name, _symbol);
__ERC20Permit_init("PoolTogether ControlledToken");
controller = _controller;
_setupDecimals(_decimals);
}
/// @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 virtual override onlyController {
_mint(_user, _amount);
}
/// @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 virtual override onlyController {
_burn(_user, _amount);
}
/// @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 virtual override onlyController {
if (_operator != _user) {
uint256 decreasedAllowance = allowance(_user, _operator).sub(_amount, "ControlledToken/exceeds-allowance");
_approve(_user, _operator, decreasedAllowance);
}
_burn(_user, _amount);
}
/// @dev Function modifier to ensure that the caller is the controller contract
modifier onlyController {
require(_msgSender() == address(controller), "ControlledToken/only-controller");
_;
}
/// @dev Controller hook to provide notifications & rule validations on token transfers to the controller.
/// This includes minting and burning.
/// May be overridden to provide more granular control over operator-burning
/// @param from Address of the account sending the tokens (address(0x0) on minting)
/// @param to Address of the account receiving the tokens (address(0x0) on burning)
/// @param amount Amount of tokens being transferred
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override {
controller.beforeTokenTransfer(from, to, amount);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol";
import "./TokenControllerInterface.sol";
/// @title Controlled ERC20 Token
/// @notice ERC20 Tokens with a controller for minting & burning
interface ControlledTokenInterface is IERC20Upgradeable {
/// @notice Interface to the contract responsible for controlling mint/burn
function controller() external view returns (TokenControllerInterface);
/// @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.5.0 <0.7.0;
/// @title Interface that allows a user to draw an address using an index
interface TicketInterface {
/// @notice Selects a user using a random number. The random number will be uniformly bounded to the ticket totalSupply.
/// @param randomNumber The random number to use to select a user.
/// @return The winner
function draw(uint256 randomNumber) external view returns (address);
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.7.0;
/// @title Controlled ERC20 Token Interface
/// @notice Required interface for Controlled ERC20 Tokens linked to a Prize Pool
/// @dev Defines the spec required to be implemented by a Controlled ERC20 Token
interface TokenControllerInterface {
/// @dev Controller hook to provide notifications & rule validations on token transfers to the controller.
/// This includes minting and burning.
/// @param from Address of the account sending the tokens (address(0x0) on minting)
/// @param to Address of the account receiving the tokens (address(0x0) on burning)
/// @param amount Amount of tokens being transferred
function beforeTokenTransfer(address from, address to, uint256 amount) external;
}
pragma solidity ^0.6.4;
import "./TokenListenerInterface.sol";
import "./TokenListenerLibrary.sol";
import "../Constants.sol";
abstract contract TokenListener is TokenListenerInterface {
function supportsInterface(bytes4 interfaceId) external override view returns (bool) {
return (
interfaceId == Constants.ERC165_INTERFACE_ID_ERC165 ||
interfaceId == TokenListenerLibrary.ERC165_INTERFACE_ID_TOKEN_LISTENER
);
}
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.5.0 <0.7.0;
import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol";
/// @title An interface that allows a contract to listen to token mint, transfer and burn events.
interface TokenListenerInterface is IERC165Upgradeable {
/// @notice Called when tokens are minted.
/// @param to The address of the receiver of the minted tokens.
/// @param amount The amount of tokens being minted
/// @param controlledToken The address of the token that is being minted
/// @param referrer The address that referred the minting.
function beforeTokenMint(address to, uint256 amount, address controlledToken, address referrer) external;
/// @notice Called when tokens are transferred or burned.
/// @param from The address of the sender of the token transfer
/// @param to The address of the receiver of the token transfer. Will be the zero address if burning.
/// @param amount The amount of tokens transferred
/// @param controlledToken The address of the token that was transferred
function beforeTokenTransfer(address from, address to, uint256 amount, address controlledToken) external;
}
pragma solidity ^0.6.12;
library TokenListenerLibrary {
/*
* bytes4(keccak256('beforeTokenMint(address,uint256,address,address)')) == 0x4d7f3db0
* bytes4(keccak256('beforeTokenTransfer(address,address,uint256,address)')) == 0xb2210957
*
* => 0x4d7f3db0 ^ 0xb2210957 == 0xff5e34e7
*/
bytes4 public constant ERC165_INTERFACE_ID_TOKEN_LISTENER = 0xff5e34e7;
}
// SPDX-License-Identifier: GPL-3.0
pragma solidity >=0.6.0 <0.7.0;
/// @notice An efficient implementation of a singly linked list of addresses
/// @dev A mapping(address => address) tracks the 'next' pointer. A special address called the SENTINEL is used to denote the beginning and end of the list.
library MappedSinglyLinkedList {
/// @notice The special value address used to denote the end of the list
address public constant SENTINEL = address(0x1);
/// @notice The data structure to use for the list.
struct Mapping {
uint256 count;
mapping(address => address) addressMap;
}
/// @notice Initializes the list.
/// @dev It is important that this is called so that the SENTINEL is correctly setup.
function initialize(Mapping storage self) internal {
require(self.count == 0, "Already init");
self.addressMap[SENTINEL] = SENTINEL;
}
function start(Mapping storage self) internal view returns (address) {
return self.addressMap[SENTINEL];
}
function next(Mapping storage self, address current) internal view returns (address) {
return self.addressMap[current];
}
function end(Mapping storage) internal pure returns (address) {
return SENTINEL;
}
function addAddresses(Mapping storage self, address[] memory addresses) internal {
for (uint256 i = 0; i < addresses.length; i++) {
addAddress(self, addresses[i]);
}
}
/// @notice Adds an address to the front of the list.
/// @param self The Mapping struct that this function is attached to
/// @param newAddress The address to shift to the front of the list
function addAddress(Mapping storage self, address newAddress) internal {
require(newAddress != SENTINEL && newAddress != address(0), "Invalid address");
require(self.addressMap[newAddress] == address(0), "Already added");
self.addressMap[newAddress] = self.addressMap[SENTINEL];
self.addressMap[SENTINEL] = newAddress;
self.count = self.count + 1;
}
/// @notice Removes an address from the list
/// @param self The Mapping struct that this function is attached to
/// @param prevAddress The address that precedes the address to be removed. This may be the SENTINEL if at the start.
/// @param addr The address to remove from the list.
function removeAddress(Mapping storage self, address prevAddress, address addr) internal {
require(addr != SENTINEL && addr != address(0), "Invalid address");
require(self.addressMap[prevAddress] == addr, "Invalid prevAddress");
self.addressMap[prevAddress] = self.addressMap[addr];
delete self.addressMap[addr];
self.count = self.count - 1;
}
/// @notice Determines whether the list contains the given address
/// @param self The Mapping struct that this function is attached to
/// @param addr The address to check
/// @return True if the address is contained, false otherwise.
function contains(Mapping storage self, address addr) internal view returns (bool) {
return addr != SENTINEL && addr != address(0) && self.addressMap[addr] != address(0);
}
/// @notice Returns an address array of all the addresses in this list
/// @dev Contains a for loop, so complexity is O(n) wrt the list size
/// @param self The Mapping struct that this function is attached to
/// @return An array of all the addresses
function addressArray(Mapping storage self) internal view returns (address[] memory) {
address[] memory array = new address[](self.count);
uint256 count;
address currentAddress = self.addressMap[SENTINEL];
while (currentAddress != address(0) && currentAddress != SENTINEL) {
array[count] = currentAddress;
currentAddress = self.addressMap[currentAddress];
count++;
}
return array;
}
/// @notice Removes every address from the list
/// @param self The Mapping struct that this function is attached to
function clearAll(Mapping storage self) internal {
address currentAddress = self.addressMap[SENTINEL];
while (currentAddress != address(0) && currentAddress != SENTINEL) {
address nextAddress = self.addressMap[currentAddress];
delete self.addressMap[currentAddress];
currentAddress = nextAddress;
}
self.addressMap[SENTINEL] = SENTINEL;
self.count = 0;
}
}
|
Returns whether the random number request has completed. return True if a random number request has completed, false otherwise.
|
function isRngCompleted() public view returns (bool) {
return rng.isRequestComplete(rngRequest.id);
}
| 1,239,832 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract TellorPlayground {
// Events
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
event NewReport(
bytes32 _queryId,
uint256 _time,
bytes _value,
uint256 _reward,
uint256 _nonce,
bytes _queryData,
address _reporter
);
event NewStaker(address _staker, uint256 _amount);
event TipAdded(
address indexed _user,
bytes32 indexed _queryId,
uint256 _tip,
uint256 _totalTip,
bytes _queryData
);
event StakeWithdrawRequested(address _staker, uint256 _amount);
event StakeWithdrawn(address _staker);
event Transfer(address indexed from, address indexed to, uint256 value);
// Storage
mapping(bytes32 => address) public addresses;
mapping(bytes32 => mapping(uint256 => bool)) public isDisputed; //queryId -> timestamp -> value
mapping(bytes32 => mapping(uint256 => address)) public reporterByTimestamp;
mapping(address => StakeInfo) stakerDetails; //mapping from a persons address to their staking info
mapping(bytes32 => uint256[]) public timestamps;
mapping(bytes32 => uint256) public tips; // mapping of data IDs to the amount of TRB they are tipped
mapping(bytes32 => mapping(uint256 => bytes)) public values; //queryId -> timestamp -> value
mapping(bytes32 => uint256[]) public voteRounds; // mapping of vote identifier hashes to an array of dispute IDs
mapping(address => mapping(address => uint256)) private _allowances;
mapping(address => uint256) private _balances;
uint256 public constant timeBasedReward = 5e17; // time based reward for a reporter for successfully submitting a value
uint256 public timeOfLastNewValue = block.timestamp; // time of the last new value, originally set to the block timestamp
uint256 public tipsInContract; // number of tips within the contract
uint256 public voteCount;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
// Structs
struct StakeInfo {
uint256 startDate; //stake start date
uint256 stakedBalance; // staked balance
uint256 lockedBalance; // amount locked for withdrawal
uint256 reporterLastTimestamp; // timestamp of reporter's last reported value
uint256 reportsSubmitted; // total number of reports submitted by reporter
}
// Functions
/**
* @dev Initializes playground parameters
*/
constructor() {
_name = "TellorPlayground";
_symbol = "TRBP";
_decimals = 18;
addresses[
keccak256(abi.encodePacked("_GOVERNANCE_CONTRACT"))
] = address(this);
}
/**
* @dev Approves amount that an address is alowed to spend of behalf of another
* @param _spender The address which is allowed to spend the tokens
* @param _amount The amount that msg.sender is allowing spender to use
* @return bool Whether the transaction succeeded
*
*/
function approve(address _spender, uint256 _amount)
public
virtual
returns (bool)
{
_approve(msg.sender, _spender, _amount);
return true;
}
/**
* @dev A mock function to create a dispute
* @param _queryId The tellorId to be disputed
* @param _timestamp the timestamp of the value to be disputed
*/
function beginDispute(bytes32 _queryId, uint256 _timestamp) external {
values[_queryId][_timestamp] = bytes("");
isDisputed[_queryId][_timestamp] = true;
voteCount++;
voteRounds[keccak256(abi.encodePacked(_queryId, _timestamp))].push(
voteCount
);
}
/**
* @dev Public function to mint tokens to the given address
* @param _user The address which will receive the tokens
*/
function faucet(address _user) external {
_mint(_user, 1000 ether);
}
/**
* @dev A mock function to submit a value to be read without reporter staking needed
* @param _queryId the ID to associate the value to
* @param _value the value for the queryId
* @param _nonce the current value count for the query id
* @param _queryData the data used by reporters to fulfill the data query
*/
// slither-disable-next-line timestamp
function submitValue(
bytes32 _queryId,
bytes calldata _value,
uint256 _nonce,
bytes memory _queryData
) external {
require(
_nonce == timestamps[_queryId].length,
"nonce should be correct"
);
require(
_queryId == keccak256(_queryData) || uint256(_queryId) <= 100,
"id must be hash of bytes data"
);
values[_queryId][block.timestamp] = _value;
timestamps[_queryId].push(block.timestamp);
// Send tips + timeBasedReward to reporter and reset tips for ID
(uint256 _tip, uint256 _reward) = getCurrentReward(_queryId);
if (_reward + _tip > 0) {
transfer(msg.sender, _reward + _tip);
}
timeOfLastNewValue = block.timestamp;
tipsInContract -= _tip;
tips[_queryId] = 0;
reporterByTimestamp[_queryId][block.timestamp] = msg.sender;
stakerDetails[msg.sender].reporterLastTimestamp = block.timestamp;
stakerDetails[msg.sender].reportsSubmitted++;
emit NewReport(
_queryId,
block.timestamp,
_value,
_tip + _reward,
_nonce,
_queryData,
msg.sender
);
}
/**
* @dev Adds a tip to a given query ID.
* @param _queryId is the queryId to look up
* @param _amount is the amount of tips
* @param _queryData is the extra bytes data needed to fulfill the request
*/
function tipQuery(
bytes32 _queryId,
uint256 _amount,
bytes memory _queryData
) external {
require(
_queryId == keccak256(_queryData) || uint256(_queryId) <= 100,
"id must be hash of bytes data"
);
_transfer(msg.sender, address(this), _amount);
_amount = _amount / 2;
_burn(address(this), _amount);
tipsInContract += _amount;
tips[_queryId] += _amount;
emit TipAdded(
msg.sender,
_queryId,
_amount,
tips[_queryId],
_queryData
);
}
/**
* @dev Transfer tokens from one user to another
* @param _recipient The destination address
* @param _amount The amount of tokens, including decimals, to transfer
* @return bool If the transfer succeeded
*/
function transfer(address _recipient, uint256 _amount)
public
virtual
returns (bool)
{
_transfer(msg.sender, _recipient, _amount);
return true;
}
/**
* @dev Transfer tokens from user to another
* @param _sender The address which owns the tokens
* @param _recipient The destination address
* @param _amount The quantity of tokens to transfer
* @return bool Whether the transfer succeeded
*/
function transferFrom(
address _sender,
address _recipient,
uint256 _amount
) public virtual returns (bool) {
_transfer(_sender, _recipient, _amount);
_approve(
_sender,
msg.sender,
_allowances[_sender][msg.sender] - _amount
);
return true;
}
// Tellor Flex
/**
* @dev Allows a reporter to submit stake
* @param _amount amount of tokens to stake
*/
function depositStake(uint256 _amount) external {
StakeInfo storage _staker = stakerDetails[msg.sender];
if (_staker.lockedBalance > 0) {
if (_staker.lockedBalance >= _amount) {
_staker.lockedBalance -= _amount;
} else {
require(
_transferFrom(
msg.sender,
address(this),
_amount - _staker.lockedBalance
)
);
_staker.lockedBalance = 0;
}
} else {
require(_transferFrom(msg.sender, address(this), _amount));
}
_staker.startDate = block.timestamp; // This resets their stake start date to now
_staker.stakedBalance += _amount;
emit NewStaker(msg.sender, _amount);
}
/**
* @dev Allows a reporter to request to withdraw their stake
* @param _amount amount of staked tokens requesting to withdraw
*/
function requestStakingWithdraw(uint256 _amount) external {
StakeInfo storage _staker = stakerDetails[msg.sender];
require(
_staker.stakedBalance >= _amount,
"insufficient staked balance"
);
_staker.startDate = block.timestamp;
_staker.lockedBalance += _amount;
_staker.stakedBalance -= _amount;
emit StakeWithdrawRequested(msg.sender, _amount);
}
/**
* @dev Withdraws a reporter's stake
*/
function withdrawStake() external {
StakeInfo storage _s = stakerDetails[msg.sender];
// Ensure reporter is locked and that enough time has passed
require(block.timestamp - _s.startDate >= 7 days, "7 days didn't pass");
require(_s.lockedBalance > 0, "reporter not locked for withdrawal");
_transfer(address(this), msg.sender, _s.lockedBalance);
_s.lockedBalance = 0;
emit StakeWithdrawn(msg.sender);
}
/**
* @dev Returns the reporter for a given timestamp and queryId
* @param _queryId bytes32 version of the queryId
* @param _timestamp uint256 timestamp of report
* @return address of data reporter
*/
function getReporterByTimestamp(bytes32 _queryId, uint256 _timestamp)
external
view
returns (address)
{
return reporterByTimestamp[_queryId][_timestamp];
}
/**
* @dev Allows users to retrieve all information about a staker
* @param _staker address of staker inquiring about
* @return uint startDate of staking
* @return uint current amount staked
* @return uint current amount locked for withdrawal
* @return uint reporter's last reported timestamp
* @return uint total number of reports submitted by reporter
*/
function getStakerInfo(address _staker)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
)
{
return (
stakerDetails[_staker].startDate,
stakerDetails[_staker].stakedBalance,
stakerDetails[_staker].lockedBalance,
stakerDetails[_staker].reporterLastTimestamp,
stakerDetails[_staker].reportsSubmitted
);
}
// Getters
/**
* @dev Returns the amount that an address is alowed to spend of behalf of another
* @param _owner The address which owns the tokens
* @param _spender The address that will use the tokens
* @return uint256 The amount of allowed tokens
*/
function allowance(address _owner, address _spender)
public
view
virtual
returns (uint256)
{
return _allowances[_owner][_spender];
}
/**
* @dev Returns the balance of a given user.
* @param _account user address
* @return uint256 user's token balance
*/
function balanceOf(address _account) public view returns (uint256) {
return _balances[_account];
}
/**
* @dev Returns the number of decimals used to get its user representation.
* @return uint8 the number of decimals; used only for display purposes
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev Calculates the current reward for a reporter given tips and time based reward
* @param _queryId is ID of the specific data feed
* @return uint256 tip amount for given query ID
* @return uint256 time based reward
*/
// slither-disable-next-line timestamp
function getCurrentReward(bytes32 _queryId)
public
view
returns (uint256, uint256)
{
uint256 _timeDiff = block.timestamp - timeOfLastNewValue;
uint256 _reward = (_timeDiff * timeBasedReward) / 300; //.5 TRB per 5 minutes (should we make this upgradeable)
if (balanceOf(address(this)) < _reward + tipsInContract) {
_reward = balanceOf(address(this)) - tipsInContract;
}
return (tips[_queryId], _reward);
}
/**
* @dev Counts the number of values that have been submitted for a given ID
* @param _queryId the ID to look up
* @return uint256 count of the number of values received for the queryId
*/
function getNewValueCountbyQueryId(bytes32 _queryId)
public
view
returns (uint256)
{
return timestamps[_queryId].length;
}
/**
* @dev Gets the timestamp for the value based on their index
* @param _queryId is the queryId to look up
* @param _index is the value index to look up
* @return uint256 timestamp
*/
function getTimestampbyQueryIdandIndex(bytes32 _queryId, uint256 _index)
public
view
returns (uint256)
{
uint256 len = timestamps[_queryId].length;
if (len == 0 || len <= _index) return 0;
return timestamps[_queryId][_index];
}
/**
* @dev Returns an array of voting rounds for a given vote
* @param _hash is the identifier hash for a vote
* @return uint256[] memory dispute IDs of the vote rounds
*/
function getVoteRounds(bytes32 _hash)
public
view
returns (uint256[] memory)
{
return voteRounds[_hash];
}
/**
* @dev Returns the name of the token.
* @return string name of the token
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Retrieves value from oracle based on queryId/timestamp
* @param _queryId being requested
* @param _timestamp to retrieve data/value from
* @return bytes value for queryId/timestamp submitted
*/
function retrieveData(bytes32 _queryId, uint256 _timestamp)
public
view
returns (bytes memory)
{
return values[_queryId][_timestamp];
}
/**
* @dev Returns the symbol of the token.
* @return string symbol of the token
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the total supply of the token.
* @return uint256 total supply of token
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
// Internal functions
/**
* @dev Internal function to approve tokens for the user
* @param _owner The owner of the tokens
* @param _spender The address which is allowed to spend the tokens
* @param _amount The amount that msg.sender is allowing spender to use
*/
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 Internal function to burn tokens for the user
* @param _account The address whose tokens to burn
* @param _amount The quantity of tokens to burn
*/
function _burn(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: burn from the zero address");
_balances[_account] -= _amount;
_totalSupply -= _amount;
emit Transfer(_account, address(0), _amount);
}
/**
* @dev Internal function to create new tokens for the user
* @param _account The address which receives minted tokens
* @param _amount The quantity of tokens to min
*/
function _mint(address _account, uint256 _amount) internal virtual {
require(_account != address(0), "ERC20: mint to the zero address");
_totalSupply += _amount;
_balances[_account] += _amount;
emit Transfer(address(0), _account, _amount);
}
/**
* @dev Internal function to perform token transfer
* @param _sender The address which owns the tokens
* @param _recipient The destination address
* @param _amount The quantity of tokens to transfer
*/
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"
);
_balances[_sender] -= _amount;
_balances[_recipient] += _amount;
emit Transfer(_sender, _recipient, _amount);
}
/**
* @dev Allows this contract to transfer tokens from one user to another
* @param _sender The address which owns the tokens
* @param _recipient The destination address
* @param _amount The quantity of tokens to transfer
* @return bool Whether the transfer succeeded
*/
function _transferFrom(
address _sender,
address _recipient,
uint256 _amount
) internal virtual returns (bool) {
_transfer(_sender, _recipient, _amount);
_approve(
_sender,
msg.sender,
_allowances[_sender][address(this)] - _amount
);
return true;
}
}
|
Transfer tokens from one user to another _recipient The destination address _amount The amount of tokens, including decimals, to transfer return bool If the transfer succeeded/
|
function transfer(address _recipient, uint256 _amount)
public
virtual
returns (bool)
{
_transfer(msg.sender, _recipient, _amount);
return true;
}
| 12,899,680 |
/**
* SPDX-License-Identifier: UNLICENSED
*/
pragma solidity =0.6.10;
pragma experimental ABIEncoderV2;
import {OwnableUpgradeSafe} from "./packages/oz/upgradeability/OwnableUpgradeSafe.sol";
import {ReentrancyGuardUpgradeSafe} from "./packages/oz/upgradeability/ReentrancyGuardUpgradeSafe.sol";
import {Initializable} from "./packages/oz/upgradeability/Initializable.sol";
import {SafeMath} from "./packages/oz/SafeMath.sol";
import {MarginVault} from "./libs/MarginVault.sol";
import {Actions} from "./libs/Actions.sol";
import {AddressBookInterface} from "./interfaces/AddressBookInterface.sol";
import {OtokenInterface} from "./interfaces/OtokenInterface.sol";
import {MarginCalculatorInterface} from "./interfaces/MarginCalculatorInterface.sol";
import {OracleInterface} from "./interfaces/OracleInterface.sol";
import {WhitelistInterface} from "./interfaces/WhitelistInterface.sol";
import {MarginPoolInterface} from "./interfaces/MarginPoolInterface.sol";
import {CalleeInterface} from "./interfaces/CalleeInterface.sol";
/**
* @title Controller
* @author Opyn Team
* @notice Contract that controls the Gamma Protocol and the interaction of all sub contracts
*/
contract Controller is Initializable, OwnableUpgradeSafe, ReentrancyGuardUpgradeSafe {
using MarginVault for MarginVault.Vault;
using SafeMath for uint256;
AddressBookInterface public addressbook;
WhitelistInterface public whitelist;
OracleInterface public oracle;
MarginCalculatorInterface public calculator;
MarginPoolInterface public pool;
///@dev scale used in MarginCalculator
uint256 internal constant BASE = 8;
/// @notice address that has permission to partially pause the system, where system functionality is paused
/// except redeem and settleVault
address public partialPauser;
/// @notice address that has permission to fully pause the system, where all system functionality is paused
address public fullPauser;
/// @notice True if all system functionality is paused other than redeem and settle vault
bool public systemPartiallyPaused;
/// @notice True if all system functionality is paused
bool public systemFullyPaused;
/// @notice True if a call action can only be executed to a whitelisted callee
bool public callRestricted;
/// @dev mapping between an owner address and the number of owner address vaults
mapping(address => uint256) internal accountVaultCounter;
/// @dev mapping between an owner address and a specific vault using a vault id
mapping(address => mapping(uint256 => MarginVault.Vault)) internal vaults;
/// @dev mapping between an account owner and their approved or unapproved account operators
mapping(address => mapping(address => bool)) internal operators;
/// @notice emits an event when an account operator is updated for a specific account owner
event AccountOperatorUpdated(address indexed accountOwner, address indexed operator, bool isSet);
/// @notice emits an event when a new vault is opened
event VaultOpened(address indexed accountOwner, uint256 vaultId);
/// @notice emits an event when a long oToken is deposited into a vault
event LongOtokenDeposited(
address indexed otoken,
address indexed accountOwner,
address indexed from,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a long oToken is withdrawn from a vault
event LongOtokenWithdrawed(
address indexed otoken,
address indexed AccountOwner,
address indexed to,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a collateral asset is deposited into a vault
event CollateralAssetDeposited(
address indexed asset,
address indexed accountOwner,
address indexed from,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a collateral asset is withdrawn from a vault
event CollateralAssetWithdrawed(
address indexed asset,
address indexed AccountOwner,
address indexed to,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a short oToken is minted from a vault
event ShortOtokenMinted(
address indexed otoken,
address indexed AccountOwner,
address indexed to,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when a short oToken is burned
event ShortOtokenBurned(
address indexed otoken,
address indexed AccountOwner,
address indexed from,
uint256 vaultId,
uint256 amount
);
/// @notice emits an event when an oToken is redeemed
event Redeem(
address indexed otoken,
address indexed redeemer,
address indexed receiver,
address collateralAsset,
uint256 otokenBurned,
uint256 payout
);
/// @notice emits an event when a vault is settled
event VaultSettled(
address indexed AccountOwner,
address indexed to,
address indexed otoken,
uint256 vaultId,
uint256 payout
);
/// @notice emits an event when a call action is executed
event CallExecuted(address indexed from, address indexed to, bytes data);
/// @notice emits an event when the fullPauser address changes
event FullPauserUpdated(address indexed oldFullPauser, address indexed newFullPauser);
/// @notice emits an event when the partialPauser address changes
event PartialPauserUpdated(address indexed oldPartialPauser, address indexed newPartialPauser);
/// @notice emits an event when the system partial paused status changes
event SystemPartiallyPaused(bool isPaused);
/// @notice emits an event when the system fully paused status changes
event SystemFullyPaused(bool isPaused);
/// @notice emits an event when the call action restriction changes
event CallRestricted(bool isRestricted);
/**
* @notice modifier to check if the system is not partially paused, where only redeem and settleVault is allowed
*/
modifier notPartiallyPaused {
_isNotPartiallyPaused();
_;
}
/**
* @notice modifier to check if the system is not fully paused, where no functionality is allowed
*/
modifier notFullyPaused {
_isNotFullyPaused();
_;
}
/**
* @notice modifier to check if sender is the fullPauser address
*/
modifier onlyFullPauser {
require(msg.sender == fullPauser, "Controller: sender is not fullPauser");
_;
}
/**
* @notice modifier to check if the sender is the partialPauser address
*/
modifier onlyPartialPauser {
require(msg.sender == partialPauser, "Controller: sender is not partialPauser");
_;
}
/**
* @notice modifier to check if the sender is the account owner or an approved account operator
* @param _sender sender address
* @param _accountOwner account owner address
*/
modifier onlyAuthorized(address _sender, address _accountOwner) {
_isAuthorized(_sender, _accountOwner);
_;
}
/**
* @notice modifier to check if the called address is a whitelisted callee address
* @param _callee called address
*/
modifier onlyWhitelistedCallee(address _callee) {
if (callRestricted) {
require(_isCalleeWhitelisted(_callee), "Controller: callee is not a whitelisted address");
}
_;
}
/**
* @dev check if the system is not in a partiallyPaused state
*/
function _isNotPartiallyPaused() internal view {
require(!systemPartiallyPaused, "Controller: system is partially paused");
}
/**
* @dev check if the system is not in an fullyPaused state
*/
function _isNotFullyPaused() internal view {
require(!systemFullyPaused, "Controller: system is fully paused");
}
/**
* @dev check if the sender is an authorized operator
* @param _sender msg.sender
* @param _accountOwner owner of a vault
*/
function _isAuthorized(address _sender, address _accountOwner) internal view {
require(
(_sender == _accountOwner) || (operators[_accountOwner][_sender]),
"Controller: msg.sender is not authorized to run action"
);
}
/**
* @notice initalize the deployed contract
* @param _addressBook addressbook module
* @param _owner account owner address
*/
function initialize(address _addressBook, address _owner) external initializer {
require(_addressBook != address(0), "Controller: invalid addressbook address");
require(_owner != address(0), "Controller: invalid owner address");
__Ownable_init(_owner);
__ReentrancyGuard_init_unchained();
addressbook = AddressBookInterface(_addressBook);
_refreshConfigInternal();
}
/**
* @notice allows the partialPauser to toggle the systemPartiallyPaused variable and partially pause or partially unpause the system
* @dev can only be called by the partialPauser
* @param _partiallyPaused new boolean value to set systemPartiallyPaused to
*/
function setSystemPartiallyPaused(bool _partiallyPaused) external onlyPartialPauser {
require(systemPartiallyPaused != _partiallyPaused, "Controller: invalid input");
systemPartiallyPaused = _partiallyPaused;
emit SystemPartiallyPaused(systemPartiallyPaused);
}
/**
* @notice allows the fullPauser to toggle the systemFullyPaused variable and fully pause or fully unpause the system
* @dev can only be called by the fullPauser
* @param _fullyPaused new boolean value to set systemFullyPaused to
*/
function setSystemFullyPaused(bool _fullyPaused) external onlyFullPauser {
require(systemFullyPaused != _fullyPaused, "Controller: invalid input");
systemFullyPaused = _fullyPaused;
emit SystemFullyPaused(systemFullyPaused);
}
/**
* @notice allows the owner to set the fullPauser address
* @dev can only be called by the owner
* @param _fullPauser new fullPauser address
*/
function setFullPauser(address _fullPauser) external onlyOwner {
require(_fullPauser != address(0), "Controller: fullPauser cannot be set to address zero");
require(fullPauser != _fullPauser, "Controller: invalid input");
emit FullPauserUpdated(fullPauser, _fullPauser);
fullPauser = _fullPauser;
}
/**
* @notice allows the owner to set the partialPauser address
* @dev can only be called by the owner
* @param _partialPauser new partialPauser address
*/
function setPartialPauser(address _partialPauser) external onlyOwner {
require(_partialPauser != address(0), "Controller: partialPauser cannot be set to address zero");
require(partialPauser != _partialPauser, "Controller: invalid input");
emit PartialPauserUpdated(partialPauser, _partialPauser);
partialPauser = _partialPauser;
}
/**
* @notice allows the owner to toggle the restriction on whitelisted call actions and only allow whitelisted
* call addresses or allow any arbitrary call addresses
* @dev can only be called by the owner
* @param _isRestricted new call restriction state
*/
function setCallRestriction(bool _isRestricted) external onlyOwner {
require(callRestricted != _isRestricted, "Controller: invalid input");
callRestricted = _isRestricted;
emit CallRestricted(callRestricted);
}
/**
* @notice allows a user to give or revoke privileges to an operator which can act on their behalf on their vaults
* @dev can only be updated by the vault owner
* @param _operator operator that the sender wants to give privileges to or revoke them from
* @param _isOperator new boolean value that expresses if the sender is giving or revoking privileges for _operator
*/
function setOperator(address _operator, bool _isOperator) external {
require(operators[msg.sender][_operator] != _isOperator, "Controller: invalid input");
operators[msg.sender][_operator] = _isOperator;
emit AccountOperatorUpdated(msg.sender, _operator, _isOperator);
}
/**
* @dev updates the configuration of the controller. can only be called by the owner
*/
function refreshConfiguration() external onlyOwner {
_refreshConfigInternal();
}
/**
* @notice execute a number of actions on specific vaults
* @dev can only be called when the system is not fully paused
* @param _actions array of actions arguments
*/
function operate(Actions.ActionArgs[] memory _actions) external nonReentrant notFullyPaused {
(bool vaultUpdated, address vaultOwner, uint256 vaultId) = _runActions(_actions);
if (vaultUpdated) _verifyFinalState(vaultOwner, vaultId);
}
/**
* @notice check if a specific address is an operator for an owner account
* @param _owner account owner address
* @param _operator account operator address
* @return True if the _operator is an approved operator for the _owner account
*/
function isOperator(address _owner, address _operator) external view returns (bool) {
return operators[_owner][_operator];
}
/**
* @notice returns the current controller configuration
* @return whitelist, the address of the whitelist module
* @return oracle, the address of the oracle module
* @return calculator, the address of the calculator module
* @return pool, the address of the pool module
*/
function getConfiguration()
external
view
returns (
address,
address,
address,
address
)
{
return (address(whitelist), address(oracle), address(calculator), address(pool));
}
/**
* @notice return a vault's proceeds pre or post expiry, the amount of collateral that can be removed from a vault
* @param _owner account owner of the vault
* @param _vaultId vaultId to return balances for
* @return amount of collateral that can be taken out
*/
function getProceed(address _owner, uint256 _vaultId) external view returns (uint256) {
MarginVault.Vault memory vault = getVault(_owner, _vaultId);
(uint256 netValue, ) = calculator.getExcessCollateral(vault);
return netValue;
}
/**
* @notice get an oToken's payout/cash value after expiry, in the collateral asset
* @param _otoken oToken address
* @param _amount amount of the oToken to calculate the payout for, always represented in 1e8
* @return amount of collateral to pay out
*/
function getPayout(address _otoken, uint256 _amount) public view returns (uint256) {
uint256 rate = calculator.getExpiredPayoutRate(_otoken);
return rate.mul(_amount).div(10**BASE);
}
/**
* @dev return if an expired oToken contract’s settlement price has been finalized
* @param _otoken address of the oToken
* @return True if the oToken has expired AND all oracle prices at the expiry timestamp have been finalized, False if not
*/
function isSettlementAllowed(address _otoken) public view returns (bool) {
OtokenInterface otoken = OtokenInterface(_otoken);
address underlying = otoken.underlyingAsset();
address strike = otoken.strikeAsset();
address collateral = otoken.collateralAsset();
uint256 expiry = otoken.expiryTimestamp();
bool isUnderlyingFinalized = oracle.isDisputePeriodOver(underlying, expiry);
bool isStrikeFinalized = oracle.isDisputePeriodOver(strike, expiry);
bool isCollateralFinalized = oracle.isDisputePeriodOver(collateral, expiry);
return isUnderlyingFinalized && isStrikeFinalized && isCollateralFinalized;
}
/**
* @notice get the number of vaults for a specified account owner
* @param _accountOwner account owner address
* @return number of vaults
*/
function getAccountVaultCounter(address _accountOwner) external view returns (uint256) {
return accountVaultCounter[_accountOwner];
}
/**
* @notice check if an oToken has expired
* @param _otoken oToken address
* @return True if the otoken has expired, False if not
*/
function hasExpired(address _otoken) external view returns (bool) {
uint256 otokenExpiryTimestamp = OtokenInterface(_otoken).expiryTimestamp();
return now >= otokenExpiryTimestamp;
}
/**
* @notice return a specific vault
* @param _owner account owner
* @param _vaultId vault id of vault to return
* @return Vault struct that corresponds to the _vaultId of _owner
*/
function getVault(address _owner, uint256 _vaultId) public view returns (MarginVault.Vault memory) {
return vaults[_owner][_vaultId];
}
/**
* @notice execute a variety of actions
* @dev for each action in the action array, execute the corresponding action, only one vault can be modified
* for all actions except SettleVault, Redeem, and Call
* @param _actions array of type Actions.ActionArgs[], which expresses which actions the user wants to execute
* @return vaultUpdated, indicates if a vault has changed
* @return owner, the vault owner if a vault has changed
* @return vaultId, the vault Id if a vault has changed
*/
function _runActions(Actions.ActionArgs[] memory _actions)
internal
returns (
bool,
address,
uint256
)
{
address vaultOwner;
uint256 vaultId;
bool vaultUpdated;
for (uint256 i = 0; i < _actions.length; i++) {
Actions.ActionArgs memory action = _actions[i];
Actions.ActionType actionType = action.actionType;
if (
(actionType != Actions.ActionType.SettleVault) &&
(actionType != Actions.ActionType.Redeem) &&
(actionType != Actions.ActionType.Call)
) {
// check if this action is manipulating the same vault as all other actions, if a vault has already been updated
if (vaultUpdated) {
require(vaultOwner == action.owner, "Controller: can not run actions for different owners");
require(vaultId == action.vaultId, "Controller: can not run actions on different vaults");
}
vaultUpdated = true;
vaultId = action.vaultId;
vaultOwner = action.owner;
}
if (actionType == Actions.ActionType.OpenVault) {
_openVault(Actions._parseOpenVaultArgs(action));
} else if (actionType == Actions.ActionType.DepositLongOption) {
_depositLong(Actions._parseDepositArgs(action));
} else if (actionType == Actions.ActionType.WithdrawLongOption) {
_withdrawLong(Actions._parseWithdrawArgs(action));
} else if (actionType == Actions.ActionType.DepositCollateral) {
_depositCollateral(Actions._parseDepositArgs(action));
} else if (actionType == Actions.ActionType.WithdrawCollateral) {
_withdrawCollateral(Actions._parseWithdrawArgs(action));
} else if (actionType == Actions.ActionType.MintShortOption) {
_mintOtoken(Actions._parseMintArgs(action));
} else if (actionType == Actions.ActionType.BurnShortOption) {
_burnOtoken(Actions._parseBurnArgs(action));
} else if (actionType == Actions.ActionType.Redeem) {
_redeem(Actions._parseRedeemArgs(action));
} else if (actionType == Actions.ActionType.SettleVault) {
_settleVault(Actions._parseSettleVaultArgs(action));
} else if (actionType == Actions.ActionType.Call) {
_call(Actions._parseCallArgs(action));
}
}
return (vaultUpdated, vaultOwner, vaultId);
}
/**
* @notice verify the vault final state after executing all actions
* @param _owner account owner address
* @param _vaultId vault id of the final vault
*/
function _verifyFinalState(address _owner, uint256 _vaultId) internal view {
MarginVault.Vault memory _vault = getVault(_owner, _vaultId);
(, bool isValidVault) = calculator.getExcessCollateral(_vault);
require(isValidVault, "Controller: invalid final vault state");
}
/**
* @notice open a new vault inside an account
* @dev only the account owner or operator can open a vault, cannot be called when system is partiallyPaused or fullyPaused
* @param _args OpenVaultArgs structure
*/
function _openVault(Actions.OpenVaultArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
accountVaultCounter[_args.owner] = accountVaultCounter[_args.owner].add(1);
require(
_args.vaultId == accountVaultCounter[_args.owner],
"Controller: can not run actions on inexistent vault"
);
emit VaultOpened(_args.owner, accountVaultCounter[_args.owner]);
}
/**
* @notice deposit a long oToken into a vault
* @dev only the account owner or operator can deposit a long oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args DepositArgs structure
*/
function _depositLong(Actions.DepositArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
require(
(_args.from == msg.sender) || (_args.from == _args.owner),
"Controller: cannot deposit long otoken from this address"
);
require(
whitelist.isWhitelistedOtoken(_args.asset),
"Controller: otoken is not whitelisted to be used as collateral"
);
OtokenInterface otoken = OtokenInterface(_args.asset);
require(now < otoken.expiryTimestamp(), "Controller: otoken used as collateral is already expired");
vaults[_args.owner][_args.vaultId].addLong(_args.asset, _args.amount, _args.index);
pool.transferToPool(_args.asset, _args.from, _args.amount);
emit LongOtokenDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount);
}
/**
* @notice withdraw a long oToken from a vault
* @dev only the account owner or operator can withdraw a long oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args WithdrawArgs structure
*/
function _withdrawLong(Actions.WithdrawArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
OtokenInterface otoken = OtokenInterface(_args.asset);
require(now < otoken.expiryTimestamp(), "Controller: can not withdraw an expired otoken");
vaults[_args.owner][_args.vaultId].removeLong(_args.asset, _args.amount, _args.index);
pool.transferToUser(_args.asset, _args.to, _args.amount);
emit LongOtokenWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount);
}
/**
* @notice deposit a collateral asset into a vault
* @dev only the account owner or operator can deposit collateral, cannot be called when system is partiallyPaused or fullyPaused
* @param _args DepositArgs structure
*/
function _depositCollateral(Actions.DepositArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
require(
(_args.from == msg.sender) || (_args.from == _args.owner),
"Controller: cannot deposit collateral from this address"
);
require(
whitelist.isWhitelistedCollateral(_args.asset),
"Controller: asset is not whitelisted to be used as collateral"
);
vaults[_args.owner][_args.vaultId].addCollateral(_args.asset, _args.amount, _args.index);
pool.transferToPool(_args.asset, _args.from, _args.amount);
emit CollateralAssetDeposited(_args.asset, _args.owner, _args.from, _args.vaultId, _args.amount);
}
/**
* @notice withdraw a collateral asset from a vault
* @dev only the account owner or operator can withdraw collateral, cannot be called when system is partiallyPaused or fullyPaused
* @param _args WithdrawArgs structure
*/
function _withdrawCollateral(Actions.WithdrawArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
MarginVault.Vault memory vault = getVault(_args.owner, _args.vaultId);
if (_isNotEmpty(vault.shortOtokens)) {
OtokenInterface otoken = OtokenInterface(vault.shortOtokens[0]);
require(
now < otoken.expiryTimestamp(),
"Controller: can not withdraw collateral from a vault with an expired short otoken"
);
}
vaults[_args.owner][_args.vaultId].removeCollateral(_args.asset, _args.amount, _args.index);
pool.transferToUser(_args.asset, _args.to, _args.amount);
emit CollateralAssetWithdrawed(_args.asset, _args.owner, _args.to, _args.vaultId, _args.amount);
}
/**
* @notice mint short oTokens from a vault which creates an obligation that is recorded in the vault
* @dev only the account owner or operator can mint an oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args MintArgs structure
*/
function _mintOtoken(Actions.MintArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
require(whitelist.isWhitelistedOtoken(_args.otoken), "Controller: otoken is not whitelisted to be minted");
OtokenInterface otoken = OtokenInterface(_args.otoken);
require(now < otoken.expiryTimestamp(), "Controller: can not mint expired otoken");
vaults[_args.owner][_args.vaultId].addShort(_args.otoken, _args.amount, _args.index);
otoken.mintOtoken(_args.to, _args.amount);
emit ShortOtokenMinted(_args.otoken, _args.owner, _args.to, _args.vaultId, _args.amount);
}
/**
* @notice burn oTokens to reduce or remove the minted oToken obligation recorded in a vault
* @dev only the account owner or operator can burn an oToken, cannot be called when system is partiallyPaused or fullyPaused
* @param _args MintArgs structure
*/
function _burnOtoken(Actions.BurnArgs memory _args)
internal
notPartiallyPaused
onlyAuthorized(msg.sender, _args.owner)
{
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
require((_args.from == msg.sender) || (_args.from == _args.owner), "Controller: cannot burn from this address");
OtokenInterface otoken = OtokenInterface(_args.otoken);
require(now < otoken.expiryTimestamp(), "Controller: can not burn expired otoken");
vaults[_args.owner][_args.vaultId].removeShort(_args.otoken, _args.amount, _args.index);
otoken.burnOtoken(_args.from, _args.amount);
emit ShortOtokenBurned(_args.otoken, _args.owner, _args.from, _args.vaultId, _args.amount);
}
/**
* @notice redeem an oToken after expiry, receiving the payout of the oToken in the collateral asset
* @dev cannot be called when system is fullyPaused
* @param _args RedeemArgs structure
*/
function _redeem(Actions.RedeemArgs memory _args) internal {
OtokenInterface otoken = OtokenInterface(_args.otoken);
require(whitelist.isWhitelistedOtoken(_args.otoken), "Controller: otoken is not whitelisted to be redeemed");
require(now >= otoken.expiryTimestamp(), "Controller: can not redeem un-expired otoken");
require(isSettlementAllowed(_args.otoken), "Controller: asset prices not finalized yet");
uint256 payout = getPayout(_args.otoken, _args.amount);
otoken.burnOtoken(msg.sender, _args.amount);
pool.transferToUser(otoken.collateralAsset(), _args.receiver, payout);
emit Redeem(_args.otoken, msg.sender, _args.receiver, otoken.collateralAsset(), _args.amount, payout);
}
/**
* @notice settle a vault after expiry, removing the net proceeds/collateral after both long and short oToken payouts have settled
* @dev deletes a vault of vaultId after net proceeds/collateral is removed, cannot be called when system is fullyPaused
* @param _args SettleVaultArgs structure
*/
function _settleVault(Actions.SettleVaultArgs memory _args) internal onlyAuthorized(msg.sender, _args.owner) {
require(_checkVaultId(_args.owner, _args.vaultId), "Controller: invalid vault id");
MarginVault.Vault memory vault = getVault(_args.owner, _args.vaultId);
bool hasShort = _isNotEmpty(vault.shortOtokens);
bool hasLong = _isNotEmpty(vault.longOtokens);
require(hasShort || hasLong, "Controller: Can't settle vault with no otoken");
OtokenInterface otoken = hasShort
? OtokenInterface(vault.shortOtokens[0])
: OtokenInterface(vault.longOtokens[0]);
require(now >= otoken.expiryTimestamp(), "Controller: can not settle vault with un-expired otoken");
require(isSettlementAllowed(address(otoken)), "Controller: asset prices not finalized yet");
(uint256 payout, ) = calculator.getExcessCollateral(vault);
if (hasLong) {
OtokenInterface longOtoken = OtokenInterface(vault.longOtokens[0]);
longOtoken.burnOtoken(address(pool), vault.longAmounts[0]);
}
delete vaults[_args.owner][_args.vaultId];
pool.transferToUser(otoken.collateralAsset(), _args.to, payout);
emit VaultSettled(_args.owner, _args.to, address(otoken), _args.vaultId, payout);
}
/**
* @notice execute arbitrary calls
* @dev cannot be called when system is partiallyPaused or fullyPaused
* @param _args Call action
*/
function _call(Actions.CallArgs memory _args)
internal
notPartiallyPaused
onlyWhitelistedCallee(_args.callee)
returns (uint256)
{
CalleeInterface(_args.callee).callFunction(msg.sender, _args.data);
emit CallExecuted(msg.sender, _args.callee, _args.data);
}
/**
* @notice check if a vault id is valid for a given account owner address
* @param _accountOwner account owner address
* @param _vaultId vault id to check
* @return True if the _vaultId is valid, False if not
*/
function _checkVaultId(address _accountOwner, uint256 _vaultId) internal view returns (bool) {
return ((_vaultId > 0) && (_vaultId <= accountVaultCounter[_accountOwner]));
}
function _isNotEmpty(address[] memory _array) internal pure returns (bool) {
return (_array.length > 0) && (_array[0] != address(0));
}
/**
* @notice return if a callee address is whitelisted or not
* @param _callee callee address
* @return True if callee address is whitelisted, False if not
*/
function _isCalleeWhitelisted(address _callee) internal view returns (bool) {
return whitelist.isWhitelistedCallee(_callee);
}
/**
* @dev updates the internal configuration of the controller
*/
function _refreshConfigInternal() internal {
whitelist = WhitelistInterface(addressbook.getWhitelist());
oracle = OracleInterface(addressbook.getOracle());
calculator = MarginCalculatorInterface(addressbook.getMarginCalculator());
pool = MarginPoolInterface(addressbook.getMarginPool());
}
}
|
check if an oToken has expired _otoken oToken address return True if the otoken has expired, False if not/
|
function hasExpired(address _otoken) external view returns (bool) {
uint256 otokenExpiryTimestamp = OtokenInterface(_otoken).expiryTimestamp();
return now >= otokenExpiryTimestamp;
}
| 942,804 |
/**
*Submitted for verification at Etherscan.io on 2020-11-05
*/
/*
website: bns.finance
This project is freshly written to change the way ICO is done.
BBBBBBBBBBBBBBBBB NNNNNNNN NNNNNNNN SSSSSSSSSSSSSSS DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFFFFFFFFFFFFFIIIIIIIIII
B::::::::::::::::B N:::::::N N::::::N SS:::::::::::::::S D::::::::::::DDD E::::::::::::::::::::EF::::::::::::::::::::FI::::::::I
B::::::BBBBBB:::::B N::::::::N N::::::NS:::::SSSSSS::::::S D:::::::::::::::DD E::::::::::::::::::::EF::::::::::::::::::::FI::::::::I
BB:::::B B:::::BN:::::::::N N::::::NS:::::S SSSSSSS DDD:::::DDDDD:::::DEE::::::EEEEEEEEE::::EFF::::::FFFFFFFFF::::FII::::::II
B::::B B:::::BN::::::::::N N::::::NS:::::S D:::::D D:::::D E:::::E EEEEEE F:::::F FFFFFF I::::I
B::::B B:::::BN:::::::::::N N::::::NS:::::S D:::::D D:::::DE:::::E F:::::F I::::I
B::::BBBBBB:::::B N:::::::N::::N N::::::N S::::SSSS D:::::D D:::::DE::::::EEEEEEEEEE F::::::FFFFFFFFFF I::::I
B:::::::::::::BB N::::::N N::::N N::::::N SS::::::SSSSS D:::::D D:::::DE:::::::::::::::E F:::::::::::::::F I::::I
B::::BBBBBB:::::B N::::::N N::::N:::::::N SSS::::::::SS D:::::D D:::::DE:::::::::::::::E F:::::::::::::::F I::::I
B::::B B:::::BN::::::N N:::::::::::N SSSSSS::::S D:::::D D:::::DE::::::EEEEEEEEEE F::::::FFFFFFFFFF I::::I
B::::B B:::::BN::::::N N::::::::::N S:::::S D:::::D D:::::DE:::::E F:::::F I::::I
B::::B B:::::BN::::::N N:::::::::N S:::::S D:::::D D:::::D E:::::E EEEEEE F:::::F I::::I
BB:::::BBBBBB::::::BN::::::N N::::::::NSSSSSSS S:::::S DDD:::::DDDDD:::::DEE::::::EEEEEEEE:::::EFF:::::::FF II::::::II
B:::::::::::::::::B N::::::N N:::::::NS::::::SSSSSS:::::S ...... D:::::::::::::::DD E::::::::::::::::::::EF::::::::FF I::::::::I
B::::::::::::::::B N::::::N N::::::NS:::::::::::::::SS .::::. D::::::::::::DDD E::::::::::::::::::::EF::::::::FF I::::::::I
BBBBBBBBBBBBBBBBB NNNNNNNN NNNNNNN SSSSSSSSSSSSSSS ...... DDDDDDDDDDDDD EEEEEEEEEEEEEEEEEEEEEEFFFFFFFFFFF IIIIIIIIII
*/
// SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
/*
* @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;
}
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SAO");
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, "SMO");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "IB");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "RR");
}
/**
* @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, "IBC");
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), "CNC");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length != 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "DAB0");
_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, "LF1");
if (returndata.length != 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "LF2");
}
}
}
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 public _totalSupply;
string public _name;
string public _symbol;
uint8 public _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
// /**
// * @dev Returns the name of the token.
// */
// function name() public view returns (string memory) {
// return _name;
// }
// /**
// * @dev Returns the symbol of the token, usually a shorter version of the
// * name.
// */
// function symbol() public view returns (string memory) {
// return _symbol;
// }
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
// function decimals() public view returns (uint8) {
// return _decimals;
// }
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ISA");
require(recipient != address(0), "IRA");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "TIF");
_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), "M0");
_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), "B0");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "BIB");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "IA");
require(spender != address(0), "A0");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
// /**
// * @dev Sets {decimals} to a value other than the default one of 18.
// *
// * WARNING: This function should only be called from the constructor. Most
// * applications that interact with token contracts will not expect
// * {decimals} to ever change, and may work incorrectly if it does.
// */
// function _setupDecimals(uint8 decimals_) internal {
// _decimals = decimals_;
// }
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
contract BnsdLaunchPool is Context {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of a raising pool.
struct RaisePoolInfo {
IERC20 raiseToken; // Address of raising token contract.
uint256 maxTokensPerPerson; // Maximum tokens a user can buy.
uint256 totalTokensOnSale; // Total tokens available on offer.
uint256 startBlock; // When the sale starts
uint256 endBlock; // When the sale ends
uint256 totalTokensSold; // Total tokens sold to users so far
uint256 tokensDeposited; // Total ICO tokens deposited
uint256 votes; // Voted by users
address owner; // Owner of the pool
bool updateLocked; // No pool info can be updated once this is turned ON
bool balanceAdded; // Whether ICO tokens are added in correct amount
bool paymentMethodAdded; // Supported currencies added or not
string poolName; // Human readable string name of the pool
}
struct AirdropPoolInfo {
uint256 totalTokensAvailable; // Total tokens staked so far.
IERC20 airdropToken; // Address of staking LP token.
bool airdropExists;
}
// Info of a raising pool.
struct UseCasePoolInfo {
uint256 tokensAllocated; // Total tokens available for this use
uint256 tokensClaimed; // Total tokens claimed
address reserveAdd; // Address where tokens will be released for that usecase.
bool tokensDeposited; // No pool info can be updated once this is turned ON
bool exists; // Whether reserve already exists for a pool
string useName; // Human readable string name of the pool
uint256[] unlock_perArray; // Release percent for usecase
uint256[] unlock_daysArray; // Release days for usecase
}
struct DistributionInfo {
uint256[] percentArray; // Percentage of tokens to be unlocked every phase
uint256[] daysArray; // Days from the endDate when tokens starts getting unlocked
}
// The BNSD TOKEN!
address public timeLock;
// Dev address.
address public devaddr;
// Temp dev address while switching
address private potentialAdmin;
// To store owner diistribution info after sale ends
mapping (uint256 => DistributionInfo) private ownerDistInfo;
// To store user distribution info after sale ends
mapping (uint256 => DistributionInfo) private userDistInfo;
// To store tokens on sale and their rates
mapping (uint256 => mapping (address => uint256)) public saleRateInfo;
// To store invite codes and corresponding token address and pool owners, INVITE CODE => TOKEN => OWNER => bool
mapping (uint256 => mapping (address => mapping (address => bool))) private inviteCodeList;
// To store user contribution for a sale - POOL => USER => USDT
mapping (uint256 => mapping (address => mapping (address => uint256))) public userDepositInfo;
// To store total token promised to a user - POOL => USER
mapping (uint256 => mapping (address => uint256)) public userTokenAllocation;
// To store total token claimed by a user already
mapping (uint256 => mapping (address => uint256)) public userTokenClaimed;
// To store total token redeemed by users after sale
mapping (uint256 => uint256) public totalTokenClaimed;
// To store total token raised by a project - POOL => TOKEN => AMT
mapping (uint256 => mapping (address => uint256)) public fundsRaisedSoFar;
mapping (uint256 => address) private tempAdmin;
// To store total token claimed by a project
mapping (uint256 => mapping (address => uint256)) public fundsClaimedSoFar;
// To store addresses voted for a project - POOL => USER => BOOL
mapping (uint256 => mapping (address => bool)) public userVotes;
// No of blocks in a day - 6700
uint256 public constant BLOCKS_PER_DAY = 6700; // Changing to 5 for test cases
// Info of each pool on blockchain.
RaisePoolInfo[] public poolInfo;
// Info of reserve pool of any project - POOL => RESERVE_ADD => USECASEINFO
mapping (uint256 => mapping (address => UseCasePoolInfo)) public useCaseInfo;
// To store total token reserved
mapping (uint256 => uint256) public totalTokenReserved;
// To store total reserved claimed
mapping (uint256 => uint256) public totalReservedTokenClaimed;
// To store list of all sales associated with a token
mapping (address => uint256[]) public listSaleTokens;
// To store list of all currencies allowed for a sale
mapping (uint256 => address[]) public listSupportedCurrencies;
// To store list of all reserve addresses for a sale
mapping (uint256 => address[]) public listReserveAddresses;
// To check if staking is enabled on a token
mapping (address => bool) public stakingEnabled;
// To get staking weight of a token
mapping (address => uint256) public stakingWeight;
// To store sum of weight of all staking tokens
uint256 public totalStakeWeight;
// To store list of staking addresses
address[] public stakingPools;
// To store stats of staked tokens per sale
mapping (uint256 => mapping (address => uint256)) public stakedLPTokensInfo;
// To store user staked amount for a sale - POOL => USER => LP_TOKEN
mapping (uint256 => mapping (address => mapping (address => uint256))) public userStakeInfo;
// To store reward claimed by a user - POOL => USER => BOOL
mapping (uint256 => mapping (address => bool)) public rewardClaimed;
// To store airdrop claimed by a user - POOL => USER => BOOL
mapping (uint256 => mapping (address => bool)) public airdropClaimed;
// To store extra airdrop tokens withdrawn by fund raiser - POOL => BOOL
mapping (uint256 => bool) public extraAirdropClaimed;
// To store airdrop info for a sale
mapping (uint256 => AirdropPoolInfo) public airdropInfo;
// To store airdrop tokens balance of a user , TOKEN => USER => BAL
mapping (address => mapping (address => uint256)) public airdropBalances;
uint256 public fee = 300; // To be divided by 1e4 before using it anywhere => 3.00%
uint256 public constant rewardPer = 8000; // To be divided by 1e4 before using it anywhere => 80.00%
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Stake(address indexed user, address indexed lptoken, uint256 indexed pid, uint256 amount);
event UnStake(address indexed user, address indexed lptoken, uint256 indexed pid, uint256 amount);
event MoveStake(address indexed user, address indexed lptoken, uint256 pid, uint256 indexed pidnew, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event WithdrawAirdrop(address indexed user, address indexed token, uint256 amount);
event ClaimAirdrop(address indexed user, address indexed token, uint256 amount);
event AirdropDeposit(address indexed user, address indexed token, uint256 indexed pid, uint256 amount);
event AirdropExtraWithdraw(address indexed user, address indexed token, uint256 indexed pid, uint256 amount);
event Voted(address indexed user, uint256 indexed pid);
constructor() public {
devaddr = _msgSender();
}
modifier onlyAdmin() {
require(devaddr == _msgSender(), "ND");
_;
}
modifier onlyAdminOrTimeLock() {
require((devaddr == _msgSender() || timeLock == _msgSender()), "ND");
_;
}
function setTimeLockAdd(address _add) public onlyAdmin {
timeLock = _add;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function getListOfSale(address _token) external view returns (uint256[] memory) {
return listSaleTokens[_token];
}
function getUserDistPercent(uint256 _pid) external view returns (uint256[] memory) {
return userDistInfo[_pid].percentArray;
}
function getUserDistDays(uint256 _pid) external view returns (uint256[] memory) {
return userDistInfo[_pid].daysArray;
}
function getReserveUnlockPercent(uint256 _pid, address _reserveAdd) external view returns (uint256[] memory) {
return useCaseInfo[_pid][_reserveAdd].unlock_perArray;
}
function getReserveUnlockDays(uint256 _pid, address _reserveAdd) external view returns (uint256[] memory) {
return useCaseInfo[_pid][_reserveAdd].unlock_daysArray;
}
function getUserDistBlocks(uint256 _pid) external view returns (uint256[] memory) {
uint256[] memory daysArray = userDistInfo[_pid].daysArray;
uint256 endPool = poolInfo[_pid].endBlock;
for(uint256 i=0; i<daysArray.length; i++){
daysArray[i] = (daysArray[i].mul(BLOCKS_PER_DAY)).add(endPool);
}
return daysArray;
}
function getOwnerDistPercent(uint256 _pid) external view returns (uint256[] memory) {
return ownerDistInfo[_pid].percentArray;
}
function getOwnerDistDays(uint256 _pid) external view returns (uint256[] memory) {
return ownerDistInfo[_pid].daysArray;
}
// Add a new token sale to the pool. Can only be called by the person having the invite code.
function addNewPool(uint256 totalTokens, uint256 maxPerPerson, uint256 startBlock, uint256 endBlock, string memory namePool, IERC20 tokenAddress, uint256 _inviteCode) external returns (uint256) {
require(endBlock > startBlock, "ESC"); // END START COMPARISON FAILED
require(startBlock > block.number, "TLS"); // TIME LIMIT START SALE
require(maxPerPerson !=0 && totalTokens!=0, "IIP"); // INVALID INDIVIDUAL PER PERSON
require(inviteCodeList[_inviteCode][address(tokenAddress)][_msgSender()]==true,"IIC"); // INVALID INVITE CODE
poolInfo.push(RaisePoolInfo({
raiseToken: tokenAddress,
maxTokensPerPerson: maxPerPerson,
totalTokensOnSale: totalTokens,
startBlock: startBlock,
endBlock: endBlock,
poolName: namePool,
updateLocked: false,
owner: _msgSender(),
totalTokensSold: 0,
balanceAdded: false,
tokensDeposited: 0,
paymentMethodAdded: false,
votes: 0
}));
uint256 poolId = (poolInfo.length - 1);
listSaleTokens[address(tokenAddress)].push(poolId);
// This makes the invite code claimed
inviteCodeList[_inviteCode][address(tokenAddress)][_msgSender()] = false;
return poolId;
}
function _checkSumArray(uint256[] memory _percentArray) internal pure returns (bool) {
uint256 _sum;
for (uint256 i = 0; i < _percentArray.length; i++) {
_sum = _sum.add(_percentArray[i]);
}
return (_sum==10000);
}
function _checkValidDaysArray(uint256[] memory _daysArray) internal pure returns (bool) {
uint256 _lastDay = _daysArray[0];
for (uint256 i = 1; i < _daysArray.length; i++) {
if(_lastDay < _daysArray[i]){
_lastDay = _daysArray[i];
}
else {
return false;
}
}
return true;
}
function _checkUpdateAllowed(uint256 _pid) internal view{
RaisePoolInfo storage pool = poolInfo[_pid];
require(pool.updateLocked == false, "CT2"); // CRITICAL TERMINATION 2
require(pool.owner==_msgSender(), "OAU"); // OWNER AUTHORIZATION FAILED
require(pool.startBlock > block.number, "CT"); // CRITICAL TERMINATION
}
// Add rule for funds locking after sale
function updateUserDistributionRule(uint256 _pid, uint256[] memory _percentArray, uint256[] memory _daysArray) external {
require(_percentArray.length == _daysArray.length, "LM"); // LENGTH MISMATCH
_checkUpdateAllowed(_pid);
require(_checkSumArray(_percentArray), "SE"); // SUM OF PERCENT INVALID
require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING
userDistInfo[_pid] = DistributionInfo({
percentArray: _percentArray,
daysArray: _daysArray
});
}
// Add rule for funds unlocking of the fund raiser after sale
function updateOwnerDistributionRule(uint256 _pid, uint256[] memory _percentArray, uint256[] memory _daysArray) external {
require(_percentArray.length == _daysArray.length, "LM"); // LENGTH MISMATCH
_checkUpdateAllowed(_pid);
require(_checkSumArray(_percentArray), "SE"); // SUM OF PERCENT INVALID
require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING
ownerDistInfo[_pid] = DistributionInfo({
percentArray: _percentArray,
daysArray: _daysArray
});
}
// Lock sale detail changes in future
function lockPool(uint256 _pid) external {
require(poolInfo[_pid].paymentMethodAdded==true, "CP"); // CHECK PAYMENT METHOD FAILED
_checkUpdateAllowed(_pid);
poolInfo[_pid].updateLocked = true;
}
// Add supported currencies and their rate w.r.t token on sale
// rateToken = price of one satoshi of the token in terms of token to be raised * 1e18
// 1 BNSD = 0.00021 ETH => 1e18 BNSD Satoshi = 0.00021 * 1e18 ETH satoshi => 1 BNSD Satoshi = 0.00021 ETH satoshi => rateToken = 0.00021 * 1e18 = 21 * 1e13
// rateToken for BNSD/ETH pair = 21 * 1e13;
function addSupportedCurrencies(uint256 _pid, address _tokenRaise, uint256 rateToken) external {
_checkUpdateAllowed(_pid);
require(rateToken!=0, "IR"); // INVALID RATE
require(_tokenRaise!=address(poolInfo[_pid].raiseToken), "IT"); // INVALIID PURCHASE TOKEN
if(address(this).balance == 0){ //inject PRESENT ETHER
listSupportedCurrencies[_pid].push(_tokenRaise);
}
saleRateInfo[_pid][_tokenRaise] = rateToken;
poolInfo[_pid].paymentMethodAdded = true;
}
function getSupportedCurrencies(uint256 _pid) external view returns (address[] memory) {
return listSupportedCurrencies[_pid];
}
function _checkUpdateReserveAllowed(uint256 _pid, address _resAdd) internal view returns (bool) {
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
return (poolU.exists == false || poolU.tokensDeposited == false);
// if(poolU.exists == false || poolU.tokensDeposited == false){
// return true;
// }
// return false;
}
function addReservePool(uint256 _pid, address _reserveAdd, string memory _nameReserve, uint256 _totalTokens, uint256[] memory _perArray, uint256[] memory _daysArray) external {
_checkUpdateAllowed(_pid);
require(_checkUpdateReserveAllowed(_pid, _reserveAdd) == true, "UB"); // UPDATE RESERVE FAILED
require(_checkSumArray(_perArray), "SE"); // SUM OF PERCENT INVALID
require(_checkValidDaysArray(_daysArray), "DMI"); // DAYS SHOULD BE MONOTONIICALLY INCREASING
require(_perArray.length==_daysArray.length, "IAL"); // INVALID ARRAY LENGTH
if(useCaseInfo[_pid][_reserveAdd].exists == false){
listReserveAddresses[_pid].push(_reserveAdd);
}
useCaseInfo[_pid][_reserveAdd] = UseCasePoolInfo({
reserveAdd: _reserveAdd,
useName: _nameReserve,
tokensAllocated: _totalTokens,
unlock_perArray: _perArray,
unlock_daysArray: _daysArray,
tokensDeposited: false,
tokensClaimed: 0,
exists: true
});
}
function getReserveAddresses(uint256 _pid) external view returns (address[] memory) {
return listReserveAddresses[_pid];
}
function tokensPurchaseAmt(uint256 _pid, address _tokenAdd, uint256 amt) public view returns (uint256) {
uint256 rateToken = saleRateInfo[_pid][_tokenAdd];
require(rateToken!=0, "NAT"); // NOT AVAILABLE TOKEN
return (amt.mul(1e18)).div(rateToken);
}
// Check if user can deposit specfic amount of funds to the pool
function _checkDepositAllowed(uint256 _pid, address _tokenAdd, uint256 _amt) internal view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
uint256 userBought = userTokenAllocation[_pid][_msgSender()];
uint256 purchasePossible = tokensPurchaseAmt(_pid, _tokenAdd, _amt);
require(pool.balanceAdded == true, "NA"); // NOT AVAILABLE
require(pool.startBlock <= block.number, "NT1"); // NOT AVAILABLE TIME 1
require(pool.endBlock >= block.number, "NT2"); // NOT AVAILABLE TIME 2
require(pool.totalTokensSold.add(purchasePossible) <= pool.totalTokensOnSale, "PLE"); // POOL LIMIT EXCEEDED
require(userBought.add(purchasePossible) <= pool.maxTokensPerPerson, "ILE"); // INDIVIDUAL LIMIT EXCEEDED
return purchasePossible;
}
// Check max a user can deposit right now
function getMaxDepositAllowed(uint256 _pid, address _tokenAdd, address _user) external view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
uint256 maxBuyPossible = (pool.maxTokensPerPerson).sub(userTokenAllocation[_pid][_user]);
uint256 maxBuyPossiblePoolLimit = (pool.totalTokensOnSale).sub(pool.totalTokensSold);
if(maxBuyPossiblePoolLimit < maxBuyPossible){
maxBuyPossible = maxBuyPossiblePoolLimit;
}
if(block.number >= pool.startBlock && block.number <= pool.endBlock && pool.balanceAdded == true){
uint256 rateToken = saleRateInfo[_pid][_tokenAdd];
return (maxBuyPossible.mul(rateToken).div(1e18));
}
else {
return 0;
}
}
// Check if deposit is enabled for a pool
function checkDepositEnabled(uint256 _pid) external view returns (bool){
RaisePoolInfo storage pool = poolInfo[_pid];
if(pool.balanceAdded == true && pool.startBlock <= block.number && pool.endBlock >= block.number && pool.totalTokensSold <= pool.totalTokensOnSale && pool.paymentMethodAdded==true){
return true;
}
else {
return false;
}
}
// Deposit ICO tokens to start a pool for ICO.
function depositICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
address msgSender = _msgSender();
require(_tokenAdd == pool.raiseToken, "NOT"); // NOT VALID TOKEN
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
require(block.number < pool.endBlock, "NT"); // No point adding tokens after sale has ended - Possible deadlock case
_tokenAdd.safeTransferFrom(msgSender, address(this), _amount);
pool.tokensDeposited = (pool.tokensDeposited).add(_amount);
if(pool.tokensDeposited >= pool.totalTokensOnSale){
pool.balanceAdded = true;
}
emit Deposit(msgSender, _pid, _amount);
}
// Deposit Airdrop tokens anytime before end of the sale.
function depositAirdropTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number < pool.endBlock, "NT"); // NOT VALID TIME
AirdropPoolInfo storage airdrop = airdropInfo[_pid];
require((_tokenAdd == airdrop.airdropToken || airdrop.airdropExists==false), "NOT"); // NOT VALID TOKEN
require(_msgSender() == pool.owner || _msgSender() == devaddr , "NAU"); // NOT AUTHORISED USER
_tokenAdd.safeTransferFrom(_msgSender(), address(this), _amount);
airdrop.totalTokensAvailable = (airdrop.totalTokensAvailable).add(_amount);
if(!airdrop.airdropExists){
airdrop.airdropToken = _tokenAdd;
airdrop.airdropExists = true;
}
emit AirdropDeposit(_msgSender(), address(_tokenAdd), _pid, _amount);
}
// Withdraw extra airdrop tokens - Possible only if no one added liquidity to one of the pools
function withdrawExtraAirdropTokens(uint256 _pid) external {
require(extraAirdropClaimed[_pid]==false, "NA"); // NOT AVAILABLE
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number > pool.endBlock, "NSE"); // SALE NOT ENDED
address msgSender = _msgSender();
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
uint256 extraTokens = calculateExtraAirdropTokens(_pid);
require(extraTokens!=0, "NAT"); // NOT AVAILABLE TOKEN
extraAirdropClaimed[_pid] = true;
airdropInfo[_pid].airdropToken.safeTransfer(msgSender, extraTokens);
emit AirdropExtraWithdraw(msg.sender, address(airdropInfo[_pid].airdropToken), _pid, extraTokens);
}
function calculateExtraAirdropTokens(uint256 _pid) public view returns (uint256){
if(extraAirdropClaimed[_pid] == true) return 0;
uint256 _totalTokens;
for (uint256 i=0; i<stakingPools.length; i++){
uint256 stake = stakedLPTokensInfo[_pid][stakingPools[i]];
if(address(this).balance == 0){ //inject PRESENT ETHER
_totalTokens = _totalTokens.add(((stakingWeight[stakingPools[i]]).mul(airdropInfo[_pid].totalTokensAvailable)).div(totalStakeWeight));
}
}
return _totalTokens;
}
// Deposit LP tokens for a sale.
function stakeLPTokens(uint256 _pid, uint256 _amount, IERC20 _lpAdd) external {
require(stakingEnabled[address(_lpAdd)]==true, "NST"); // NOT STAKING TOKEN
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number < pool.startBlock, "NT"); // NOT VALID TIME
address msgSender = _msgSender();
_lpAdd.safeTransferFrom(msgSender, address(this), _amount);
stakedLPTokensInfo[_pid][address(_lpAdd)] = (stakedLPTokensInfo[_pid][address(_lpAdd)]).add(_amount);
userStakeInfo[_pid][msgSender][address(_lpAdd)] = (userStakeInfo[_pid][msgSender][address(_lpAdd)]).add(_amount);
emit Stake(msg.sender, address(_lpAdd), _pid, _amount);
}
// Withdraw LP tokens from a sale after it's over => Automatically claims rewards and airdrops also
function withdrawLPTokens(uint256 _pid, uint256 _amount, IERC20 _lpAdd) external {
require(stakingEnabled[address(_lpAdd)]==true, "NAT"); // NOT AUTHORISED TOKEN
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number > pool.endBlock, "SE"); // SALE NOT ENDED
address msgSender = _msgSender();
claimRewardAndAirdrop(_pid);
userStakeInfo[_pid][msgSender][address(_lpAdd)] = (userStakeInfo[_pid][msgSender][address(_lpAdd)]).sub(_amount);
_lpAdd.safeTransfer(msgSender, _amount);
emit UnStake(msg.sender, address(_lpAdd), _pid, _amount);
}
// Withdraw airdrop tokens accumulated over one or more than one sale.
function withdrawAirdropTokens(IERC20 _token, uint256 _amount) external {
address msgSender = _msgSender();
airdropBalances[address(_token)][msgSender] = (airdropBalances[address(_token)][msgSender]).sub(_amount);
_token.safeTransfer(msgSender, _amount);
emit WithdrawAirdrop(msgSender, address(_token), _amount);
}
// Move LP tokens from one sale to another directly => Automatically claims rewards and airdrops also
function moveLPTokens(uint256 _pid, uint256 _newpid, uint256 _amount, address _lpAdd) external {
require(stakingEnabled[_lpAdd]==true, "NAT1"); // NOT AUTHORISED TOKEN 1
RaisePoolInfo storage poolOld = poolInfo[_pid];
RaisePoolInfo storage poolNew = poolInfo[_newpid];
require(block.number > poolOld.endBlock, "NUA"); // OLD SALE NOT ENDED
require(block.number < poolNew.startBlock, "NSA"); // SALE START CHECK FAILED
address msgSender = _msgSender();
claimRewardAndAirdrop(_pid);
userStakeInfo[_pid][msgSender][_lpAdd] = (userStakeInfo[_pid][msgSender][_lpAdd]).sub(_amount);
userStakeInfo[_newpid][msgSender][_lpAdd] = (userStakeInfo[_newpid][msgSender][_lpAdd]).add(_amount);
emit MoveStake(msg.sender, _lpAdd, _pid, _newpid, _amount);
}
function claimRewardAndAirdrop(uint256 _pid) public {
RaisePoolInfo storage pool = poolInfo[_pid];
require(block.number > pool.endBlock, "SE"); // SUM INVALID
_claimReward(_pid, _msgSender());
_claimAirdrop(_pid, _msgSender());
}
function _claimReward(uint256 _pid, address _user) internal {
if (rewardClaimed[_pid][_user]==false){
rewardClaimed[_pid][_user] = true;
for (uint256 i=0; i<stakingPools.length; i++){
for(uint256 j=0; j<listSupportedCurrencies[_pid].length; j++){
uint256 _tokenAmt = getReward(_pid, _user, stakingPools[i], listSupportedCurrencies[_pid][j]);
_creditAirdrop(_user, listSupportedCurrencies[_pid][j], _tokenAmt);
}
}
}
}
function _claimAirdrop(uint256 _pid, address _user) internal {
if (airdropClaimed[_pid][_user]==false){
airdropClaimed[_pid][_user] = true;
address _airdropToken = address(airdropInfo[_pid].airdropToken);
uint256 _tokenAmt = 0;
for (uint256 i=0; i<stakingPools.length; i++){
_tokenAmt = _tokenAmt.add(getAirdrop(_pid, _user, stakingPools[i]));
}
if(_tokenAmt !=0){
_creditAirdrop(_user, _airdropToken, _tokenAmt);
}
}
}
function _creditAirdrop(address _user, address _token, uint256 _amt) internal {
airdropBalances[_token][_user] = (airdropBalances[_token][_user]).add(_amt);
emit ClaimAirdrop(_user, _token, _amt);
}
function getReward(uint256 _pid, address _user, address _lpAdd, address _token) public view returns (uint256) {
uint256 stake = stakedLPTokensInfo[_pid][_lpAdd];
if(address(this).balance==0) return 0; //inject PRESENT ETHER
uint256 _multipliedData = (userStakeInfo[_pid][_user][_lpAdd]).mul(fundsRaisedSoFar[_pid][_token]);
_multipliedData = (_multipliedData).mul(rewardPer).mul(fee).mul(stakingWeight[_lpAdd]);
return (((_multipliedData).div(stake)).div(1e8)).div(totalStakeWeight);
}
function getAirdrop(uint256 _pid, address _user, address _lpAdd) public view returns (uint256) {
uint256 _userStaked = userStakeInfo[_pid][_user][_lpAdd];
uint256 _totalStaked = stakedLPTokensInfo[_pid][_lpAdd];
if(address(this).balance==0) return 0; //inject PRESENT ETHER
return ((((_userStaked).mul(airdropInfo[_pid].totalTokensAvailable).mul(stakingWeight[_lpAdd])).div(_totalStaked))).div(totalStakeWeight);
}
// Deposit ICO tokens for a use case as reserve.
function depositReserveICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd, address _resAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
address msgSender = _msgSender();
require(_tokenAdd == pool.raiseToken, "NOT"); // NOT AUTHORISED TOKEN
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
require(poolU.tokensDeposited == false, "DR"); // TOKENS NOT DEPOSITED
require(poolU.tokensAllocated == _amount && _amount!=0, "NA"); // NOT AVAILABLE
require(block.number < pool.endBlock, "CRN"); // CANNOT_RESERVE_NOW to avoid deadlocks
_tokenAdd.safeTransferFrom(msgSender, address(this), _amount);
totalTokenReserved[_pid] = (totalTokenReserved[_pid]).add(_amount);
poolU.tokensDeposited = true;
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw extra unsold ICO tokens or extra deposited tokens.
function withdrawExtraICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
RaisePoolInfo storage pool = poolInfo[_pid];
address msgSender = _msgSender();
require(_tokenAdd == pool.raiseToken, "NT"); // NOT AUTHORISED TOKEN
require(msgSender == pool.owner, "NAU"); // NOT AUTHORISED USER
require(block.number > pool.endBlock, "NA"); // NOT AVAILABLE TIME
uint256 _amtAvail = pool.tokensDeposited.sub(pool.totalTokensSold);
require(_amtAvail >= _amount, "NAT"); // NOT AVAILABLE TOKEN
pool.tokensDeposited = (pool.tokensDeposited).sub(_amount);
_tokenAdd.safeTransfer(msgSender, _amount);
emit Withdraw(msgSender, _pid, _amount);
}
// Fetch extra ICO tokens available.
function fetchExtraICOTokens(uint256 _pid) external view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
return pool.tokensDeposited.sub(pool.totalTokensSold);
}
// Deposit tokens to a pool for ICO.
function deposit(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
address msgSender = _msgSender();
uint256 _buyThisStep = _checkDepositAllowed(_pid, address(_tokenAdd), _amount);
// require(_buyThisStep >= _amount, "CDE");
_tokenAdd.safeTransferFrom(msgSender, address(this), _amount);
userDepositInfo[_pid][msgSender][address(_tokenAdd)] = userDepositInfo[_pid][msgSender][address(_tokenAdd)].add(_amount);
userTokenAllocation[_pid][msgSender] = userTokenAllocation[_pid][msgSender].add(_buyThisStep);
poolInfo[_pid].totalTokensSold = poolInfo[_pid].totalTokensSold.add(_buyThisStep);
fundsRaisedSoFar[_pid][address(_tokenAdd)] = fundsRaisedSoFar[_pid][address(_tokenAdd)].add(_amount);
emit Deposit(msg.sender, _pid, _amount);
}
// Vote your favourite ICO project.
function voteProject(uint256 _pid) external {
address msgSender = _msgSender();
require(userVotes[_pid][msgSender]==false,"AVO"); // ALREADY VOTED
require(poolInfo[_pid].endBlock >= block.number,"CVO"); // CANNOT VOTE NOW
userVotes[_pid][msgSender] = true;
poolInfo[_pid].votes = (poolInfo[_pid].votes).add(1);
emit Voted(msgSender, _pid);
}
function _calculatePerAvailable(uint256[] memory _daysArray, uint256[] memory _percentArray, uint256 blockEnd) internal view returns (uint256) {
uint256 _defaultPer = 10000;
uint256 _perNow;
if(address(this).balance==0){ //inject PRESENT ETHER
return _defaultPer;
}
uint256 daysDone = ((block.number).sub(blockEnd)).div(BLOCKS_PER_DAY);
for (uint256 i = 0; i < _daysArray.length; i++) {
if(_daysArray[i] <= daysDone){
_perNow = _perNow.add(_percentArray[i]);
}
else {
break;
}
}
return _perNow;
}
function _getPercentAvailable(uint256 _pid, uint256 blockEnd) internal view returns (uint256){
DistributionInfo storage distInfo = userDistInfo[_pid];
uint256[] storage _percentArray = distInfo.percentArray;
uint256[] storage _daysArray = distInfo.daysArray;
return _calculatePerAvailable(_daysArray, _percentArray, blockEnd);
}
// Check amount of ICO tokens withdrawable by user till now - public
function amountAvailToWithdrawUser(uint256 _pid, address _user) public view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
if(pool.endBlock < block.number){
uint256 percentAvail = _getPercentAvailable(_pid, pool.endBlock);
return ((percentAvail).mul(userTokenAllocation[_pid][_user]).div(10000)).sub(userTokenClaimed[_pid][_user]);
}
else {
return 0;
}
}
// Withdraw ICO tokens after sale is over based on distribution rules.
function withdrawUser(uint256 _pid, uint256 _amount) external {
RaisePoolInfo storage pool = poolInfo[_pid];
address msgSender = _msgSender();
uint256 _amtAvail = amountAvailToWithdrawUser(_pid, msgSender);
require(_amtAvail >= _amount, "NAT"); // NOT AUTHORISED TOKEN
userTokenClaimed[_pid][msgSender] = userTokenClaimed[_pid][msgSender].add(_amount);
totalTokenClaimed[_pid] = totalTokenClaimed[_pid].add(_amount);
pool.raiseToken.safeTransfer(msgSender, _amount);
emit Withdraw(msgSender, _pid, _amount);
}
function _getPercentAvailableFundRaiser(uint256 _pid, uint256 blockEnd) internal view returns (uint256){
DistributionInfo storage distInfo = ownerDistInfo[_pid];
uint256[] storage _percentArray = distInfo.percentArray;
uint256[] storage _daysArray = distInfo.daysArray;
return _calculatePerAvailable(_daysArray, _percentArray, blockEnd);
}
// Check amount of ICO tokens withdrawable by user till now
function amountAvailToWithdrawFundRaiser(uint256 _pid, IERC20 _tokenAdd) public view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
if(pool.endBlock < block.number){
uint256 percentAvail = _getPercentAvailableFundRaiser(_pid, pool.endBlock);
return (((percentAvail).mul(fundsRaisedSoFar[_pid][address(_tokenAdd)]).div(10000))).sub(fundsClaimedSoFar[_pid][address(_tokenAdd)]);
}
else {
return 0;
}
}
function _getPercentAvailableReserve(uint256 _pid, uint256 blockEnd, address _resAdd) internal view returns (uint256){
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
uint256[] storage _percentArray = poolU.unlock_perArray;
uint256[] storage _daysArray = poolU.unlock_daysArray;
return _calculatePerAvailable(_daysArray, _percentArray, blockEnd);
}
// Check amount of ICO tokens withdrawable by reserve user till now
function amountAvailToWithdrawReserve(uint256 _pid, address _resAdd) public view returns (uint256){
RaisePoolInfo storage pool = poolInfo[_pid];
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_resAdd];
if(pool.endBlock < block.number){
uint256 percentAvail = _getPercentAvailableReserve(_pid, pool.endBlock, _resAdd);
return ((percentAvail).mul(poolU.tokensAllocated).div(10000)).sub(poolU.tokensClaimed);
}
else {
return 0;
}
}
// Withdraw ICO tokens for various use cases as per the schedule promised on provided address.
function withdrawReserveICOTokens(uint256 _pid, uint256 _amount, IERC20 _tokenAdd) external {
UseCasePoolInfo storage poolU = useCaseInfo[_pid][_msgSender()];
require(poolU.reserveAdd == _msgSender(), "NAUTH"); // NOT AUTHORISED USER
require(_tokenAdd == poolInfo[_pid].raiseToken, "NT"); // NOT AUTHORISED TOKEN
uint256 _amtAvail = amountAvailToWithdrawReserve(_pid, _msgSender());
require(_amtAvail >= _amount, "NAT"); // NOT AVAILABLE USER
poolU.tokensClaimed = poolU.tokensClaimed.add(_amount);
totalTokenReserved[_pid] = totalTokenReserved[_pid].sub(_amount);
totalReservedTokenClaimed[_pid] = totalReservedTokenClaimed[_pid].add(_amount);
_tokenAdd.safeTransfer(_msgSender(), _amount);
emit Withdraw(_msgSender(), _pid, _amount);
}
// Withdraw raised funds after sale is over as per the schedule promised
function withdrawFundRaiser(uint256 _pid, uint256 _amount, IERC20 _tokenAddress) external {
RaisePoolInfo storage pool = poolInfo[_pid];
require(pool.owner == _msgSender(), "NAUTH"); // NOT AUTHORISED USER
uint256 _amtAvail = amountAvailToWithdrawFundRaiser(_pid, _tokenAddress);
require(_amtAvail >= _amount, "NAT"); // NOT AUTHORISED TOKEN
uint256 _fee = ((_amount).mul(fee)).div(1e4);
uint256 _actualTransfer = _amtAvail.sub(_fee);
uint256 _feeDev = (_fee).mul(10000 - rewardPer).div(1e4); // Remaining tokens for reward mining
fundsClaimedSoFar[_pid][address(_tokenAddress)] = fundsClaimedSoFar[_pid][address(_tokenAddress)].add(_amount);
_tokenAddress.safeTransfer(_msgSender(), _actualTransfer);
_tokenAddress.safeTransfer(devaddr, _feeDev);
emit Withdraw(_msgSender(), _pid, _actualTransfer);
emit Withdraw(devaddr, _pid, _feeDev);
}
// Update dev address by initiating with the previous dev.
function changeDev(address _newowner) external onlyAdmin {
potentialAdmin = _newowner;
}
function becomeDev() external {
require(potentialAdmin == msg.sender, "NA"); // NOT ALLOWED
devaddr = msg.sender;
}
// Update temp pool owner address by initiating with the previous pool owner.
function changePoolOwner(uint256 _pid, address _newowner) external {
require(_msgSender()==poolInfo[_pid].owner, "OA"); // NOT AUTHORISED USER
tempAdmin[_pid] = _newowner;
}
// Claim pool ownership with new address
function becomePoolOwner(uint256 _pid) external {
if (tempAdmin[_pid] == _msgSender()) poolInfo[_pid].owner = _msgSender();
}
// Update fee, can never be more than 3%.
function changeFee(uint256 _fee) external onlyAdmin{
require(_fee <= 300, "MAX3"); // MAX FEE POSSIBLE
fee = _fee;
}
// To generate a new invite code
function generateNewCode(address _token, address _poolOwner) external onlyAdminOrTimeLock returns (uint256) {
uint256 inviteCode = block.number;
inviteCodeList[inviteCode][_token][_poolOwner] = true;
return inviteCode;
}
// To invalidate an invite code
function invalidateOldCode(uint256 _inviteCode, address _token, address _poolOwner) external onlyAdmin {
inviteCodeList[_inviteCode][_token][_poolOwner] = false;
}
// To add or update a staking pool with weight
function addStakingPool(address _token, uint256 _weight) external onlyAdmin {
if(stakingEnabled[_token]==false){
stakingPools.push(_token);
stakingEnabled[_token] = true;
}
totalStakeWeight = totalStakeWeight.sub(stakingWeight[_token]).add(_weight);
stakingWeight[_token] = _weight;
}
}
|
Lock sale detail changes in future
|
function lockPool(uint256 _pid) external {
_checkUpdateAllowed(_pid);
poolInfo[_pid].updateLocked = true;
}
| 1,045,273 |
pragma solidity >=0.4.22 <0.9.0;
contract SupplyChain {
//Smart Contract owner will be the person who deploys the contract only he can authorize various roles like retailer, Manufacturer,etc
address public Owner;
//note this constructor will be called when smart contract will be deployed on blockchain
//Roles (flow of pharma supply chain)
// RawMaterialSupplier; //This is where Manufacturer will get raw materials to make medicines
// Manufacturer; //Various WHO guidelines should be followed by this person
// Distributor; //This guy distributes the medicines to retailers
// Retailer; //Normal customer buys from the retailer
//modifier to make sure only the owner is using the function
modifier onlyByOwner() {
_;
}
//stages of a medicine in pharma supply chain
enum STAGE {
Init,
Manufacture,
Distribution,
Retail,
PartiallySold,
sold
}
//using this we are going to track every single medicine the owner orders
//Medicine count
uint256 public medicineCtr = 4;
//Raw material supplier count
//uint256 public rmsCtr = 0;
//Manufacturer count
uint256 public manCtr = 0;
//distributor count
uint256 public disCtr = 0;
//retailer count
uint256 public retCtr = 0;
uint256 public docCtr = 0;
uint256 public patCtr = 0;
uint256 public solCtr = 0;
uint256 public parCtr = 0;
//To store information about the medicine
struct medicine {
uint256 id; //unique medicine id
string name; //name of the medicine
//uint256 RMSid; //id of the Raw Material supplier for this particular medicine
uint256 MANid; //id of the Manufacturer for this particular medicine
uint256 DISid; //id of the distributor for this particular medicine
uint256 RETid; //id of the retailer for this particular medicine
uint256 ManQuantity;
uint256 DisQuantity;
uint256 RetQuantity;
uint256 PatQuantity;
STAGE stage; //current medicine stage
}
//To store all the medicines on the blockchain
mapping(uint256 => medicine) public MedicineStock;
constructor() public{
MedicineStock[1] = medicine(1,"crocin",0,0,0,0,0,0,0,STAGE.Init);
MedicineStock[2] = medicine(2,"dolo",0,0,0,0,0,0,0,STAGE.Init);
MedicineStock[3] = medicine(3,"calpol",0,0,0,0,0,0,0,STAGE.Init);
MedicineStock[4] = medicine(4,"montefex",0,0,0,0,0,0,0,STAGE.Init);
}
//To show status to client applications
function showStage(uint256 _medicineID)
public
view
returns (string memory)
{
require(medicineCtr > 0);
if (MedicineStock[_medicineID].stage == STAGE.Init)
return "Medicine Ordered";
//else if (MedicineStock[_medicineID].stage == STAGE.RawMaterialSupply)
// return "Raw Material Supply Stage";
else if (MedicineStock[_medicineID].stage == STAGE.Manufacture)
return "Manufacturing Stage";
else if (MedicineStock[_medicineID].stage == STAGE.Distribution)
return "Distribution Stage";
else if (MedicineStock[_medicineID].stage == STAGE.Retail)
return "Retail Stage";
else if (MedicineStock[_medicineID].stage == STAGE.PartiallySold)
return "Partially Sold";
else if (MedicineStock[_medicineID].stage == STAGE.sold)
return "Medicine Sold";
}
//To store information about raw material supplier
//struct rawMaterialSupplier {
// address addr;
// uint256 id; //supplier id
// string name; //Name of the raw material supplier
// string place; //Place the raw material supplier is based in
// uint256 Quantity;
// }
//To store all the raw material suppliers on the blockchain
//mapping(uint256 => rawMaterialSupplier) public RMS;
//To store information about manufacturer
struct manufacturer {
address addr;
uint256 id; //manufacturer id
string name; //Name of the manufacturer
string place; //Place the manufacturer is based in
uint256 Quantity;
}
//To store all the manufacturers on the blockchain
mapping(uint256 => manufacturer) public MAN;
//To store information about distributor
struct distributor {
address addr;
uint256 id; //distributor id
string name; //Name of the distributor
string place; //Place the distributor is based in
uint256 Quantity;
}
//To store all the distributors on the blockchain
mapping(uint256 => distributor) public DIS;
//To store information about retailer
struct retailer {
address addr;
uint256 id; //retailer id
string name; //Name of the retailer
string place; //Place the retailer is based in
uint256 Quantity;
}
//To store all the retailers on the blockchain
mapping(uint256 => retailer) public RET;
//patient
struct patient {
uint256 id; //patient id
string name; //Name of the patient
string phoneNo;
string email;
uint256 docID;
string medName;
uint256 Quantity;
}
mapping(uint256 => patient) public PAT;
//Doctor
struct doctor {
address addr;
uint256 id; //doctor id
string name; //Name of the doctor
}
mapping(uint256 => doctor) public DOC;
struct soldMed {
uint256 Retid;
uint256 DocId;
uint256 PatId;
uint256 MedId;
uint256 Quantity;
}
mapping(uint256 => soldMed) public SOL;
struct parPat {
uint256 Retid;
uint256 DocId;
uint256 PatId;
uint256 MedId;
uint256 balQ;
uint256 presQ;
}
mapping(uint256 => parPat) public PAR;
function addDoctor(
address _address,
string memory _name
) public onlyByOwner() {
docCtr++;
DOC[docCtr]=doctor(_address,docCtr,_name);
}
//To add manufacturer. Only contract owner can add a new manufacturer
function addManufacturer(
address _address,
string memory _name,
string memory _place
) public onlyByOwner() {
manCtr++;
MAN[manCtr] = manufacturer(_address, manCtr, _name, _place,0);
}
//To add distributor. Only contract owner can add a new distributor
function addDistributor(
address _address,
string memory _name,
string memory _place
) public onlyByOwner() {
disCtr++;
DIS[disCtr] = distributor(_address, disCtr, _name, _place,0);
}
//To add retailer. Only contract owner can add a new retailer
function addRetailer(
address _address,
string memory _name,
string memory _place
) public onlyByOwner() {
retCtr++;
RET[retCtr] = retailer(_address, retCtr, _name, _place,0);
}
//To manufacture medicine
function Manufacturing(uint256 _medicineID,uint256 _quantity) public {
require(_medicineID > 0 && _medicineID <= medicineCtr);
uint256 _id = findMAN(msg.sender);
require(_id > 0);
require(_quantity>0);
require(MedicineStock[_medicineID].stage == STAGE.Init);
MedicineStock[_medicineID].MANid = _id;
MedicineStock[_medicineID].ManQuantity = _quantity;
MAN[_id].Quantity+=_quantity;
MedicineStock[_medicineID].stage = STAGE.Manufacture;
}
//To check if Manufacturer is available in the blockchain
function findMAN(address _address) private view returns (uint256) {
require(manCtr > 0);
for (uint256 i = 1; i <= manCtr; i++) {
if (MAN[i].addr == _address) return MAN[i].id;
}
return 0;
}
//To supply medicines from Manufacturer to distributor
function Distribute(uint256 _medicineID,uint256 _quantity) public {
require(_medicineID > 0 && _medicineID <= medicineCtr);
uint256 _id = findDIS(msg.sender);
require(_id > 0);
require(_quantity>0);
MedicineStock[_medicineID].DisQuantity = _quantity;
if( MedicineStock[_medicineID].DisQuantity< MedicineStock[_medicineID].ManQuantity){
//error
}
require(MedicineStock[_medicineID].stage == STAGE.Manufacture);
MedicineStock[_medicineID].DISid = _id;
DIS[_id].Quantity+=_quantity;
MedicineStock[_medicineID].stage = STAGE.Distribution;
}
//To check if distributor is available in the blockchain
function findDIS(address _address) private view returns (uint256) {
require(disCtr > 0);
for (uint256 i = 1; i <= disCtr; i++) {
if (DIS[i].addr == _address) return DIS[i].id;
}
return 0;
}
//To supply medicines from distributor to retailer
function Retail(uint256 _medicineID) public {
require(_medicineID > 0 && _medicineID <= medicineCtr);
uint256 _id = findRET(msg.sender);
require(_id > 0);
uint256 _quantity=MedicineStock[_id].RetQuantity;
require(_quantity>0);
MedicineStock[_medicineID].RetQuantity = _quantity;
//DIS[MED[ID].DISid].id
uint256 distId=MedicineStock[_medicineID].DISid;
//uint256 distQuant=DIS[disId].Quantity;
if(DIS[distId].Quantity- _quantity>0) {DIS[distId].Quantity=DIS[distId].Quantity- _quantity;
MedicineStock[_medicineID].DisQuantity-=_quantity;}
//else
require(MedicineStock[_medicineID].stage == STAGE.Distribution);
MedicineStock[_medicineID].RETid = _id;
RET[_id].Quantity+=_quantity;
MedicineStock[_medicineID].stage = STAGE.Retail;
}
//To check if retailer is available in the blockchain
function findRET(address _address) private view returns (uint256) {
require(retCtr > 0);
for (uint256 i = 1; i <= retCtr; i++) {
if (RET[i].addr == _address) return RET[i].id;
}
return 0;
}
//To sell medicines from retailer to consumer
function sold(string memory _patName,string memory _patEmail) public {
uint256 _RetId = findRET(msg.sender);
require(_RetId > 0);
uint256 _patId=findPat(_patName,_patEmail);
require(_patId > 0);
uint256 _docID=PAT[_patId].docID;
string memory _medName=PAT[_patId].medName;
uint256 _medId = findMed(_medName);
require(MedicineStock[_medId].stage==STAGE.Retail||MedicineStock[_medId].stage==STAGE.PartiallySold);
uint256 _patQuan = PAT[_patId].Quantity;
uint256 _retQuan = RET[_RetId].Quantity;
MedicineStock[_medId].PatQuantity = _patQuan;
//require(_id == MedicineStock[_medId].RETid); //Only correct retailer can mark medicine as sold
if(MedicineStock[_medId].stage == STAGE.Retail)
{
if(_patQuan <= _retQuan){
MedicineStock[_medId].RetQuantity-=_patQuan;
MedicineStock[_medId].stage = STAGE.sold;
MedicineStock[_medId].PatQuantity = 0;
solCtr++;
SOL[solCtr]=soldMed(_RetId,_docID,_patId,_medId,_patQuan);
}
else{
uint256 bal=_patQuan-_retQuan;
MedicineStock[_medId].stage = STAGE.PartiallySold;
parCtr++;
PAR[parCtr]=parPat(_RetId,_docID,_patId,_medId,bal,_patQuan);
}
}
else if(MedicineStock[_medId].stage == STAGE.PartiallySold)
{
if(_patQuan <= _retQuan){
MedicineStock[_medId].RetQuantity-=_patQuan;
MedicineStock[_medId].stage = STAGE.sold;
MedicineStock[_medId].PatQuantity = 0;
solCtr++;
SOL[solCtr]=soldMed(_RetId,_docID,_patId,_medId,_patQuan);
}
else{
uint256 bal=_patQuan-_retQuan;
MedicineStock[_medId].stage = STAGE.PartiallySold;
parCtr++;
PAR[parCtr]=parPat(_RetId,_docID,_patId,_medId,bal,_patQuan);
}
}
}
function findPat(string memory _name,string memory _email) private view returns (uint256) {
require(patCtr > 0);
for (uint256 i = 1; i <= patCtr; i++) {
string memory _patName=PAT[i].name;
string memory _patEmail=PAT[i].email;
if (keccak256(abi.encode(_patName)) == keccak256(abi.encode(_name))&&keccak256(abi.encode(_patEmail)) == keccak256(abi.encode(_email)))
return PAT[i].id;
}
return 0;
}
function prescribe(string memory _patName,string memory _patPhNo,string memory _email,string memory _medName,uint256 _quantity) public{
uint256 _docId = findDoc(msg.sender);
require(_docId>0);
require(_quantity>0);
uint256 _medId=findMed(_medName);
require(_medId>0);
patCtr++;
PAT[patCtr] = patient(patCtr, _patName, _patPhNo,_email,_docId,_medName,_quantity);
MedicineStock[_medId].PatQuantity=_quantity;
}
function findDoc(address _address) private view returns (uint256) {
require(docCtr > 0);
for (uint256 i = 1; i <= docCtr; i++) {
if (DOC[i].addr == _address) return DOC[i].id;
}
return 0;
}
function findMed(string memory _name) private view returns (uint256) {
require(medicineCtr > 0);
string memory _medName;
for (uint256 i = 1; i <= medicineCtr; i++) {
_medName=MedicineStock[i].name;
if (keccak256(abi.encode(_medName)) == keccak256(abi.encode(_name))) return MedicineStock[i].id;
}
return 0;
}
// To add new medicines to the stock
function addMedicine(uint256 _medId,uint256 _quantity)
public
onlyByOwner()
{
//js changes
require((manCtr > 0) && (disCtr > 0) && (retCtr > 0));
MedicineStock[_medId].RetQuantity=_quantity;
}
}
|
To show status to client applicationselse if (MedicineStock[_medicineID].stage == STAGE.RawMaterialSupply) return "Raw Material Supply Stage";
|
function showStage(uint256 _medicineID)
public
view
returns (string memory)
{
require(medicineCtr > 0);
if (MedicineStock[_medicineID].stage == STAGE.Init)
return "Medicine Ordered";
else if (MedicineStock[_medicineID].stage == STAGE.Manufacture)
return "Manufacturing Stage";
else if (MedicineStock[_medicineID].stage == STAGE.Distribution)
return "Distribution Stage";
else if (MedicineStock[_medicineID].stage == STAGE.Retail)
return "Retail Stage";
else if (MedicineStock[_medicineID].stage == STAGE.PartiallySold)
return "Partially Sold";
else if (MedicineStock[_medicineID].stage == STAGE.sold)
return "Medicine Sold";
}
| 930,258 |
./partial_match/1/0xe35aC90D3BD1009977c989F3eb0c0d3E9F171817/sources/contracts/extensions/token/erc20/ERC20TokenExtension.sol
|
Returns the symbol of the token, usually a shorter version of the name./
|
function symbol() external view virtual returns (string memory) {
return bytes32ToString(bytes32(dao.getConfiguration(TokenSymbol)));
}
| 15,956,370 |
//Address: 0xb56c725467c7eec851b1a4a4222d930932b04e89
//Contract name: E4RowEscrow
//Balance: 0.1862646004623971 Ether
//Verification Date: 6/15/2017
//Transacion Count: 3958
// CODE STARTS HERE
pragma solidity ^0.4.11;
// version (LAVA-Q)
contract E4RowEscrow {
event StatEvent(string msg);
event StatEventI(string msg, uint val);
event StatEventA(string msg, address addr);
uint constant MAX_PLAYERS = 5;
enum EndReason {erWinner, erTimeOut, erCancel}
enum SettingStateValue {debug, release, lockedRelease}
struct gameInstance {
bool active; // active
bool allocd; // allocated already.
EndReason reasonEnded; // enum reason of ended
uint8 numPlayers;
uint128 totalPot; // total of all bets
uint128[5] playerPots; // individual deposits
address[5] players; // player addrs
uint lastMoved; // time game last moved
}
struct arbiter {
mapping (uint => uint) gameIndexes; // game handles
bool registered;
bool locked;
uint8 numPlayers;
uint16 arbToken; // 2 bytes
uint16 escFeePctX10; // escrow fee -- frac of 1000
uint16 arbFeePctX10; // arbiter fee -- frac of 1000
uint32 gameSlots; // a counter of alloc'd game structs (they can be reused)
uint128 feeCap; // max fee (escrow + arb) in wei
uint128 arbHoldover; // hold accumulated gas credits and arbiter fees
}
address public owner; // owner is address that deployed contract
address public tokenPartner; // the address of partner that receives rake fees
uint public numArbiters; // number of arbiters
int numGamesStarted; // total stats from all arbiters
uint public numGamesCompleted; // ...
uint public numGamesCanceled; // tied and canceled
uint public numGamesTimedOut; // ...
uint public houseFeeHoldover; // hold fee till threshold
uint public lastPayoutTime; // timestamp of last payout time
// configurables
uint public gameTimeOut;
uint public registrationFee;
uint public houseFeeThreshold;
uint public payoutInterval;
uint acctCallGas; // for payments to simple accts
uint tokCallGas; // for calling token contract. eg fee payout
uint public startGameGas; // gas consumed by startGame
uint public winnerDecidedGas; // gas consumed by winnerDecided
SettingStateValue public settingsState = SettingStateValue.debug;
mapping (address => arbiter) arbiters;
mapping (uint => address) arbiterTokens;
mapping (uint => address) arbiterIndexes;
mapping (uint => gameInstance) games;
function E4RowEscrow() public
{
owner = msg.sender;
}
function applySettings(SettingStateValue _state, uint _fee, uint _threshold, uint _timeout, uint _interval, uint _startGameGas, uint _winnerDecidedGas)
{
if (msg.sender != owner)
throw;
// ----------------------------------------------
// these items are tweakable for game optimization
// ----------------------------------------------
houseFeeThreshold = _threshold;
gameTimeOut = _timeout;
payoutInterval = _interval;
if (settingsState == SettingStateValue.lockedRelease) {
StatEvent("Settings Tweaked");
return;
}
settingsState = _state;
registrationFee = _fee;
// set default op gas - any futher settings done in set up gas
acctCallGas = 21000;
tokCallGas = 360000;
// set gas consumption - these should never change (except gas price)
startGameGas = _startGameGas;
winnerDecidedGas = _winnerDecidedGas;
StatEvent("Settings Changed");
}
//-----------------------------
// return an arbiter token from an hGame
//-----------------------------
function ArbTokFromHGame(uint _hGame) returns (uint _tok)
{
_tok = (_hGame / (2 ** 48)) & 0xffff;
}
//-----------------------------
// suicide the contract, not called for release
//-----------------------------
function HaraKiri()
{
if ((msg.sender == owner) && (settingsState != SettingStateValue.lockedRelease))
suicide(tokenPartner);
else
StatEvent("Kill attempt failed");
}
//-----------------------------
// default function
// who are we to look a gift-horse in the mouth?
//-----------------------------
function() payable {
StatEvent("thanks!");
houseFeeHoldover += msg.value;
}
function blackHole() payable {
StatEvent("thanks!#2");
}
//------------------------------------------------------
// check active game and valid player, return player index
//-------------------------------------------------------
function validPlayer(uint _hGame, address _addr) internal returns( bool _valid, uint _pidx)
{
_valid = false;
if (activeGame(_hGame)) {
for (uint i = 0; i < games[_hGame].numPlayers; i++) {
if (games[_hGame].players[i] == _addr) {
_valid=true;
_pidx = i;
break;
}
}
}
}
//------------------------------------------------------
// check the arbiter is valid by comparing token
//------------------------------------------------------
function validArb(address _addr, uint _tok) internal returns( bool _valid)
{
_valid = false;
if ((arbiters[_addr].registered)
&& (arbiters[_addr].arbToken == _tok))
_valid = true;
}
//------------------------------------------------------
// check the arbiter is valid without comparing token
//------------------------------------------------------
function validArb2(address _addr) internal returns( bool _valid)
{
_valid = false;
if (arbiters[_addr].registered)
_valid = true;
}
//------------------------------------------------------
// check if arbiter is locked out
//------------------------------------------------------
function arbLocked(address _addr) internal returns( bool _locked)
{
_locked = false;
if (validArb2(_addr))
_locked = arbiters[_addr].locked;
}
//------------------------------------------------------
// return if game is active
//------------------------------------------------------
function activeGame(uint _hGame) internal returns( bool _valid)
{
_valid = false;
if ((_hGame > 0)
&& (games[_hGame].active))
_valid = true;
}
//------------------------------------------------------
// register game arbiter, max players of 5, pass in exact registration fee
//------------------------------------------------------
function registerArbiter(uint _numPlayers, uint _arbToken, uint _escFeePctX10, uint _arbFeePctX10, uint _feeCap) public payable
{
if (msg.value != registrationFee) {
throw; //Insufficient Fee
}
if (_arbToken == 0) {
throw; // invalid token
}
if (arbTokenExists(_arbToken & 0xffff)) {
throw; // Token Already Exists
}
if (arbiters[msg.sender].registered) {
throw; // Arb Already Registered
}
if (_numPlayers > MAX_PLAYERS) {
throw; // Exceeds Max Players
}
if (_escFeePctX10 < 20) {
throw; // less than 2% min escrow fee
}
if (_arbFeePctX10 > 10) {
throw; // more than than 1% max arbiter fee
}
arbiters[msg.sender].locked = false;
arbiters[msg.sender].numPlayers = uint8(_numPlayers);
arbiters[msg.sender].escFeePctX10 = uint8(_escFeePctX10);
arbiters[msg.sender].arbFeePctX10 = uint8(_arbFeePctX10);
arbiters[msg.sender].arbToken = uint16(_arbToken & 0xffff);
arbiters[msg.sender].feeCap = uint128(_feeCap);
arbiters[msg.sender].registered = true;
arbiterTokens[(_arbToken & 0xffff)] = msg.sender;
arbiterIndexes[numArbiters++] = msg.sender;
if (tokenPartner != address(0)) {
if (!tokenPartner.call.gas(tokCallGas).value(msg.value)()) {
//Statvent("Send Error"); // event never registers
throw;
}
} else {
houseFeeHoldover += msg.value;
}
StatEventI("Arb Added", _arbToken);
}
//------------------------------------------------------
// start game. pass in valid hGame containing token in top two bytes
//------------------------------------------------------
function startGame(uint _hGame, int _hkMax, address[] _players) public
{
uint ntok = ArbTokFromHGame(_hGame);
if (!validArb(msg.sender, ntok )) {
StatEvent("Invalid Arb");
return;
}
if (arbLocked(msg.sender)) {
StatEvent("Arb Locked");
return;
}
arbiter xarb = arbiters[msg.sender];
if (_players.length != xarb.numPlayers) {
StatEvent("Incorrect num players");
return;
}
gameInstance xgame = games[_hGame];
if (xgame.active) {
// guard-rail. just in case to return funds
abortGame(_hGame, EndReason.erCancel);
} else if (_hkMax > 0) {
houseKeep(_hkMax, ntok);
}
if (!xgame.allocd) {
xgame.allocd = true;
xarb.gameIndexes[xarb.gameSlots++] = _hGame;
}
numGamesStarted++; // always inc this one
xgame.active = true;
xgame.lastMoved = now;
xgame.totalPot = 0;
xgame.numPlayers = xarb.numPlayers;
for (uint i = 0; i < _players.length; i++) {
xgame.players[i] = _players[i];
xgame.playerPots[i] = 0;
}
//StatEventI("Game Added", _hGame);
}
//------------------------------------------------------
// clean up game, set to inactive, refund any balances
// called by housekeep ONLY
//------------------------------------------------------
function abortGame(uint _hGame, EndReason _reason) private returns(bool _success)
{
gameInstance xgame = games[_hGame];
// find game in game id,
if (xgame.active) {
_success = true;
for (uint i = 0; i < xgame.numPlayers; i++) {
if (xgame.playerPots[i] > 0) {
address a = xgame.players[i];
uint nsend = xgame.playerPots[i];
xgame.playerPots[i] = 0;
if (!a.call.gas(acctCallGas).value(nsend)()) {
houseFeeHoldover += nsend; // cannot refund due to error, give to the house
StatEventA("Cannot Refund Address", a);
}
}
}
xgame.active = false;
xgame.reasonEnded = _reason;
if (_reason == EndReason.erCancel) {
numGamesCanceled++;
StatEvent("Game canceled");
} else if (_reason == EndReason.erTimeOut) {
numGamesTimedOut++;
StatEvent("Game timed out");
} else
StatEvent("Game aborted");
}
}
//------------------------------------------------------
// called by arbiter when winner is decided
// *pass in high num for winnerbal for tie games
//------------------------------------------------------
function winnerDecided(uint _hGame, address _winner, uint _winnerBal) public
{
if (!validArb(msg.sender, ArbTokFromHGame(_hGame))) {
StatEvent("Invalid Arb");
return; // no throw no change made
}
var (valid, pidx) = validPlayer(_hGame, _winner);
if (!valid) {
StatEvent("Invalid Player");
return;
}
arbiter xarb = arbiters[msg.sender];
gameInstance xgame = games[_hGame];
if (xgame.playerPots[pidx] < _winnerBal) {
abortGame(_hGame, EndReason.erCancel);
return;
}
xgame.active = false;
xgame.reasonEnded = EndReason.erWinner;
numGamesCompleted++;
if (xgame.totalPot > 0) {
// calc payouts: escrowFee, arbiterFee, gasCost, winner payout
uint _escrowFee = (xgame.totalPot * xarb.escFeePctX10) / 1000;
uint _arbiterFee = (xgame.totalPot * xarb.arbFeePctX10) / 1000;
if ((_escrowFee + _arbiterFee) > xarb.feeCap) {
_escrowFee = xarb.feeCap * xarb.escFeePctX10 / (xarb.escFeePctX10 + xarb.arbFeePctX10);
_arbiterFee = xarb.feeCap * xarb.arbFeePctX10 / (xarb.escFeePctX10 + xarb.arbFeePctX10);
}
uint _payout = xgame.totalPot - (_escrowFee + _arbiterFee);
uint _gasCost = tx.gasprice * (startGameGas + winnerDecidedGas);
if (_gasCost > _payout)
_gasCost = _payout;
_payout -= _gasCost;
// do payouts
xarb.arbHoldover += uint128(_arbiterFee + _gasCost);
houseFeeHoldover += _escrowFee;
if ((houseFeeHoldover > houseFeeThreshold)
&& (now > (lastPayoutTime + payoutInterval))) {
uint ntmpho = houseFeeHoldover;
houseFeeHoldover = 0;
lastPayoutTime = now; // reset regardless of succeed/fail
if (!tokenPartner.call.gas(tokCallGas).value(ntmpho)()) {
houseFeeHoldover = ntmpho; // put it back
StatEvent("House-Fee Error1");
}
}
if (_payout > 0) {
if (!_winner.call.gas(acctCallGas).value(uint(_payout))()) {
// if you cant pay the winner - very bad
// StatEvent("Send Error");
// add funds to houseFeeHoldover to avoid acounting errs
//throw;
houseFeeHoldover += _payout;
StatEventI("Payout Error!", _hGame);
} else {
//StatEventI("Winner Paid", _hGame);
}
}
}
}
//------------------------------------------------------
// handle a bet made by a player, validate the player and game
// add to players balance
//------------------------------------------------------
function handleBet(uint _hGame) public payable
{
address _arbAddr = arbiterTokens[ArbTokFromHGame(_hGame)];
if (_arbAddr == address(0)) {
throw; // "Invalid hGame"
}
var (valid, pidx) = validPlayer(_hGame, msg.sender);
if (!valid) {
throw; // "Invalid Player"
}
gameInstance xgame = games[_hGame];
xgame.playerPots[pidx] += uint128(msg.value);
xgame.totalPot += uint128(msg.value);
//StatEventI("Bet Added", _hGame);
}
//------------------------------------------------------
// return if arb token exists
//------------------------------------------------------
function arbTokenExists(uint _tok) constant returns (bool _exists)
{
_exists = false;
if ((_tok > 0)
&& (arbiterTokens[_tok] != address(0))
&& arbiters[arbiterTokens[_tok]].registered)
_exists = true;
}
//------------------------------------------------------
// return arbiter game stats
//------------------------------------------------------
function getArbInfo(uint _tok) constant returns (address _addr, uint _escFeePctX10, uint _arbFeePctX10, uint _feeCap, uint _holdOver)
{
// if (arbiterTokens[_tok] != address(0)) {
_addr = arbiterTokens[_tok];
arbiter xarb = arbiters[arbiterTokens[_tok]];
_escFeePctX10 = xarb.escFeePctX10;
_arbFeePctX10 = xarb.arbFeePctX10;
_feeCap = xarb.feeCap;
_holdOver = xarb.arbHoldover;
// }
}
//------------------------------------------------------
// scan for a game 10 minutes old
// if found abort the game, causing funds to be returned
//------------------------------------------------------
function houseKeep(int _max, uint _arbToken) public
{
uint gi;
address a;
int aborted = 0;
arbiter xarb = arbiters[msg.sender];// have to set it to something
if (msg.sender == owner) {
for (uint ar = 0; (ar < numArbiters) && (aborted < _max) ; ar++) {
a = arbiterIndexes[ar];
xarb = arbiters[a];
for ( gi = 0; (gi < xarb.gameSlots) && (aborted < _max); gi++) {
gameInstance ngame0 = games[xarb.gameIndexes[gi]];
if ((ngame0.active)
&& ((now - ngame0.lastMoved) > gameTimeOut)) {
abortGame(xarb.gameIndexes[gi], EndReason.erTimeOut);
++aborted;
}
}
}
} else {
if (!validArb(msg.sender, _arbToken))
StatEvent("Housekeep invalid arbiter");
else {
a = msg.sender;
xarb = arbiters[a];
for (gi = 0; (gi < xarb.gameSlots) && (aborted < _max); gi++) {
gameInstance ngame1 = games[xarb.gameIndexes[gi]];
if ((ngame1.active)
&& ((now - ngame1.lastMoved) > gameTimeOut)) {
abortGame(xarb.gameIndexes[gi], EndReason.erTimeOut);
++aborted;
}
}
}
}
}
//------------------------------------------------------
// return game info
//------------------------------------------------------
function getGameInfo(uint _hGame) constant returns (EndReason _reason, uint _players, uint _totalPot, bool _active)
{
gameInstance xgame = games[_hGame];
_active = xgame.active;
_players = xgame.numPlayers;
_totalPot = xgame.totalPot;
_reason = xgame.reasonEnded;
}
//------------------------------------------------------
// return arbToken and low bytes from an HGame
//------------------------------------------------------
function checkHGame(uint _hGame) constant returns(uint _arbTok, uint _lowWords)
{
_arbTok = ArbTokFromHGame(_hGame);
_lowWords = _hGame & 0xffffffffffff;
}
//------------------------------------------------------
// get operation gas amounts
//------------------------------------------------------
function getOpGas() constant returns (uint _ag, uint _tg)
{
_ag = acctCallGas; // winner paid
_tg = tokCallGas; // token contract call gas
}
//------------------------------------------------------
// set operation gas amounts for forwading operations
//------------------------------------------------------
function setOpGas(uint _ag, uint _tg)
{
if (msg.sender != owner)
throw;
acctCallGas = _ag;
tokCallGas = _tg;
}
//------------------------------------------------------
// set a micheivous arbiter to locked
//------------------------------------------------------
function setArbiterLocked(address _addr, bool _lock) public
{
if (owner != msg.sender) {
throw;
} else if (!validArb2(_addr)) {
StatEvent("invalid arb");
} else {
arbiters[_addr].locked = _lock;
}
}
//------------------------------------------------------
// flush the house fees whenever commanded to.
// ignore the threshold and the last payout time
// but this time only reset lastpayouttime upon success
//------------------------------------------------------
function flushHouseFees()
{
if (msg.sender != owner) {
StatEvent("only owner calls this function");
} else if (houseFeeHoldover > 0) {
uint ntmpho = houseFeeHoldover;
houseFeeHoldover = 0;
if (!tokenPartner.call.gas(tokCallGas).value(ntmpho)()) {
houseFeeHoldover = ntmpho; // put it back
StatEvent("House-Fee Error2");
} else {
lastPayoutTime = now;
StatEvent("House-Fee Paid");
}
}
}
// ----------------------------
// withdraw expense funds to arbiter
// ----------------------------
function withdrawArbFunds() public
{
if (!validArb2(msg.sender)) {
StatEvent("invalid arbiter");
} else {
arbiter xarb = arbiters[msg.sender];
if (xarb.arbHoldover == 0) {
StatEvent("0 Balance");
return;
} else {
uint _amount = xarb.arbHoldover;
xarb.arbHoldover = 0;
if (!msg.sender.call.gas(acctCallGas).value(_amount)())
throw;
}
}
}
//------------------------------------------------------
// set the token partner
//------------------------------------------------------
function setTokenPartner(address _addr) public
{
if (msg.sender != owner) {
throw;
}
if ((settingsState == SettingStateValue.lockedRelease)
&& (tokenPartner == address(0))) {
tokenPartner = _addr;
StatEvent("Token Partner Final!");
} else if (settingsState != SettingStateValue.lockedRelease) {
tokenPartner = _addr;
StatEvent("Token Partner Assigned!");
}
}
// ----------------------------
// swap executor
// ----------------------------
function changeOwner(address _addr)
{
if (msg.sender != owner
|| settingsState == SettingStateValue.lockedRelease)
throw;
owner = _addr;
}
}
|
------------------------------------------------------ flush the house fees whenever commanded to. ignore the threshold and the last payout time but this time only reset lastpayouttime upon success------------------------------------------------------
|
function flushHouseFees()
{
if (msg.sender != owner) {
StatEvent("only owner calls this function");
uint ntmpho = houseFeeHoldover;
houseFeeHoldover = 0;
if (!tokenPartner.call.gas(tokCallGas).value(ntmpho)()) {
StatEvent("House-Fee Error2");
lastPayoutTime = now;
StatEvent("House-Fee Paid");
}
}
}
| 12,615,567 |
./full_match/1/0x911a768fF40e6477736AA009EF0055563982bE3a/sources/src/ExternalRefinancing.sol
|
Reads the int192 at `cdPtr` in calldata.
|
function readInt192(
CalldataPointer cdPtr
) internal pure returns (int192 value) {
assembly {
value := calldataload(cdPtr)
}
}
| 3,218,364 |
// SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity 0.8.7;
import "@rari-capital/solmate/src/tokens/ERC20.sol";
import "@rari-capital/solmate/src/utils/SafeTransferLib.sol";
import "@openzeppelin/contracts/access/Ownable.sol";
import "../../libraries/Babylonian.sol";
import "../../interfaces/IStrategy.sol";
import "../../interfaces/ISushiSwap.sol";
import "../../interfaces/IMasterChef.sol";
import "../../interfaces/IDynamicSubLPStrategy.sol";
import "../../interfaces/IBentoBoxMinimal.sol";
/// @notice Dynamic strategy that can have different farming strategy
/// For example, farming on Trader Joe then unwrap the jLP to
/// mint pLP and farm on Pengolin.
contract DynamicLPStrategy is IStrategy, Ownable {
using SafeTransferLib for ERC20;
address public immutable strategyToken;
address public immutable token0;
address public immutable token1;
address public immutable bentoBox;
address public feeCollector;
uint8 public feePercent;
uint256 public maxBentoBoxBalance; /// @dev Slippage protection when calling harvest
mapping(address => bool) public strategyExecutors; /// @dev EOAs that can execute safeHarvest
IDynamicSubLPStrategy[] public subStrategies;
IDynamicSubLPStrategy public currentSubStrategy;
bool public exited; /// @dev After bentobox 'exits' the strategy harvest, skim and withdraw functions can no loner be called
event LogSubStrategyAdded(address indexed subStrategy);
event LogSubStrategyChanged(
address indexed fromStrategy,
address indexed toStrategy,
uint256 amountOut,
uint256 amountOutPrice,
uint256 amountIn,
uint256 amountInPrice
);
event LogSetStrategyExecutor(address indexed executor, bool allowed);
/** @param _strategyToken Address of the underlying LP token the strategy invests.
@param _bentoBox BentoBox address.
@param _strategyExecutor an EOA that will execute the safeHarvest function.
*/
constructor(
address _strategyToken,
address _bentoBox,
address _strategyExecutor
) {
strategyToken = _strategyToken;
token0 = ISushiSwap(_strategyToken).token0();
token1 = ISushiSwap(_strategyToken).token1();
bentoBox = _bentoBox;
if (_strategyExecutor != address(0)) {
strategyExecutors[_strategyExecutor] = true;
emit LogSetStrategyExecutor(_strategyExecutor, true);
}
}
modifier isActive() {
require(!exited, "BentoBox Strategy: exited");
_;
}
modifier onlyBentoBox() {
require(msg.sender == bentoBox, "BentoBox Strategy: only BentoBox");
_;
}
/// @notice Ensure the current strategy is handling _strategyToken token so that skim,
/// withdraw and exit can report correctly back to bentobox.
modifier onlyValidStrategy() {
require(address(currentSubStrategy) != address(0), "zero address");
require(currentSubStrategy.strategyTokenIn() == strategyToken, "not handling strategyToken");
_;
}
modifier onlyExecutor() {
require(strategyExecutors[msg.sender], "BentoBox Strategy: only Executors");
_;
}
function addSubStrategy(IDynamicSubLPStrategy subStrategy) public onlyOwner {
require(address(subStrategy) != address(0), "zero address");
require(subStrategy.dynamicStrategy() == address(this), "dynamicStrategy mismatch");
/// @dev make sure the strategy pair token is using the same token0 and token1
ISushiSwap sushiPair = ISushiSwap(subStrategy.strategyTokenIn());
require(sushiPair.token0() == token0 && sushiPair.token1() == token1, "incompatible tokens");
subStrategies.push(subStrategy);
emit LogSubStrategyAdded(address(subStrategy));
if (address(currentSubStrategy) == address(0)) {
require(subStrategy.strategyTokenIn() == strategyToken, "not strategyTokenIn");
currentSubStrategy = subStrategy;
emit LogSubStrategyChanged(address(0), address(currentSubStrategy), 0, 0, 0, 0);
}
}
/// @param index the index of the next strategy to use
/// @param maxSlippageBps maximum tolerated amount of basis points of the total migrated
/// 5 = 0.05%
/// 10_000 = 100%
/// @param minDustAmount0 when the new strategy needs to wrap the token0 and token1 from previousSubStrategy
/// unwrapped token0 and token1, after initial addLiquidity, what minimum remaining
/// amount left in the contract (from new pair imbalance),
/// should be considered to swap again for more liquidity. Set to 0 to ignore.
/// @param minDustAmount1 same as minDustAmount0 but for token1
function changeStrategy(
uint256 index,
uint256 maxSlippageBps,
uint256 minDustAmount0,
uint256 minDustAmount1
) public onlyExecutor {
require(index < subStrategies.length, "invalid index");
IDynamicSubLPStrategy previousSubStrategy = currentSubStrategy;
currentSubStrategy = subStrategies[index];
require(previousSubStrategy != currentSubStrategy, "already current");
/// @dev the next sub strategy is not using the same strategy token
/// and requires a convertion
if (previousSubStrategy.strategyTokenIn() != currentSubStrategy.strategyTokenIn()) {
/// @dev unwrap needs send the token0 and token1 to the next strategy directly
(uint256 amountFrom, uint256 priceAmountFrom) = previousSubStrategy.withdrawAndUnwrapTo(currentSubStrategy);
/// @dev wrap from the tokens sent from the previous strategy
(uint256 amountTo, uint256 priceAmountTo) = currentSubStrategy.wrapAndDeposit(minDustAmount0, minDustAmount1);
uint256 minToteraledPrice = priceAmountFrom - ((priceAmountFrom * maxSlippageBps) / 10_000);
require(priceAmountTo >= minToteraledPrice, "maximumBps exceeded");
emit LogSubStrategyChanged(
address(previousSubStrategy),
address(currentSubStrategy),
amountFrom,
priceAmountFrom,
amountTo,
priceAmountTo
);
}
}
/// @inheritdoc IStrategy
function skim(uint256 amount) external override onlyValidStrategy {
/// @dev bentobox transfers the token in this strategy so we need to
/// forward them to the sub strategy so that the specific skim can work.
ERC20(strategyToken).transfer(address(currentSubStrategy), amount);
currentSubStrategy.skim(amount);
}
/// @inheritdoc IStrategy
function withdraw(uint256 amount) external override isActive onlyBentoBox onlyValidStrategy returns (uint256 actualAmount) {
return currentSubStrategy.withdraw(amount);
}
/// @notice Harvest profits while preventing a sandwich attack exploit.
/// @param maxBalance The maximum balance of the underlying token that is allowed to be in BentoBox.
/// @param rebalance Whether BentoBox should rebalance the strategy assets to acheive it's target allocation.
/// @param maxChangeAmount When rebalancing - the maximum amount that will be deposited to or withdrawn from a strategy to BentoBox.
/// @dev maxBalance can be set to 0 to keep the previous value.
/// @dev maxChangeAmount can be set to 0 to allow for full rebalancing.
function safeHarvest(
uint256 maxBalance,
bool rebalance,
uint256 maxChangeAmount
) external onlyExecutor {
if (maxBalance > 0) {
maxBentoBoxBalance = maxBalance;
}
IBentoBoxMinimal(bentoBox).harvest(strategyToken, rebalance, maxChangeAmount);
}
/// @inheritdoc IStrategy
/// @dev Only BentoBox can call harvest on this strategy.
/// @dev Ensures that (1) the caller was this contract (called through the safeHarvest function)
/// and (2) that we are not being frontrun by a large BentoBox deposit when harvesting profits.
/// @dev Beware that calling harvest can result in a subsequent skim or withdraw call if it's rebalancing.
function harvest(uint256 balance, address sender) external override isActive onlyBentoBox returns (int256) {
require(address(currentSubStrategy) != address(0), "zero address");
/// @dev Don't revert if conditions aren't met in order to allow
/// BentoBox to continue execution as it might need to do a rebalance.
if (sender == address(this) && IBentoBoxMinimal(bentoBox).totals(strategyToken).elastic <= maxBentoBoxBalance && balance > 0) {
return int256(currentSubStrategy.harvest());
}
return int256(0);
}
/// @inheritdoc IStrategy
/// @dev do not use isActive modifier here; allow bentobox to call strategy.exit() multiple times
function exit(uint256 balance) external override onlyBentoBox onlyValidStrategy returns (int256 amountAdded) {
uint256 actualBalance = currentSubStrategy.exit();
/// @dev Calculate tokens added (or lost).
amountAdded = int256(actualBalance) - int256(balance);
exited = true;
}
function swapToLP(uint256 amountOutMin) external onlyExecutor returns (uint256) {
return currentSubStrategy.swapToLP(amountOutMin, feePercent, feeCollector);
}
function setStrategyExecutor(address executor, bool value) external onlyOwner {
strategyExecutors[executor] = value;
emit LogSetStrategyExecutor(executor, value);
}
function setFeeParameters(address _feeCollector, uint8 _feePercent) external onlyOwner {
require(feePercent <= 100, "invalid feePercent");
feeCollector = _feeCollector;
feePercent = _feePercent;
}
}
|
@inheritdoc IStrategy do not use isActive modifier here; allow bentobox to call strategy.exit() multiple times
|
function exit(uint256 balance) external override onlyBentoBox onlyValidStrategy returns (int256 amountAdded) {
uint256 actualBalance = currentSubStrategy.exit();
amountAdded = int256(actualBalance) - int256(balance);
exited = true;
| 5,432,266 |
./full_match/4/0xa3cA8e18ACF68955B93eCB5e416bC5728a15657B/sources/contracts/KingOfTheHill.sol
|
This private function is called to update variables. The following variables are updated: - gameBlock is set to zero to report that the game is over and waiting another return. - balance of the last _jackpotOwner and the _owner are updated. - _jackpot is updated with a new seed Seed calculation: the two rewards (owner and jackpotOwner) and the seed are splitted differently depends on who call the function. There are three case: (Seed / Owner gain / JackpotOwner gain -- in %) - the owner call this function: 10 / 10 / 80 - the jackpotOwner call this function: 5 / 5 / 90 - the next player call this function: 8 / 8 / 86 /
|
function _gameOver(address caller) private {
uint256 amount;
if (caller == _owner) {
amount = 10;
amount = 5;
amount = 8;
}
uint256 seed = (_jackpot*amount)/100;
_gamersRewards[_jackpotOwner] += _jackpot-(seed*2);
_gamersRewards[_owner] += seed;
_jackpot = seed;
_gameBlock = 0;
}
| 12,463,515 |
./full_match/1/0x82a7b5842085f434c6584A8c44b6A1C15c25a512/sources/contracts/test/integrations/DelegateCash/TestDelegationRegistry.sol
|
The global mapping and single source of truth for delegations vault -> vaultVersion -> delegationHash A mapping of wallets to versions (for cheap revocation) A mapping of wallets to delegates to versions (for cheap revocation) A secondary mapping to return onchain enumerability of delegations that a given address can perform delegate -> delegationHashes A secondary mapping used to return delegation information about a delegation delegationHash -> DelegateInfo @inheritdoc ERC165/
|
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) {
return interfaceId == type(IDelegationRegistry).interfaceId || super.supportsInterface(interfaceId);
}
| 9,659,503 |
pragma solidity ^0.5.0;
import "./ReentrancyGuard.sol";
import "./SafeMath.sol";
import "./SafeMathUInt128.sol";
import "./SafeCast.sol";
import "./Utils.sol";
import "./Storage.sol";
import "./Config.sol";
import "./Events.sol";
import "./Bytes.sol";
import "./Operations.sol";
import "./UpgradeableMaster.sol";
import "./uniswap/UniswapV2Factory.sol";
import "./PairTokenManager.sol";
/// @title zkSync main contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract ZkSync is PairTokenManager, UpgradeableMaster, Storage, Config, Events, ReentrancyGuard {
using SafeMath for uint256;
using SafeMathUInt128 for uint128;
bytes32 public constant EMPTY_STRING_KECCAK = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
//create pair
function createPair(address _tokenA, address _tokenB) external {
requireActive();
governance.requireTokenLister(msg.sender);
//check _tokenA is registered or not
uint16 tokenAID = governance.validateTokenAddress(_tokenA);
//check _tokenB is registered or not
uint16 tokenBID = governance.validateTokenAddress(_tokenB);
//make sure _tokenA is fee token
require(tokenAID <= MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS, "tokenA should be fee token");
//create pair
address pair = pairmanager.createPair(_tokenA, _tokenB);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
tokenAID,
_tokenA,
tokenBID,
_tokenB,
validatePairTokenAddress(pair),
pair
);
}
//create pair including ETH
function createETHPair(address _tokenERC20) external {
requireActive();
governance.requireTokenLister(msg.sender);
//check _tokenERC20 is registered or not
uint16 erc20ID = governance.validateTokenAddress(_tokenERC20);
//create pair
address pair = pairmanager.createPair(address(0), _tokenERC20);
require(pair != address(0), "pair is invalid");
addPairToken(pair);
registerCreatePair(
0,
address(0),
erc20ID,
_tokenERC20,
validatePairTokenAddress(pair),
pair
);
}
function registerCreatePair(uint16 _tokenAID, address _tokenA, uint16 _tokenBID, address _tokenB, uint16 _tokenPair, address _pair) internal {
// Priority Queue request
Operations.CreatePair memory op = Operations.CreatePair({
accountId : 0, //unknown at this point
tokenA : _tokenAID,
tokenB : _tokenBID,
tokenPair : _tokenPair,
pair : _pair
});
bytes memory pubData = Operations.writeCreatePairPubdata(op);
bytes memory userData = abi.encodePacked(
_tokenA, // tokenA address
_tokenB // tokenB address
);
addPriorityRequest(Operations.OpType.CreatePair, pubData, userData);
emit OnchainCreatePair(_tokenAID, _tokenBID, _tokenPair, _pair);
}
// Upgrade functional
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint) {
return UPGRADE_NOTICE_PERIOD;
}
/// @notice Notification that upgrade notice period started
function upgradeNoticePeriodStarted() external {
}
/// @notice Notification that upgrade preparation status is activated
function upgradePreparationStarted() external {
upgradePreparationActive = true;
upgradePreparationActivationTime = now;
}
/// @notice Notification that upgrade canceled
function upgradeCanceled() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Notification that upgrade finishes
function upgradeFinishes() external {
upgradePreparationActive = false;
upgradePreparationActivationTime = 0;
}
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool) {
return !exodusMode;
}
constructor() public {
governance = Governance(msg.sender);
zkSyncCommitBlockAddress = address(this);
zkSyncExitAddress = address(this);
}
/// @notice Franklin contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _governanceAddress The address of Governance contract
/// _verifierAddress The address of Verifier contract
/// _ // FIXME: remove _genesisAccAddress
/// _genesisRoot Genesis blocks (first block) root
function initialize(bytes calldata initializationParameters) external {
require(address(governance) == address(0), "init0");
initializeReentrancyGuard();
(
address _governanceAddress,
address _verifierAddress,
address _verifierExitAddress,
address _pairManagerAddress
) = abi.decode(initializationParameters, (address, address, address, address));
verifier = Verifier(_verifierAddress);
verifierExit = VerifierExit(_verifierExitAddress);
governance = Governance(_governanceAddress);
pairmanager = UniswapV2Factory(_pairManagerAddress);
maxDepositAmount = DEFAULT_MAX_DEPOSIT_AMOUNT;
withdrawGasLimit = ERC20_WITHDRAWAL_GAS_LIMIT;
}
function setGenesisRootAndAddresses(bytes32 _genesisRoot, address _zkSyncCommitBlockAddress, address _zkSyncExitAddress) external {
// This function cannot be called twice as long as
// _zkSyncCommitBlockAddress and _zkSyncExitAddress have been set to
// non-zero.
require(zkSyncCommitBlockAddress == address(0), "sraa1");
require(zkSyncExitAddress == address(0), "sraa2");
blocks[0].stateRoot = _genesisRoot;
zkSyncCommitBlockAddress = _zkSyncCommitBlockAddress;
zkSyncExitAddress = _zkSyncExitAddress;
}
/// @notice zkSync contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Sends tokens
/// @dev NOTE: will revert if transfer call fails or rollup balance difference (before and after transfer) is bigger than _maxAmount
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @param _maxAmount Maximum possible amount of tokens to transfer to this account
function withdrawERC20Guarded(IERC20 _token, address _to, uint128 _amount, uint128 _maxAmount) external returns (uint128 withdrawnAmount) {
require(msg.sender == address(this), "wtg10");
// wtg10 - can be called only from this contract as one "external" call (to revert all this function state changes if it is needed)
uint16 lpTokenId = tokenIds[address(_token)];
uint256 balance_before = _token.balanceOf(address(this));
if (lpTokenId > 0) {
validatePairTokenAddress(address(_token));
pairmanager.mint(address(_token), _to, _amount);
} else {
require(Utils.sendERC20(_token, _to, _amount), "wtg11");
// wtg11 - ERC20 transfer fails
}
uint256 balance_after = _token.balanceOf(address(this));
uint256 balance_diff = balance_before.sub(balance_after);
require(balance_diff <= _maxAmount, "wtg12");
// wtg12 - rollup balance difference (before and after transfer) is bigger than _maxAmount
return SafeCast.toUint128(balance_diff);
}
/// @notice executes pending withdrawals
/// @param _n The number of withdrawals to complete starting from oldest
function completeWithdrawals(uint32 _n) external nonReentrant {
// TODO: when switched to multi validators model we need to add incentive mechanism to call complete.
uint32 toProcess = Utils.minU32(_n, numberOfPendingWithdrawals);
uint32 startIndex = firstPendingWithdrawalIndex;
numberOfPendingWithdrawals -= toProcess;
firstPendingWithdrawalIndex += toProcess;
for (uint32 i = startIndex; i < startIndex + toProcess; ++i) {
uint16 tokenId = pendingWithdrawals[i].tokenId;
address to = pendingWithdrawals[i].to;
// send fails are ignored hence there is always a direct way to withdraw.
delete pendingWithdrawals[i];
bytes22 packedBalanceKey = packAddressAndTokenId(to, tokenId);
uint128 amount = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
// amount is zero means funds has been withdrawn with withdrawETH or withdrawERC20
if (amount != 0) {
balancesToWithdraw[packedBalanceKey].balanceToWithdraw -= amount;
bool sent = false;
if (tokenId == 0) {
address payable toPayable = address(uint160(to));
sent = Utils.sendETHNoRevert(toPayable, amount);
} else {
address tokenAddr = address(0);
if (tokenId < PAIR_TOKEN_START_ID) {
// It is normal ERC20
tokenAddr = governance.tokenAddresses(tokenId);
} else {
// It is pair token
tokenAddr = tokenAddresses[tokenId];
}
// tokenAddr cannot be 0
require(tokenAddr != address(0), "cwt0");
// we can just check that call not reverts because it wants to withdraw all amount
(sent,) = address(this).call.gas(withdrawGasLimit)(
abi.encodeWithSignature("withdrawERC20Guarded(address,address,uint128,uint128)", tokenAddr, to, amount, amount)
);
}
if (!sent) {
balancesToWithdraw[packedBalanceKey].balanceToWithdraw += amount;
}
}
}
if (toProcess > 0) {
emit PendingWithdrawalsComplete(startIndex, startIndex + toProcess);
}
}
/// @notice Accrues users balances from deposit priority requests in Exodus mode
/// @dev WARNING: Only for Exodus mode
/// @dev Canceling may take several separate transactions to be completed
/// @param _n number of requests to process
function cancelOutstandingDepositsForExodusMode(uint64 _n) external nonReentrant {
require(exodusMode, "coe01");
// exodus mode not active
uint64 toProcess = Utils.minU64(totalOpenPriorityRequests, _n);
require(toProcess > 0, "coe02");
// no deposits to process
for (uint64 id = firstPriorityRequestId; id < firstPriorityRequestId + toProcess; id++) {
if (priorityRequests[id].opType == Operations.OpType.Deposit) {
Operations.Deposit memory op = Operations.readDepositPubdata(priorityRequests[id].pubData);
bytes22 packedBalanceKey = packAddressAndTokenId(op.owner, op.tokenId);
balancesToWithdraw[packedBalanceKey].balanceToWithdraw += op.amount;
}
delete priorityRequests[id];
}
firstPriorityRequestId += toProcess;
totalOpenPriorityRequests -= toProcess;
}
/// @notice Deposit ETH to Layer 2 - transfer ether from user into contract, validate it, register deposit
/// @param _franklinAddr The receiver Layer 2 address
function depositETH(address _franklinAddr) external payable nonReentrant {
requireActive();
registerDeposit(0, SafeCast.toUint128(msg.value), _franklinAddr);
}
/// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to sender
/// @param _amount Ether amount to withdraw
function withdrawETH(uint128 _amount) external nonReentrant {
registerWithdrawal(0, _amount, msg.sender);
(bool success,) = msg.sender.call.value(_amount)("");
require(success, "fwe11");
// ETH withdraw failed
}
/// @notice Withdraw ETH to Layer 1 - register withdrawal and transfer ether to _to address
/// @param _amount Ether amount to withdraw
function withdrawETHWithAddress(uint128 _amount, address payable _to) external nonReentrant {
require(_to != address(0), "ipa11");
registerWithdrawal(0, _amount, _to);
(bool success,) = _to.call.value(_amount)("");
require(success, "fwe12");
// ETH withdraw failed
}
/// @notice Config amount limit for each ERC20 deposit
/// @param _amount Max deposit amount
function setMaxDepositAmount(uint128 _amount) external {
governance.requireGovernor(msg.sender);
maxDepositAmount = _amount;
}
/// @notice Config gas limit for withdraw erc20 token
/// @param _gasLimit withdraw erc20 gas limit
function setWithDrawGasLimit(uint256 _gasLimit) external {
governance.requireGovernor(msg.sender);
withdrawGasLimit = _gasLimit;
}
/// @notice Deposit ERC20 token to Layer 2 - transfer ERC20 tokens from user into contract, validate it, register deposit
/// @param _token Token address
/// @param _amount Token amount
/// @param _franklinAddr Receiver Layer 2 address
function depositERC20(IERC20 _token, uint104 _amount, address _franklinAddr) external nonReentrant {
requireActive();
// Get token id by its address
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
} else {
lpTokenId = validatePairTokenAddress(address(_token));
}
uint256 balance_before = 0;
uint256 balance_after = 0;
uint128 deposit_amount = 0;
if (lpTokenId > 0) {
// Note: For lp token, main contract always has no money
balance_before = _token.balanceOf(msg.sender);
pairmanager.burn(address(_token), msg.sender, SafeCast.toUint128(_amount));
balance_after = _token.balanceOf(msg.sender);
deposit_amount = SafeCast.toUint128(balance_before.sub(balance_after));
require(deposit_amount <= maxDepositAmount, "fd011");
registerDeposit(lpTokenId, deposit_amount, _franklinAddr);
} else {
balance_before = _token.balanceOf(address(this));
require(Utils.transferFromERC20(_token, msg.sender, address(this), SafeCast.toUint128(_amount)), "fd012");
// token transfer failed deposit
balance_after = _token.balanceOf(address(this));
deposit_amount = SafeCast.toUint128(balance_after.sub(balance_before));
require(deposit_amount <= maxDepositAmount, "fd013");
registerDeposit(tokenId, deposit_amount, _franklinAddr);
}
}
/// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to sender
/// @param _token Token address
/// @param _amount amount to withdraw
function withdrawERC20(IERC20 _token, uint128 _amount) external nonReentrant {
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
} else {
tokenId = validatePairTokenAddress(address(_token));
}
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
uint128 withdrawnAmount = this.withdrawERC20Guarded(_token, msg.sender, _amount, balance);
registerWithdrawal(tokenId, withdrawnAmount, msg.sender);
}
/// @notice Withdraw ERC20 token to Layer 1 - register withdrawal and transfer ERC20 to _to address
/// @param _token Token address
/// @param _amount amount to withdraw
/// @param _to address to withdraw
function withdrawERC20WithAddress(IERC20 _token, uint128 _amount, address payable _to) external nonReentrant {
require(_to != address(0), "ipa12");
uint16 lpTokenId = tokenIds[address(_token)];
uint16 tokenId = 0;
if (lpTokenId == 0) {
// This means it is not a pair address
tokenId = governance.validateTokenAddress(address(_token));
} else {
tokenId = validatePairTokenAddress(address(_token));
}
bytes22 packedBalanceKey = packAddressAndTokenId(_to, tokenId);
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
uint128 withdrawnAmount = this.withdrawERC20Guarded(_token, _to, _amount, balance);
registerWithdrawal(tokenId, withdrawnAmount, _to);
}
/// @notice Register full exit request - pack pubdata, add priority request
/// @param _accountId Numerical id of the account
/// @param _token Token address, 0 address for ether
function fullExit(uint32 _accountId, address _token) external nonReentrant {
requireActive();
require(_accountId <= MAX_ACCOUNT_ID, "fee11");
uint16 tokenId;
if (_token == address(0)) {
tokenId = 0;
} else {
tokenId = governance.validateTokenAddress(_token);
require(tokenId <= MAX_AMOUNT_OF_REGISTERED_TOKENS, "fee12");
}
// Priority Queue request
Operations.FullExit memory op = Operations.FullExit({
accountId : _accountId,
owner : msg.sender,
tokenId : tokenId,
amount : 0 // unknown at this point
});
bytes memory pubData = Operations.writeFullExitPubdata(op);
addPriorityRequest(Operations.OpType.FullExit, pubData, "");
// User must fill storage slot of balancesToWithdraw(msg.sender, tokenId) with nonzero value
// In this case operator should just overwrite this slot during confirming withdrawal
bytes22 packedBalanceKey = packAddressAndTokenId(msg.sender, tokenId);
balancesToWithdraw[packedBalanceKey].gasReserveValue = 0xff;
}
/// @notice Register deposit request - pack pubdata, add priority request and emit OnchainDeposit event
/// @param _tokenId Token by id
/// @param _amount Token amount
/// @param _owner Receiver
function registerDeposit(
uint16 _tokenId,
uint128 _amount,
address _owner
) internal {
// Priority Queue request
Operations.Deposit memory op = Operations.Deposit({
accountId : 0, // unknown at this point
owner : _owner,
tokenId : _tokenId,
amount : _amount
});
bytes memory pubData = Operations.writeDepositPubdata(op);
addPriorityRequest(Operations.OpType.Deposit, pubData, "");
emit OnchainDeposit(
msg.sender,
_tokenId,
_amount,
_owner
);
}
/// @notice Register withdrawal - update user balance and emit OnchainWithdrawal event
/// @param _token - token by id
/// @param _amount - token amount
/// @param _to - address to withdraw to
function registerWithdrawal(uint16 _token, uint128 _amount, address payable _to) internal {
bytes22 packedBalanceKey = packAddressAndTokenId(_to, _token);
uint128 balance = balancesToWithdraw[packedBalanceKey].balanceToWithdraw;
balancesToWithdraw[packedBalanceKey].balanceToWithdraw = balance.sub(_amount);
emit OnchainWithdrawal(
_to,
_token,
_amount
);
}
/// @notice Checks that current state not is exodus mode
function requireActive() internal view {
require(!exodusMode, "fre11");
// exodus mode activated
}
// Priority queue
/// @notice Saves priority request in storage
/// @dev Calculates expiration block for request, store this request and emit NewPriorityRequest event
/// @param _opType Rollup operation type
/// @param _pubData Operation pubdata
function addPriorityRequest(
Operations.OpType _opType,
bytes memory _pubData,
bytes memory _userData
) internal {
// Expiration block is: current block number + priority expiration delta
uint256 expirationBlock = block.number + PRIORITY_EXPIRATION;
uint64 nextPriorityRequestId = firstPriorityRequestId + totalOpenPriorityRequests;
priorityRequests[nextPriorityRequestId] = PriorityOperation({
opType : _opType,
pubData : _pubData,
expirationBlock : expirationBlock
});
emit NewPriorityRequest(
msg.sender,
nextPriorityRequestId,
_opType,
_pubData,
_userData,
expirationBlock
);
totalOpenPriorityRequests++;
}
// The contract is too large. Break some functions to zkSyncCommitBlockAddress
function() external payable {
address nextAddress = zkSyncCommitBlockAddress;
require(nextAddress != address(0), "zkSyncCommitBlockAddress should be set");
// Execute external function from facet using delegatecall and return any value.
assembly {
calldatacopy(0, 0, calldatasize())
let result := delegatecall(gas(), nextAddress, 0, calldatasize(), 0, 0)
returndatacopy(0, 0, returndatasize())
switch result
case 0 {revert(0, returndatasize())}
default {return (0, returndatasize())}
}
}
}
pragma solidity ^0.5.0;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*
* _Since v2.5.0:_ this module is now much more gas efficient, given net gas
* metering changes introduced in the Istanbul hardfork.
*/
contract ReentrancyGuard {
/// Address of lock flag variable.
/// Flag is placed at random memory location to not interfere with Storage contract.
uint constant private LOCK_FLAG_ADDRESS = 0x8e94fed44239eb2314ab7a406345e6c5a8f0ccedf3b600de3d004e672c33abf4; // keccak256("ReentrancyGuard") - 1;
function initializeReentrancyGuard () internal {
// Storing an initial non-zero value makes deployment a bit more
// expensive, but in exchange the refund on every call to nonReentrant
// will be lower in amount. Since refunds are capped to a percetange of
// the total transaction's gas, it is best to keep them low in cases
// like this one, to increase the likelihood of the full refund coming
// into effect.
assembly { sstore(LOCK_FLAG_ADDRESS, 1) }
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
bool notEntered;
assembly { notEntered := sload(LOCK_FLAG_ADDRESS) }
// On the first call to nonReentrant, _notEntered will be true
require(notEntered, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
assembly { sstore(LOCK_FLAG_ADDRESS, 0) }
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
assembly { sstore(LOCK_FLAG_ADDRESS, 1) }
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.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 SafeMathUInt128 {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint128 a, uint128 b) internal pure returns (uint128) {
uint128 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint128 a, uint128 b) internal pure returns (uint128) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
require(b <= a, errorMessage);
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
// 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;
}
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint128 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(uint128 a, uint128 b) internal pure returns (uint128) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint128 a, uint128 b, string memory errorMessage) internal pure returns (uint128) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
/**
* @dev Wrappers over Solidity's uintXX casting operators with added overflow
* checks.
*
* Downcasting from uint256 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} to extend it to smaller types, by performing
* all math on `uint256` and then downcasting.
*
* _Available since v2.5.0._
*/
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 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 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);
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./Bytes.sol";
library Utils {
/// @notice Returns lesser of two values
function minU32(uint32 a, uint32 b) internal pure returns (uint32) {
return a < b ? a : b;
}
/// @notice Returns lesser of two values
function minU64(uint64 a, uint64 b) internal pure returns (uint64) {
return a < b ? a : b;
}
/// @notice Sends tokens
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transfer` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function sendERC20(IERC20 _token, address _to, uint256 _amount) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call(
abi.encodeWithSignature("transfer(address,uint256)", _to, _amount)
);
// `transfer` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Transfers token from one address to another
/// @dev NOTE: this function handles tokens that have transfer function not strictly compatible with ERC20 standard
/// @dev NOTE: call `transferFrom` to this token may return (bool) or nothing
/// @param _token Token address
/// @param _from Address of sender
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function transferFromERC20(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
(bool callSuccess, bytes memory callReturnValueEncoded) = address(_token).call(
abi.encodeWithSignature("transferFrom(address,address,uint256)", _from, _to, _amount)
);
// `transferFrom` method may return (bool) or nothing.
bool returnedSuccess = callReturnValueEncoded.length == 0 || abi.decode(callReturnValueEncoded, (bool));
return callSuccess && returnedSuccess;
}
/// @notice Sends ETH
/// @param _to Address of recipient
/// @param _amount Amount of tokens to transfer
/// @return bool flag indicating that transfer is successful
function sendETHNoRevert(address payable _to, uint256 _amount) internal returns (bool) {
// TODO: Use constant from Config
uint256 ETH_WITHDRAWAL_GAS_LIMIT = 10000;
(bool callSuccess, ) = _to.call.gas(ETH_WITHDRAWAL_GAS_LIMIT).value(_amount)("");
return callSuccess;
}
/// @notice Recovers signer's address from ethereum signature for given message
/// @param _signature 65 bytes concatenated. R (32) + S (32) + V (1)
/// @param _message signed message.
/// @return address of the signer
function recoverAddressFromEthSignature(bytes memory _signature, bytes memory _message) internal pure returns (address) {
require(_signature.length == 65, "ves10"); // incorrect signature length
bytes32 signR;
bytes32 signS;
uint offset = 0;
(offset, signR) = Bytes.readBytes32(_signature, offset);
(offset, signS) = Bytes.readBytes32(_signature, offset);
uint8 signV = uint8(_signature[offset]);
return ecrecover(keccak256(_message), signV, signR, signS);
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./Governance.sol";
import "./Verifier.sol";
import "./VerifierExit.sol";
import "./Operations.sol";
import "./uniswap/UniswapV2Factory.sol";
/// @title ZKSwap storage contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Storage {
/// @notice Flag indicates that upgrade preparation status is active
/// @dev Will store false in case of not active upgrade mode
bool public upgradePreparationActive;
/// @notice Upgrade preparation activation timestamp (as seconds since unix epoch)
/// @dev Will be equal to zero in case of not active upgrade mode
uint public upgradePreparationActivationTime;
/// @notice Verifier contract. Used to verify block proof and exit proof
Verifier internal verifier;
VerifierExit internal verifierExit;
/// @notice Governance contract. Contains the governor (the owner) of whole system, validators list, possible tokens list
Governance internal governance;
UniswapV2Factory internal pairmanager;
struct BalanceToWithdraw {
uint128 balanceToWithdraw;
uint8 gasReserveValue; // gives user opportunity to fill storage slot with nonzero value
}
/// @notice Root-chain balances (per owner and token id, see packAddressAndTokenId) to withdraw
mapping(bytes22 => BalanceToWithdraw) public balancesToWithdraw;
/// @notice verified withdrawal pending to be executed.
struct PendingWithdrawal {
address to;
uint16 tokenId;
}
/// @notice Verified but not executed withdrawals for addresses stored in here (key is pendingWithdrawal's index in pending withdrawals queue)
mapping(uint32 => PendingWithdrawal) public pendingWithdrawals;
uint32 public firstPendingWithdrawalIndex;
uint32 public numberOfPendingWithdrawals;
/// @notice Total number of verified blocks i.e. blocks[totalBlocksVerified] points at the latest verified block (block 0 is genesis)
uint32 public totalBlocksVerified;
/// @notice Total number of checked blocks
uint32 public totalBlocksChecked;
/// @notice Total number of committed blocks i.e. blocks[totalBlocksCommitted] points at the latest committed block
uint32 public totalBlocksCommitted;
/// @notice Rollup block data (once per block)
/// @member validator Block producer
/// @member committedAtBlock ETH block number at which this block was committed
/// @member cumulativeOnchainOperations Total number of operations in this and all previous blocks
/// @member priorityOperations Total number of priority operations for this block
/// @member commitment Hash of the block circuit commitment
/// @member stateRoot New tree root hash
///
/// Consider memory alignment when changing field order: https://solidity.readthedocs.io/en/v0.4.21/miscellaneous.html
struct Block {
uint32 committedAtBlock;
uint64 priorityOperations;
uint32 chunks;
bytes32 withdrawalsDataHash; /// can be restricted to 16 bytes to reduce number of required storage slots
bytes32 commitment;
bytes32 stateRoot;
}
/// @notice Blocks by Franklin block id
mapping(uint32 => Block) public blocks;
/// @notice Onchain operations - operations processed inside rollup blocks
/// @member opType Onchain operation type
/// @member amount Amount used in the operation
/// @member pubData Operation pubdata
struct OnchainOperation {
Operations.OpType opType;
bytes pubData;
}
/// @notice Flag indicates that a user has exited certain token balance (per account id and tokenId)
mapping(uint32 => mapping(uint16 => bool)) public exited;
mapping(uint32 => mapping(uint32 => bool)) public swap_exited;
/// @notice Flag indicates that exodus (mass exit) mode is triggered
/// @notice Once it was raised, it can not be cleared again, and all users must exit
bool public exodusMode;
/// @notice User authenticated fact hashes for some nonce.
mapping(address => mapping(uint32 => bytes32)) public authFacts;
/// @notice Priority Operation container
/// @member opType Priority operation type
/// @member pubData Priority operation public data
/// @member expirationBlock Expiration block number (ETH block) for this request (must be satisfied before)
struct PriorityOperation {
Operations.OpType opType;
bytes pubData;
uint256 expirationBlock;
}
/// @notice Priority Requests mapping (request id - operation)
/// @dev Contains op type, pubdata and expiration block of unsatisfied requests.
/// @dev Numbers are in order of requests receiving
mapping(uint64 => PriorityOperation) public priorityRequests;
/// @notice First open priority request id
uint64 public firstPriorityRequestId;
/// @notice Total number of requests
uint64 public totalOpenPriorityRequests;
/// @notice Total number of committed requests.
/// @dev Used in checks: if the request matches the operation on Rollup contract and if provided number of requests is not too big
uint64 public totalCommittedPriorityRequests;
/// @notice Packs address and token id into single word to use as a key in balances mapping
function packAddressAndTokenId(address _address, uint16 _tokenId) internal pure returns (bytes22) {
return bytes22((uint176(_address) | (uint176(_tokenId) << 160)));
}
/// @notice Gets value from balancesToWithdraw
function getBalanceToWithdraw(address _address, uint16 _tokenId) public view returns (uint128) {
return balancesToWithdraw[packAddressAndTokenId(_address, _tokenId)].balanceToWithdraw;
}
address public zkSyncCommitBlockAddress;
address public zkSyncExitAddress;
/// @notice Limit the max amount for each ERC20 deposit
uint128 public maxDepositAmount;
/// @notice withdraw erc20 token gas limit
uint256 public withdrawGasLimit;
}
pragma solidity ^0.5.0;
/// @title ZKSwap configuration constants
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Config {
/// @notice ERC20 token withdrawal gas limit, used only for complete withdrawals
uint256 constant ERC20_WITHDRAWAL_GAS_LIMIT = 350000;
/// @notice ETH token withdrawal gas limit, used only for complete withdrawals
uint256 constant ETH_WITHDRAWAL_GAS_LIMIT = 10000;
/// @notice Bytes in one chunk
uint8 constant CHUNK_BYTES = 11;
/// @notice ZKSwap address length
uint8 constant ADDRESS_BYTES = 20;
uint8 constant PUBKEY_HASH_BYTES = 20;
/// @notice Public key bytes length
uint8 constant PUBKEY_BYTES = 32;
/// @notice Ethereum signature r/s bytes length
uint8 constant ETH_SIGN_RS_BYTES = 32;
/// @notice Success flag bytes length
uint8 constant SUCCESS_FLAG_BYTES = 1;
/// @notice Max amount of fee tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 constant MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS = 32 - 1;
/// @notice start ID for user tokens
uint16 constant USER_TOKENS_START_ID = 32;
/// @notice Max amount of user tokens registered in the network
uint16 constant MAX_AMOUNT_OF_REGISTERED_USER_TOKENS = 16352;
/// @notice Max amount of tokens registered in the network
uint16 constant MAX_AMOUNT_OF_REGISTERED_TOKENS = 16384 - 1;
/// @notice Max account id that could be registered in the network
uint32 constant MAX_ACCOUNT_ID = (2 ** 28) - 1;
/// @notice Expected average period of block creation
uint256 constant BLOCK_PERIOD = 15 seconds;
/// @notice ETH blocks verification expectation
/// Blocks can be reverted if they are not verified for at least EXPECT_VERIFICATION_IN.
/// If set to 0 validator can revert blocks at any time.
uint256 constant EXPECT_VERIFICATION_IN = 0 hours / BLOCK_PERIOD;
uint256 constant NOOP_BYTES = 1 * CHUNK_BYTES;
uint256 constant CREATE_PAIR_BYTES = 3 * CHUNK_BYTES;
uint256 constant DEPOSIT_BYTES = 4 * CHUNK_BYTES;
uint256 constant TRANSFER_TO_NEW_BYTES = 4 * CHUNK_BYTES;
uint256 constant PARTIAL_EXIT_BYTES = 5 * CHUNK_BYTES;
uint256 constant TRANSFER_BYTES = 2 * CHUNK_BYTES;
uint256 constant UNISWAP_ADD_LIQ_BYTES = 3 * CHUNK_BYTES;
uint256 constant UNISWAP_RM_LIQ_BYTES = 3 * CHUNK_BYTES;
uint256 constant UNISWAP_SWAP_BYTES = 2 * CHUNK_BYTES;
/// @notice Full exit operation length
uint256 constant FULL_EXIT_BYTES = 4 * CHUNK_BYTES;
/// @notice OnchainWithdrawal data length
uint256 constant ONCHAIN_WITHDRAWAL_BYTES = 1 + 20 + 2 + 16; // (uint8 addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount)
/// @notice ChangePubKey operation length
uint256 constant CHANGE_PUBKEY_BYTES = 5 * CHUNK_BYTES;
/// @notice Expiration delta for priority request to be satisfied (in seconds)
/// NOTE: Priority expiration should be > (EXPECT_VERIFICATION_IN * BLOCK_PERIOD), otherwise incorrect block with priority op could not be reverted.
uint256 constant PRIORITY_EXPIRATION_PERIOD = 3 days;
/// @notice Expiration delta for priority request to be satisfied (in ETH blocks)
uint256 constant PRIORITY_EXPIRATION = PRIORITY_EXPIRATION_PERIOD / BLOCK_PERIOD;
/// @notice Maximum number of priority request to clear during verifying the block
/// @dev Cause deleting storage slots cost 5k gas per each slot it's unprofitable to clear too many slots
/// @dev Value based on the assumption of ~750k gas cost of verifying and 5 used storage slots per PriorityOperation structure
uint64 constant MAX_PRIORITY_REQUESTS_TO_DELETE_IN_VERIFY = 6;
/// @notice Reserved time for users to send full exit priority operation in case of an upgrade (in seconds)
uint constant MASS_FULL_EXIT_PERIOD = 3 days;
/// @notice Reserved time for users to withdraw funds from full exit priority operation in case of an upgrade (in seconds)
uint constant TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT = 2 days;
/// @notice Notice period before activation preparation status of upgrade mode (in seconds)
// NOTE: we must reserve for users enough time to send full exit operation, wait maximum time for processing this operation and withdraw funds from it.
uint constant UPGRADE_NOTICE_PERIOD = MASS_FULL_EXIT_PERIOD + PRIORITY_EXPIRATION_PERIOD + TIME_TO_WITHDRAW_FUNDS_FROM_FULL_EXIT;
// @notice Default amount limit for each ERC20 deposit
uint128 constant DEFAULT_MAX_DEPOSIT_AMOUNT = 2 ** 85;
}
pragma solidity ^0.5.0;
import "./Upgradeable.sol";
import "./Operations.sol";
/// @title ZKSwap events
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface Events {
/// @notice Event emitted when a block is committed
event BlockCommit(uint32 indexed blockNumber);
/// @notice Event emitted when a block is verified
event BlockVerification(uint32 indexed blockNumber);
/// @notice Event emitted when a sequence of blocks is verified
event MultiblockVerification(uint32 indexed blockNumberFrom, uint32 indexed blockNumberTo);
/// @notice Event emitted when user send a transaction to withdraw her funds from onchain balance
event OnchainWithdrawal(
address indexed owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Event emitted when user send a transaction to deposit her funds
event OnchainDeposit(
address indexed sender,
uint16 indexed tokenId,
uint128 amount,
address indexed owner
);
event OnchainCreatePair(
uint16 indexed tokenAId,
uint16 indexed tokenBId,
uint16 indexed pairId,
address pair
);
/// @notice Event emitted when user sends a authentication fact (e.g. pub-key hash)
event FactAuth(
address indexed sender,
uint32 nonce,
bytes fact
);
/// @notice Event emitted when blocks are reverted
event BlocksRevert(
uint32 indexed totalBlocksVerified,
uint32 indexed totalBlocksCommitted
);
/// @notice Exodus mode entered event
event ExodusMode();
/// @notice New priority request event. Emitted when a request is placed into mapping
event NewPriorityRequest(
address sender,
uint64 serialId,
Operations.OpType opType,
bytes pubData,
bytes userData,
uint256 expirationBlock
);
/// @notice Deposit committed event.
event DepositCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Full exit committed event.
event FullExitCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
address owner,
uint16 indexed tokenId,
uint128 amount
);
/// @notice Pending withdrawals index range that were added in the verifyBlock operation.
/// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex)
event PendingWithdrawalsAdd(
uint32 queueStartIndex,
uint32 queueEndIndex
);
/// @notice Pending withdrawals index range that were executed in the completeWithdrawals operation.
/// NOTE: processed indexes in the queue map are [queueStartIndex, queueEndIndex)
event PendingWithdrawalsComplete(
uint32 queueStartIndex,
uint32 queueEndIndex
);
event CreatePairCommit(
uint32 indexed zkSyncBlockId,
uint32 indexed accountId,
uint16 tokenAId,
uint16 tokenBId,
uint16 indexed tokenPairId,
address pair
);
}
/// @title Upgrade events
/// @author Matter Labs
interface UpgradeEvents {
/// @notice Event emitted when new upgradeable contract is added to upgrade gatekeeper's list of managed contracts
event NewUpgradable(
uint indexed versionId,
address indexed upgradeable
);
/// @notice Upgrade mode enter event
event NoticePeriodStart(
uint indexed versionId,
address[] newTargets,
uint noticePeriod // notice period (in seconds)
);
/// @notice Upgrade mode cancel event
event UpgradeCancel(
uint indexed versionId
);
/// @notice Upgrade mode preparation status event
event PreparationStart(
uint indexed versionId
);
/// @notice Upgrade mode complete event
event UpgradeComplete(
uint indexed versionId,
address[] newTargets
);
}
pragma solidity ^0.5.0;
// Functions named bytesToX, except bytesToBytes20, where X is some type of size N < 32 (size of one word)
// implements the following algorithm:
// f(bytes memory input, uint offset) -> X out
// where byte representation of out is N bytes from input at the given offset
// 1) We compute memory location of the word W such that last N bytes of W is input[offset..offset+N]
// W_address = input + 32 (skip stored length of bytes) + offset - (32 - N) == input + offset + N
// 2) We load W from memory into out, last N bytes of W are placed into out
library Bytes {
function toBytesFromUInt16(uint16 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 2);
}
function toBytesFromUInt24(uint24 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 3);
}
function toBytesFromUInt32(uint32 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 4);
}
function toBytesFromUInt128(uint128 self) internal pure returns (bytes memory _bts) {
return toBytesFromUIntTruncated(uint(self), 16);
}
// Copies 'len' lower bytes from 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length 'len'.
function toBytesFromUIntTruncated(uint self, uint8 byteLength) private pure returns (bytes memory bts) {
require(byteLength <= 32, "bt211");
bts = new bytes(byteLength);
// Even though the bytes will allocate a full word, we don't want
// any potential garbage bytes in there.
uint data = self << ((32 - byteLength) * 8);
assembly {
mstore(add(bts, /*BYTES_HEADER_SIZE*/32), data)
}
}
// Copies 'self' into a new 'bytes memory'.
// Returns the newly created 'bytes memory'. The returned bytes will be of length '20'.
function toBytesFromAddress(address self) internal pure returns (bytes memory bts) {
bts = toBytesFromUIntTruncated(uint(self), 20);
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToAddress(bytes memory self, uint256 _start) internal pure returns (address addr) {
uint256 offset = _start + 20;
require(self.length >= offset, "bta11");
assembly {
addr := mload(add(self, offset))
}
}
// Reasoning about why this function works is similar to that of other similar functions, except NOTE below.
// NOTE: that bytes1..32 is stored in the beginning of the word unlike other primitive types
// NOTE: theoretically possible overflow of (_start + 20)
function bytesToBytes20(bytes memory self, uint256 _start) internal pure returns (bytes20 r) {
require(self.length >= (_start + 20), "btb20");
assembly {
r := mload(add(add(self, 0x20), _start))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x2)
function bytesToUInt16(bytes memory _bytes, uint256 _start) internal pure returns (uint16 r) {
uint256 offset = _start + 0x2;
require(_bytes.length >= offset, "btu02");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x3)
function bytesToUInt24(bytes memory _bytes, uint256 _start) internal pure returns (uint24 r) {
uint256 offset = _start + 0x3;
require(_bytes.length >= offset, "btu03");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x4)
function bytesToUInt32(bytes memory _bytes, uint256 _start) internal pure returns (uint32 r) {
uint256 offset = _start + 0x4;
require(_bytes.length >= offset, "btu04");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x10)
function bytesToUInt128(bytes memory _bytes, uint256 _start) internal pure returns (uint128 r) {
uint256 offset = _start + 0x10;
require(_bytes.length >= offset, "btu16");
assembly {
r := mload(add(_bytes, offset))
}
}
// See comment at the top of this file for explanation of how this function works.
// NOTE: theoretically possible overflow of (_start + 0x14)
function bytesToUInt160(bytes memory _bytes, uint256 _start) internal pure returns (uint160 r) {
uint256 offset = _start + 0x14;
require(_bytes.length >= offset, "btu20");
assembly {
r := mload(add(_bytes, offset))
}
}
// NOTE: theoretically possible overflow of (_start + 0x20)
function bytesToBytes32(bytes memory _bytes, uint256 _start) internal pure returns (bytes32 r) {
uint256 offset = _start + 0x20;
require(_bytes.length >= offset, "btb32");
assembly {
r := mload(add(_bytes, offset))
}
}
// Original source code: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol#L228
// Get slice from bytes arrays
// Returns the newly created 'bytes memory'
// NOTE: theoretically possible overflow of (_start + _length)
function slice(
bytes memory _bytes,
uint _start,
uint _length
)
internal
pure
returns (bytes memory)
{
require(_bytes.length >= (_start + _length), "bse11"); // bytes length is less then start byte + length bytes
bytes memory tempBytes = new bytes(_length);
if (_length != 0) {
// TODO: Review this thoroughly.
assembly {
let slice_curr := add(tempBytes, 0x20)
let slice_end := add(slice_curr, _length)
for {
let array_current := add(_bytes, add(_start, 0x20))
} lt(slice_curr, slice_end) {
slice_curr := add(slice_curr, 0x20)
array_current := add(array_current, 0x20)
} {
mstore(slice_curr, mload(array_current))
}
}
}
return tempBytes;
}
/// Reads byte stream
/// @return new_offset - offset + amount of bytes read
/// @return data - actually read data
// NOTE: theoretically possible overflow of (_offset + _length)
function read(bytes memory _data, uint _offset, uint _length) internal pure returns (uint new_offset, bytes memory data) {
data = slice(_data, _offset, _length);
new_offset = _offset + _length;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readBool(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bool r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]) != 0;
}
// NOTE: theoretically possible overflow of (_offset + 1)
function readUint8(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint8 r) {
new_offset = _offset + 1;
r = uint8(_data[_offset]);
}
// NOTE: theoretically possible overflow of (_offset + 2)
function readUInt16(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint16 r) {
new_offset = _offset + 2;
r = bytesToUInt16(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 3)
function readUInt24(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint24 r) {
new_offset = _offset + 3;
r = bytesToUInt24(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 4)
function readUInt32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint32 r) {
new_offset = _offset + 4;
r = bytesToUInt32(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 16)
function readUInt128(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint128 r) {
new_offset = _offset + 16;
r = bytesToUInt128(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readUInt160(bytes memory _data, uint _offset) internal pure returns (uint new_offset, uint160 r) {
new_offset = _offset + 20;
r = bytesToUInt160(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readAddress(bytes memory _data, uint _offset) internal pure returns (uint new_offset, address r) {
new_offset = _offset + 20;
r = bytesToAddress(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 20)
function readBytes20(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes20 r) {
new_offset = _offset + 20;
r = bytesToBytes20(_data, _offset);
}
// NOTE: theoretically possible overflow of (_offset + 32)
function readBytes32(bytes memory _data, uint _offset) internal pure returns (uint new_offset, bytes32 r) {
new_offset = _offset + 32;
r = bytesToBytes32(_data, _offset);
}
// Helper function for hex conversion.
function halfByteToHex(byte _byte) internal pure returns (byte _hexByte) {
require(uint8(_byte) < 0x10, "hbh11"); // half byte's value is out of 0..15 range.
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
return byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byte) * 8)));
}
// Convert bytes to ASCII hex representation
function bytesToHexASCIIBytes(bytes memory _input) internal pure returns (bytes memory _output) {
bytes memory outStringBytes = new bytes(_input.length * 2);
// code in `assembly` construction is equivalent of the next code:
// for (uint i = 0; i < _input.length; ++i) {
// outStringBytes[i*2] = halfByteToHex(_input[i] >> 4);
// outStringBytes[i*2+1] = halfByteToHex(_input[i] & 0x0f);
// }
assembly {
let input_curr := add(_input, 0x20)
let input_end := add(input_curr, mload(_input))
for {
let out_curr := add(outStringBytes, 0x20)
} lt(input_curr, input_end) {
input_curr := add(input_curr, 0x01)
out_curr := add(out_curr, 0x02)
} {
let curr_input_byte := shr(0xf8, mload(input_curr))
// here outStringByte from each half of input byte calculates by the next:
//
// "FEDCBA9876543210" ASCII-encoded, shifted and automatically truncated.
// outStringByte = byte (uint8 (0x66656463626139383736353433323130 >> (uint8 (_byteHalf) * 8)))
mstore(out_curr, shl(0xf8, shr(mul(shr(0x04, curr_input_byte), 0x08), 0x66656463626139383736353433323130)))
mstore(add(out_curr, 0x01), shl(0xf8, shr(mul(and(0x0f, curr_input_byte), 0x08), 0x66656463626139383736353433323130)))
}
}
return outStringBytes;
}
/// Trim bytes into single word
function trim(bytes memory _data, uint _new_length) internal pure returns (uint r) {
require(_new_length <= 0x20, "trm10"); // new_length is longer than word
require(_data.length >= _new_length, "trm11"); // data is to short
uint a;
assembly {
a := mload(add(_data, 0x20)) // load bytes into uint256
}
return a >> ((0x20 - _new_length) * 8);
}
}
pragma solidity ^0.5.0;
import "./Bytes.sol";
/// @title ZKSwap operations tools
library Operations {
// Circuit ops and their pubdata (chunks * bytes)
/// @notice ZKSwap circuit operation type
enum OpType {
Noop,
Deposit,
TransferToNew,
PartialExit,
_CloseAccount, // used for correct op id offset
Transfer,
FullExit,
ChangePubKey,
CreatePair,
AddLiquidity,
RemoveLiquidity,
Swap
}
// Byte lengths
uint8 constant TOKEN_BYTES = 2;
uint8 constant PUBKEY_BYTES = 32;
uint8 constant NONCE_BYTES = 4;
uint8 constant PUBKEY_HASH_BYTES = 20;
uint8 constant ADDRESS_BYTES = 20;
/// @notice Packed fee bytes lengths
uint8 constant FEE_BYTES = 2;
/// @notice ZKSwap account id bytes lengths
uint8 constant ACCOUNT_ID_BYTES = 4;
uint8 constant AMOUNT_BYTES = 16;
/// @notice Signature (for example full exit signature) bytes length
uint8 constant SIGNATURE_BYTES = 64;
// Deposit pubdata
struct Deposit {
uint32 accountId;
uint16 tokenId;
uint128 amount;
address owner;
}
uint public constant PACKED_DEPOSIT_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + TOKEN_BYTES + AMOUNT_BYTES + ADDRESS_BYTES;
/// Deserialize deposit pubdata
function readDepositPubdata(bytes memory _data) internal pure
returns (Deposit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
require(offset == PACKED_DEPOSIT_PUBDATA_BYTES, "rdp10"); // reading invalid deposit pubdata size
}
/// Serialize deposit pubdata
function writeDepositPubdata(Deposit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenId, // tokenId
op.amount, // amount
op.owner // owner
);
}
/// @notice Check that deposit pubdata from request and block matches
function depositPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_DEPOSIT_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
// FullExit pubdata
struct FullExit {
uint32 accountId;
address owner;
uint16 tokenId;
uint128 amount;
}
uint public constant PACKED_FULL_EXIT_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + ADDRESS_BYTES + TOKEN_BYTES + AMOUNT_BYTES;
function readFullExitPubdata(bytes memory _data) internal pure
returns (FullExit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
require(offset == PACKED_FULL_EXIT_PUBDATA_BYTES, "rfp10"); // reading invalid full exit pubdata size
}
function writeFullExitPubdata(FullExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
op.accountId, // accountId
op.owner, // owner
op.tokenId, // tokenId
op.amount // amount
);
}
/// @notice Check that full exit pubdata from request and block matches
function fullExitPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// `amount` is ignored because it is present in block pubdata but not in priority queue
uint lhs = Bytes.trim(_lhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES);
uint rhs = Bytes.trim(_rhs, PACKED_FULL_EXIT_PUBDATA_BYTES - AMOUNT_BYTES);
return lhs == rhs;
}
// PartialExit pubdata
struct PartialExit {
//uint32 accountId; -- present in pubdata, ignored at serialization
uint16 tokenId;
uint128 amount;
//uint16 fee; -- present in pubdata, ignored at serialization
address owner;
}
function readPartialExitPubdata(bytes memory _data, uint _offset) internal pure
returns (PartialExit memory parsed)
{
// NOTE: there is no check that variable sizes are same as constants (i.e. TOKEN_BYTES), fix if possible.
uint offset = _offset + ACCOUNT_ID_BYTES; // accountId (ignored)
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.tokenId) = Bytes.readUInt16(_data, offset); // tokenId
(offset, parsed.amount) = Bytes.readUInt128(_data, offset); // amount
}
function writePartialExitPubdata(PartialExit memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.owner, // owner
op.tokenId, // tokenId
op.amount // amount
);
}
// ChangePubKey
struct ChangePubKey {
uint32 accountId;
bytes20 pubKeyHash;
address owner;
uint32 nonce;
}
function readChangePubKeyPubdata(bytes memory _data, uint _offset) internal pure
returns (ChangePubKey memory parsed)
{
uint offset = _offset;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.pubKeyHash) = Bytes.readBytes20(_data, offset); // pubKeyHash
(offset, parsed.owner) = Bytes.readAddress(_data, offset); // owner
(offset, parsed.nonce) = Bytes.readUInt32(_data, offset); // nonce
}
// Withdrawal data process
function readWithdrawalData(bytes memory _data, uint _offset) internal pure
returns (bool _addToPendingWithdrawalsQueue, address _to, uint16 _tokenId, uint128 _amount)
{
uint offset = _offset;
(offset, _addToPendingWithdrawalsQueue) = Bytes.readBool(_data, offset);
(offset, _to) = Bytes.readAddress(_data, offset);
(offset, _tokenId) = Bytes.readUInt16(_data, offset);
(offset, _amount) = Bytes.readUInt128(_data, offset);
}
// CreatePair pubdata
struct CreatePair {
uint32 accountId;
uint16 tokenA;
uint16 tokenB;
uint16 tokenPair;
address pair;
}
uint public constant PACKED_CREATE_PAIR_PUBDATA_BYTES =
ACCOUNT_ID_BYTES + TOKEN_BYTES + TOKEN_BYTES + TOKEN_BYTES + ADDRESS_BYTES;
function readCreatePairPubdata(bytes memory _data) internal pure
returns (CreatePair memory parsed)
{
uint offset = 0;
(offset, parsed.accountId) = Bytes.readUInt32(_data, offset); // accountId
(offset, parsed.tokenA) = Bytes.readUInt16(_data, offset); // tokenAId
(offset, parsed.tokenB) = Bytes.readUInt16(_data, offset); // tokenBId
(offset, parsed.tokenPair) = Bytes.readUInt16(_data, offset); // pairId
(offset, parsed.pair) = Bytes.readAddress(_data, offset); // pairId
require(offset == PACKED_CREATE_PAIR_PUBDATA_BYTES, "rcp10"); // reading invalid create pair pubdata size
}
function writeCreatePairPubdata(CreatePair memory op) internal pure returns (bytes memory buf) {
buf = abi.encodePacked(
bytes4(0), // accountId (ignored) (update when ACCOUNT_ID_BYTES is changed)
op.tokenA, // tokenAId
op.tokenB, // tokenBId
op.tokenPair, // pairId
op.pair // pair account
);
}
/// @notice Check that create pair pubdata from request and block matches
function createPairPubdataMatch(bytes memory _lhs, bytes memory _rhs) internal pure returns (bool) {
// We must ignore `accountId` because it is present in block pubdata but not in priority queue
bytes memory lhs_trimmed = Bytes.slice(_lhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
bytes memory rhs_trimmed = Bytes.slice(_rhs, ACCOUNT_ID_BYTES, PACKED_CREATE_PAIR_PUBDATA_BYTES - ACCOUNT_ID_BYTES);
return keccak256(lhs_trimmed) == keccak256(rhs_trimmed);
}
}
pragma solidity ^0.5.0;
/// @title Interface of the upgradeable master contract (defines notice period duration and allows finish upgrade during preparation of it)
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface UpgradeableMaster {
/// @notice Notice period before activation preparation status of upgrade mode
function getNoticePeriod() external returns (uint);
/// @notice Notifies contract that notice period started
function upgradeNoticePeriodStarted() external;
/// @notice Notifies contract that upgrade preparation status is activated
function upgradePreparationStarted() external;
/// @notice Notifies contract that upgrade canceled
function upgradeCanceled() external;
/// @notice Notifies contract that upgrade finishes
function upgradeFinishes() external;
/// @notice Checks that contract is ready for upgrade
/// @return bool flag indicating that contract is ready for upgrade
function isReadyForUpgrade() external returns (bool);
}
pragma solidity =0.5.16;
import './interfaces/IUniswapV2Factory.sol';
import './UniswapV2Pair.sol';
contract UniswapV2Factory is IUniswapV2Factory {
mapping(address => mapping(address => address)) public getPair;
address[] public allPairs;
address public zkSyncAddress;
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
constructor() public {
}
function initialize(bytes calldata data) external {
}
function setZkSyncAddress(address _zksyncAddress) external {
require(zkSyncAddress == address(0), "szsa1");
zkSyncAddress = _zksyncAddress;
}
/// @notice PairManager contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function allPairsLength() external view returns (uint) {
return allPairs.length;
}
function createPair(address tokenA, address tokenB) external returns (address pair) {
require(msg.sender == zkSyncAddress, 'fcp1');
require(tokenA != tokenB, 'UniswapV2: IDENTICAL_ADDRESSES');
(address token0, address token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA);
//require(token0 != address(0), 'UniswapV2: ZERO_ADDRESS');
require(getPair[token0][token1] == address(0), 'UniswapV2: PAIR_EXISTS'); // single check is sufficient
bytes memory bytecode = type(UniswapV2Pair).creationCode;
bytes32 salt = keccak256(abi.encodePacked(token0, token1));
assembly {
pair := create2(0, add(bytecode, 32), mload(bytecode), salt)
}
require(zkSyncAddress != address(0), 'wzk');
IUniswapV2Pair(pair).initialize(token0, token1);
getPair[token0][token1] = pair;
getPair[token1][token0] = pair; // populate mapping in the reverse direction
allPairs.push(pair);
emit PairCreated(token0, token1, pair, allPairs.length);
}
function mint(address pair, address to, uint amount) external {
require(msg.sender == zkSyncAddress, 'fmt1');
IUniswapV2Pair(pair).mint(to, amount);
}
function burn(address pair, address to, uint amount) external {
require(msg.sender == zkSyncAddress, 'fbr1');
IUniswapV2Pair(pair).burn(to, amount);
}
}
pragma solidity ^0.5.0;
contract PairTokenManager {
/// @notice Max amount of pair tokens registered in the network.
uint16 constant MAX_AMOUNT_OF_PAIR_TOKENS = 49152;
uint16 constant PAIR_TOKEN_START_ID = 16384;
/// @notice Total number of pair tokens registered in the network
uint16 public totalPairTokens;
/// @notice List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @notice List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @notice Token added to Franklin net
event NewToken(
address indexed token,
uint16 indexed tokenId
);
function addPairToken(address _token) internal {
require(tokenIds[_token] == 0, "pan1"); // token exists
require(totalPairTokens < MAX_AMOUNT_OF_PAIR_TOKENS, "pan2"); // no free identifiers for tokens
uint16 newPairTokenId = PAIR_TOKEN_START_ID + totalPairTokens;
totalPairTokens++;
tokenAddresses[newPairTokenId] = _token;
tokenIds[_token] = newPairTokenId;
emit NewToken(_token, newPairTokenId);
}
/// @notice Validate pair token address
/// @param _tokenAddr Token address
/// @return tokens id
function validatePairTokenAddress(address _tokenAddr) public view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "pms3");
require(tokenId <= (PAIR_TOKEN_START_ID -1 + MAX_AMOUNT_OF_PAIR_TOKENS), "pms4");
return tokenId;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./Config.sol";
/// @title Governance Contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
contract Governance is Config {
/// @notice Token added to Franklin net
event NewToken(
address indexed token,
uint16 indexed tokenId
);
/// @notice Governor changed
event NewGovernor(
address newGovernor
);
/// @notice tokenLister changed
event NewTokenLister(
address newTokenLister
);
/// @notice Validator's status changed
event ValidatorStatusUpdate(
address indexed validatorAddress,
bool isActive
);
/// @notice Address which will exercise governance over the network i.e. add tokens, change validator set, conduct upgrades
address public networkGovernor;
/// @notice Total number of ERC20 fee tokens registered in the network (excluding ETH, which is hardcoded as tokenId = 0)
uint16 public totalFeeTokens;
/// @notice Total number of ERC20 user tokens registered in the network
uint16 public totalUserTokens;
/// @notice List of registered tokens by tokenId
mapping(uint16 => address) public tokenAddresses;
/// @notice List of registered tokens by address
mapping(address => uint16) public tokenIds;
/// @notice List of permitted validators
mapping(address => bool) public validators;
address public tokenLister;
constructor() public {
networkGovernor = msg.sender;
}
/// @notice Governance contract initialization. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param initializationParameters Encoded representation of initialization parameters:
/// _networkGovernor The address of network governor
function initialize(bytes calldata initializationParameters) external {
require(networkGovernor == address(0), "init0");
(address _networkGovernor, address _tokenLister) = abi.decode(initializationParameters, (address, address));
networkGovernor = _networkGovernor;
tokenLister = _tokenLister;
}
/// @notice Governance contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
/// @notice Change current governor
/// @param _newGovernor Address of the new governor
function changeGovernor(address _newGovernor) external {
requireGovernor(msg.sender);
require(_newGovernor != address(0), "zero address is passed as _newGovernor");
if (networkGovernor != _newGovernor) {
networkGovernor = _newGovernor;
emit NewGovernor(_newGovernor);
}
}
/// @notice Change current governor
/// @param _newTokenLister Address of the new governor
function changeTokenLister(address _newTokenLister) external {
requireGovernor(msg.sender);
require(_newTokenLister != address(0), "zero address is passed as _newTokenLister");
if (tokenLister != _newTokenLister) {
tokenLister = _newTokenLister;
emit NewTokenLister(_newTokenLister);
}
}
/// @notice Add fee token to the list of networks tokens
/// @param _token Token address
function addFeeToken(address _token) external {
requireGovernor(msg.sender);
require(tokenIds[_token] == 0, "gan11"); // token exists
require(totalFeeTokens < MAX_AMOUNT_OF_REGISTERED_FEE_TOKENS, "fee12"); // no free identifiers for tokens
require(
_token != address(0), "address cannot be zero"
);
totalFeeTokens++;
uint16 newTokenId = totalFeeTokens; // it is not `totalTokens - 1` because tokenId = 0 is reserved for eth
tokenAddresses[newTokenId] = _token;
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @notice Add token to the list of networks tokens
/// @param _token Token address
function addToken(address _token) external {
requireTokenLister(msg.sender);
require(tokenIds[_token] == 0, "gan11"); // token exists
require(totalUserTokens < MAX_AMOUNT_OF_REGISTERED_USER_TOKENS, "gan12"); // no free identifiers for tokens
require(
_token != address(0), "address cannot be zero"
);
uint16 newTokenId = USER_TOKENS_START_ID + totalUserTokens;
totalUserTokens++;
tokenAddresses[newTokenId] = _token;
tokenIds[_token] = newTokenId;
emit NewToken(_token, newTokenId);
}
/// @notice Change validator status (active or not active)
/// @param _validator Validator address
/// @param _active Active flag
function setValidator(address _validator, bool _active) external {
requireGovernor(msg.sender);
if (validators[_validator] != _active) {
validators[_validator] = _active;
emit ValidatorStatusUpdate(_validator, _active);
}
}
/// @notice Check if specified address is is governor
/// @param _address Address to check
function requireGovernor(address _address) public view {
require(_address == networkGovernor, "grr11"); // only by governor
}
/// @notice Check if specified address can list token
/// @param _address Address to check
function requireTokenLister(address _address) public view {
require(_address == networkGovernor || _address == tokenLister, "grr11"); // token lister or governor
}
/// @notice Checks if validator is active
/// @param _address Validator address
function requireActiveValidator(address _address) external view {
require(validators[_address], "grr21"); // validator is not active
}
/// @notice Validate token id (must be less than or equal to total tokens amount)
/// @param _tokenId Token id
/// @return bool flag that indicates if token id is less than or equal to total tokens amount
function isValidTokenId(uint16 _tokenId) external view returns (bool) {
return (_tokenId <= totalFeeTokens) || (_tokenId >= USER_TOKENS_START_ID && _tokenId < (USER_TOKENS_START_ID + totalUserTokens ));
}
/// @notice Validate token address
/// @param _tokenAddr Token address
/// @return tokens id
function validateTokenAddress(address _tokenAddr) external view returns (uint16) {
uint16 tokenId = tokenIds[_tokenAddr];
require(tokenId != 0, "gvs11"); // 0 is not a valid token
require(tokenId <= MAX_AMOUNT_OF_REGISTERED_TOKENS, "gvs12");
return tokenId;
}
function getTokenAddress(uint16 _tokenId) external view returns (address) {
address tokenAddr = tokenAddresses[_tokenId];
return tokenAddr;
}
}
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./KeysWithPlonkAggVerifier.sol";
// Hardcoded constants to avoid accessing store
contract Verifier is KeysWithPlonkAggVerifier {
bool constant DUMMY_VERIFIER = false;
function initialize(bytes calldata) external {
}
/// @notice Verifier contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function isBlockSizeSupported(uint32 _size) public pure returns (bool) {
if (DUMMY_VERIFIER) {
return true;
} else {
return isBlockSizeSupportedInternal(_size);
}
}
function verifyMultiblockProof(
uint256[] calldata _recursiveInput,
uint256[] calldata _proof,
uint32[] calldata _block_sizes,
uint256[] calldata _individual_vks_inputs,
uint256[] calldata _subproofs_limbs
) external view returns (bool) {
if (DUMMY_VERIFIER) {
uint oldGasValue = gasleft();
uint tmp;
while (gasleft() + 500000 > oldGasValue) {
tmp += 1;
}
return true;
}
uint8[] memory vkIndexes = new uint8[](_block_sizes.length);
for (uint32 i = 0; i < _block_sizes.length; i++) {
vkIndexes[i] = blockSizeToVkIndex(_block_sizes[i]);
}
VerificationKey memory vk = getVkAggregated(uint32(_block_sizes.length));
return verify_serialized_proof_with_recursion(_recursiveInput, _proof, VK_TREE_ROOT, VK_MAX_INDEX, vkIndexes, _individual_vks_inputs, _subproofs_limbs, vk);
}
}
pragma solidity ^0.5.0;
pragma experimental ABIEncoderV2;
import "./KeysWithPlonkSingleVerifier.sol";
// Hardcoded constants to avoid accessing store
contract VerifierExit is KeysWithPlonkSingleVerifier {
function initialize(bytes calldata) external {
}
/// @notice VerifierExit contract upgrade. Can be external because Proxy contract intercepts illegal calls of this function.
/// @param upgradeParameters Encoded representation of upgrade parameters
function upgrade(bytes calldata upgradeParameters) external {}
function verifyExitProof(
bytes32 _rootHash,
uint32 _accountId,
address _owner,
uint16 _tokenId,
uint128 _amount,
uint256[] calldata _proof
) external view returns (bool) {
bytes32 commitment = sha256(abi.encodePacked(_rootHash, _accountId, _owner, _tokenId, _amount));
uint256[] memory inputs = new uint256[](1);
uint256 mask = (~uint256(0)) >> 3;
inputs[0] = uint256(commitment) & mask;
Proof memory proof = deserialize_proof(inputs, _proof);
VerificationKey memory vk = getVkExit();
require(vk.num_inputs == inputs.length);
return verify(proof, vk);
}
function concatBytes(bytes memory param1, bytes memory param2) public pure returns (bytes memory) {
bytes memory merged = new bytes(param1.length + param2.length);
uint k = 0;
for (uint i = 0; i < param1.length; i++) {
merged[k] = param1[i];
k++;
}
for (uint i = 0; i < param2.length; i++) {
merged[k] = param2[i];
k++;
}
return merged;
}
function verifyLpExitProof(
bytes calldata _account_data,
bytes calldata _pair_data0,
bytes calldata _pair_data1,
uint256[] calldata _proof
) external view returns (bool) {
bytes memory _data1 = concatBytes(_account_data, _pair_data0);
bytes memory _data2 = concatBytes(_data1, _pair_data1);
bytes32 commitment = sha256(_data2);
uint256[] memory inputs = new uint256[](1);
uint256 mask = (~uint256(0)) >> 3;
inputs[0] = uint256(commitment) & mask;
Proof memory proof = deserialize_proof(inputs, _proof);
VerificationKey memory vk = getVkLpExit();
require(vk.num_inputs == inputs.length);
return verify(proof, vk);
}
}
pragma solidity ^0.5.0;
/// @title Interface of the upgradeable contract
/// @author Matter Labs
/// @author ZKSwap L2 Labs
interface Upgradeable {
/// @notice Upgrades target of upgradeable contract
/// @param newTarget New target
/// @param newTargetInitializationParameters New target initialization parameters
function upgradeTarget(address newTarget, bytes calldata newTargetInitializationParameters) external;
}
pragma solidity >=0.5.0;
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
}
pragma solidity =0.5.16;
import './interfaces/IUniswapV2Pair.sol';
import './UniswapV2ERC20.sol';
import './libraries/Math.sol';
import './libraries/UQ112x112.sol';
import './interfaces/IUNISWAPERC20.sol';
import './interfaces/IUniswapV2Factory.sol';
import './interfaces/IUniswapV2Callee.sol';
contract UniswapV2Pair is IUniswapV2Pair, UniswapV2ERC20 {
using UniswapSafeMath for uint;
using UQ112x112 for uint224;
address public factory;
address public token0;
address public token1;
uint private unlocked = 1;
modifier lock() {
require(unlocked == 1, 'UniswapV2: LOCKED');
unlocked = 0;
_;
unlocked = 1;
}
constructor() public {
factory = msg.sender;
}
// called once by the factory at time of deployment
function initialize(address _token0, address _token1) external {
require(msg.sender == factory, 'UniswapV2: FORBIDDEN'); // sufficient check
token0 = _token0;
token1 = _token1;
}
function mint(address to, uint amount) external lock {
require(msg.sender == factory, 'mt1');
_mint(to, amount);
}
function burn(address to, uint amount) external lock {
require(msg.sender == factory, 'br1');
_burn(to, amount);
}
}
pragma solidity >=0.5.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "./PlonkAggCore.sol";
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkAggVerifier is AggVerifierWithDeserialize {
uint256 constant VK_TREE_ROOT = 0x0a3cdc9655e61bf64758c1e8df745723e9b83addd4f0d0f2dd65dc762dc1e9e7;
uint8 constant VK_MAX_INDEX = 5;
function isBlockSizeSupportedInternal(uint32 _size) internal pure returns (bool) {
if (_size == uint32(6)) { return true; }
else if (_size == uint32(12)) { return true; }
else if (_size == uint32(48)) { return true; }
else if (_size == uint32(96)) { return true; }
else if (_size == uint32(204)) { return true; }
else if (_size == uint32(420)) { return true; }
else { return false; }
}
function blockSizeToVkIndex(uint32 _chunks) internal pure returns (uint8) {
if (_chunks == uint32(6)) { return 0; }
else if (_chunks == uint32(12)) { return 1; }
else if (_chunks == uint32(48)) { return 2; }
else if (_chunks == uint32(96)) { return 3; }
else if (_chunks == uint32(204)) { return 4; }
else if (_chunks == uint32(420)) { return 5; }
}
function getVkAggregated(uint32 _blocks) internal pure returns (VerificationKey memory vk) {
if (_blocks == uint32(1)) { return getVkAggregated1(); }
else if (_blocks == uint32(5)) { return getVkAggregated5(); }
}
function getVkAggregated1() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 4194304;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x18c95f1ae6514e11a1b30fd7923947c5ffcec5347f16e91b4dd654168326bede);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x19fbd6706b4cbde524865701eae0ae6a270608a09c3afdab7760b685c1c6c41b,
0x25082a191f0690c175cc9af1106c6c323b5b5de4e24dc23be1e965e1851bca48
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x16c02d9ca95023d1812a58d16407d1ea065073f02c916290e39242303a8a1d8e,
0x230338b422ce8533e27cd50086c28cb160cf05a7ae34ecd5899dbdf449dc7ce0
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x1db0d133243750e1ea692050bbf6068a49dc9f6bae1f11960b6ce9e10adae0f5,
0x12a453ed0121ae05de60848b4374d54ae4b7127cb307372e14e8daf5097c5123
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x1062ed5e86781fd34f78938e5950c2481a79f132085d2bc7566351ddff9fa3b7,
0x2fd7aac30f645293cc99883ab57d8c99a518d5b4ab40913808045e8653497346
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x062755048bb95739f845e8659795813127283bf799443d62fea600ae23e7f263,
0x2af86098beaa241281c78a454c5d1aa6e9eedc818c96cd1e6518e1ac2d26aa39
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x0994e25148bbd25be655034f81062d1ebf0a1c2b41e0971434beab1ae8101474,
0x27cc8cfb1fafd13068aeee0e08a272577d89f8aa0fb8507aabbc62f37587b98f
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x044edf69ce10cfb6206795f92c3be2b0d26ab9afd3977b789840ee58c7dbe927,
0x2a8aa20c106f8dc7e849bc9698064dcfa9ed0a4050d794a1db0f13b0ee3def37
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x136967f1a2696db05583a58dbf8971c5d9d1dc5f5c97e88f3b4822aa52fefa1c,
0x127b41299ea5c840c3b12dbe7b172380f432b7b63ce3b004750d6abb9e7b3b7a
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x02fd5638bf3cc2901395ad1124b951e474271770a337147a2167e9797ab9d951,
0x0fcb2e56b077c8461c36911c9252008286d782e96030769bf279024fc81d412a
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x1865c60ecad86f81c6c952445707203c9c7fdace3740232ceb704aefd5bd45b3,
0x2f35e29b39ec8bb054e2cff33c0299dd13f8c78ea24a07622128a7444aba3f26
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x2a86ec9c6c1f903650b5abbf0337be556b03f79aecc4d917e90c7db94518dde6,
0x15b1b6be641336eebd58e7991be2991debbbd780e70c32b49225aa98d10b7016
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x213e42fcec5297b8e01a602684fcd412208d15bdac6b6331a8819d478ba46899,
0x03223485f4e808a3b2496ae1a3c0dfbcbf4391cffc57ee01e8fca114636ead18
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x2e9b02f8cf605ad1a36e99e990a07d435de06716448ad53053c7a7a5341f71e1,
0x2d6fdf0bc8bd89112387b1894d6f24b45dcb122c09c84344b6fc77a619dd1d59
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkAggregated5() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 16777216;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x1951441010b2b95a6e47a6075066a50a036f5ba978c050f2821df86636c0facb);
vk.gate_setup_commitments[0] = PairingsBn254.new_g1(
0x023cfc69ef1b002da66120fce352ede75893edd8cd8196403a54e1eceb82cd43,
0x2baf3bd673e46be9df0d43ca30f834671543c22db422f450b2efd8c931e9b34e
);
vk.gate_setup_commitments[1] = PairingsBn254.new_g1(
0x23783fe0e5c3f83c02c864e25fe766afb727134c9a77ae6b9694efb7b46f31ab,
0x1903d01005e447d061c16323a1d604d8fbd4b5cc9b64945a71f1234d280c4d3a
);
vk.gate_setup_commitments[2] = PairingsBn254.new_g1(
0x2897df6c6fa993661b2b0b0cf52460278e33533de71b3c0f7ed7c1f20af238c6,
0x042344afee0aed5505e59bce4ebbe942a91268a8af6b77ea95f603b5b726e8cb
);
vk.gate_setup_commitments[3] = PairingsBn254.new_g1(
0x0fceed33e78426afc38d8a68c0d93413d2bbaa492b087125271d33d52bdb07b8,
0x0057e4f63be36edb56e91da931f3d0ba72d1862d4b7751c59b92b6ae9f1fcc11
);
vk.gate_setup_commitments[4] = PairingsBn254.new_g1(
0x14230a35f172cd77a2147cecc20b2a13148363cbab78709489a29d08001e26fb,
0x04f1040477d77896475080b5abb8091cda2cce4917ee0ba5dd62d0ab1be379b4
);
vk.gate_setup_commitments[5] = PairingsBn254.new_g1(
0x20d1a079ad80a8abb7fd8ba669dddbbe23231360a5f0ba679b6536b6bf980649,
0x120c5a845903bd6de4105eb8cef90e6dff2c3888ada16c90e1efb393778d6a4d
);
vk.gate_setup_commitments[6] = PairingsBn254.new_g1(
0x1af6b9e362e458a96b8bbbf8f8ce2bdbd650fb68478360c408a2acf1633c1ce1,
0x27033728b767b44c659e7896a6fcc956af97566a5a1135f87a2e510976a62d41
);
vk.gate_selector_commitments[0] = PairingsBn254.new_g1(
0x0dbfb3c5f5131eb6f01e12b1a6333b0ad22cc8292b666e46e9bd4d80802cccdf,
0x2d058711c42fd2fd2eef33fb327d111a27fe2063b46e1bb54b32d02e9676e546
);
vk.gate_selector_commitments[1] = PairingsBn254.new_g1(
0x0c8c7352a84dd3f32412b1a96acd94548a292411fd7479d8609ca9bd872f1e36,
0x0874203fd8012d6976698cc2df47bca14bc04879368ade6412a2109c1e71e5e8
);
vk.copy_permutation_commitments[0] = PairingsBn254.new_g1(
0x1b17bb7c319b1cf15461f4f0b69d98e15222320cb2d22f4e3a5f5e0e9e51f4bd,
0x0cf5bc338235ded905926006027aa2aab277bc32a098cd5b5353f5545cbd2825
);
vk.copy_permutation_commitments[1] = PairingsBn254.new_g1(
0x0794d3cfbc2fdd756b162571a40e40b8f31e705c77063f30a4e9155dbc00e0ef,
0x1f821232ab8826ea5bf53fe9866c74e88a218c8d163afcaa395eda4db57b7a23
);
vk.copy_permutation_commitments[2] = PairingsBn254.new_g1(
0x224d93783aa6856621a9bbec495f4830c94994e266b240db9d652dbb394a283b,
0x161bcec99f3bc449d655c0ca59874dafe1194138eec91af34392b09a83338ca1
);
vk.copy_permutation_commitments[3] = PairingsBn254.new_g1(
0x1fa27e2916b2c11d39c74c0e61063190da31c102d2b7da5c0a61ec8c5e82f132,
0x0a815ee76cd8aa600e6f66463b25a0ee57814bfdf06c65a91ddc70cede41caae
);
vk.copy_permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.copy_permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.copy_permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
pragma solidity >=0.5.0 <0.7.0;
import "./PlonkSingleCore.sol";
// Hardcoded constants to avoid accessing store
contract KeysWithPlonkSingleVerifier is SingleVerifierWithDeserialize {
function isBlockSizeSupportedInternal(uint32 _size) internal pure returns (bool) {
if (_size == uint32(6)) { return true; }
else if (_size == uint32(12)) { return true; }
else if (_size == uint32(48)) { return true; }
else if (_size == uint32(96)) { return true; }
else if (_size == uint32(204)) { return true; }
else if (_size == uint32(420)) { return true; }
else { return false; }
}
function getVkExit() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 262144;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0f60c8fe0414cb9379b2d39267945f6bd60d06a05216231b26a9fcf88ddbfebe);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x1abc710835cdc78389d61b670b0e8d26416a63c9bd3d6ed435103ebbb8a8665e,
0x138c6678230ed19f90b947d0a9027bd9fc458bbd1d2b8371fa72e28470a97b9c
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x28d81ac76e1ddf630b4bf8e4a789cf9c4470c5e5cc010a24849b20ab595b8b22,
0x251ca3cf0829b261d3be8d6cbd25aa97d9af716819c29f6319d806f075e79655
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x1504c8c227833a1152f3312d258412c334ac7ae213e21427ff63028729bc28fa,
0x0f0942f3fede795cbe624fb9ddf9be90ba546609383f2246c3c9b92af7aab5fd
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x1f14a5bb19ea2897ac6b9fbdbd2b4e371be09f8e90a47ae26602d399c9bcd311,
0x029c6ea094247da75d9a66cea627c3c77d48b898003125d4f8e785435dc2cf23
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x102cdd83e2d70638a70d700622b662607f8a2d92f5c36053a4ddb4b600d75bcf,
0x09ef3679579d761507ef69eaf49c978b271f0e4500468da1ebd7197f3ff5d6ac
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x2c2bd1d2fa3d4b3915d0fe465469e11ee563e79751da71c6082fcd0ca4e41cd5,
0x0304f16147a8af177dcc703370931d5161bda9dcf3e091787b9a54377ab54c32
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x14420680f992f4bc8d8012e2d8b14a774cf9114adf1e41b3c02c20cc1648398e,
0x237d3d5cdee5e3d7d58f4eb336ecd7aa5ec88d89205861b410420f6b9f6b26a1
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x221045ae5578ccb35e0a198d83c0fb191da8cdc98423fc46e580f1762682c73e,
0x15b7f3d74fcd258fdd2ae6001693a7c615e654d613a506d213aaf0ad314e338d
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x03e47981b459b3be258a6353593898babec571ccf3e0362d53a67f078f04830a,
0x0809556ab6eb28403bb5a749fcdbd8656940add7685ff5473dc3a9ad940034df
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x2c02322c53d7e6a6474b15c7db738419e3f4d1263e9f98ebb56c24906f555ef9,
0x2322c69f51366551665b584d797e0fdadb16fe31b1e7ae2f532847a75b3aeaab
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x2147e39b49c2bef4168884c0ac9e38bb4dc65b41ba21953f7ded2daab7fe1534,
0x071f3548c9ca2c6a8d10b11d553263ebe0afaf1f663b927ef970bd6c3974cb68
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
function getVkLpExit() internal pure returns(VerificationKey memory vk) {
vk.domain_size = 524288;
vk.num_inputs = 1;
vk.omega = PairingsBn254.new_fr(0x0cf1526aaafac6bacbb67d11a4077806b123f767e4b0883d14cc0193568fc082);
vk.selector_commitments[0] = PairingsBn254.new_g1(
0x067d967299b3d380f2e461409fbacb82d9af8c85b62de082a423f344fb0b9d38,
0x2440bd569ac24e9525b29e433334ee98d72cb8eb19af65250ee0099fb470d873
);
vk.selector_commitments[1] = PairingsBn254.new_g1(
0x086a9ed0f6175964593e516a8c1fc8bbd0a9c8afb724ebbce08a7772bd7b8837,
0x0aca3794dc6a2f0cab69dfed529d31deb7a5e9e6c339e3c07d8d88df0f7abd6b
);
vk.selector_commitments[2] = PairingsBn254.new_g1(
0x00b6bfec3aceb55618e6caf637c978c3fe2344568c64515022fcfa00e490eb97,
0x0f890fe6b9cb943fb4887df1529cdae99e2494eabf675f89905215eb51c29c6e
);
vk.selector_commitments[3] = PairingsBn254.new_g1(
0x0968470be841bcbfbcccc10dd0d8b63a871cdb3289c214fc59f38c88ab15146a,
0x1a9b4d034050fa0b119bb64ba0e967fd09f224c6fd9cd8b54cd6f081085dfb98
);
vk.selector_commitments[4] = PairingsBn254.new_g1(
0x080dbe10de0cacf12db303a86049c7a4d42f068a9def099e0cb874008f210b1b,
0x02f17638d3410ab573e33a4e6c6cf0c918bea2aa4f1025ca5ee13d7a950c4058
);
vk.selector_commitments[5] = PairingsBn254.new_g1(
0x267043dbe00520bd8bbf55a96b51fde6b3b64219eca9e2fd8309693db0cf0392,
0x08dbbfa17faad841228af22a03fab7ec20f765036a2acae62f543f61e55b6e8c
);
// we only have access to value of the d(x) witness polynomial on the next
// trace step, so we only need one element here and deal with it in other places
// by having this in mind
vk.next_step_selector_commitments[0] = PairingsBn254.new_g1(
0x215141775449677e3dbe25ff6c5e5d99336a29d952a61d5ec87618346e78df30,
0x29502caeb6afaf2acd13766d52fac2907efb7d11c66cd8beb93c8321d380b215
);
vk.permutation_commitments[0] = PairingsBn254.new_g1(
0x150790105b9f5455ae6f91daa6b03c5793fb7bcfcd9d5d37d3b643b77535b10a,
0x2b644a9736282f80fae8d35f00cbddf2bba3560c54f3d036ec1c8014c147a506
);
vk.permutation_commitments[1] = PairingsBn254.new_g1(
0x1b898666ded092a449935de7d707ad8d65809c2baccdd7dd7cfdaf2fb27e1262,
0x2a24c241dcad93b7bdf1cce2427c9c54f731a7d50c27a825e2af3dabb66dc81f
);
vk.permutation_commitments[2] = PairingsBn254.new_g1(
0x049892634dbbfa0c364523827cd7e604b70a7e24a4cb111cb8fccb7c05b04d7f,
0x1e5d8d7c0bf92d822dcf339a52c326a35cadf010b888b8f26e155a68c7e23dc9
);
vk.permutation_commitments[3] = PairingsBn254.new_g1(
0x04f90846cb1598aa05164a78d171ea918154414652d07d3f5cab84a26e6aa158,
0x0975ba8858f136bb8b1b043daf8dfed33709f72ba37e01e5de62c81f3928a13c
);
vk.permutation_non_residues[0] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000005
);
vk.permutation_non_residues[1] = PairingsBn254.new_fr(
0x0000000000000000000000000000000000000000000000000000000000000007
);
vk.permutation_non_residues[2] = PairingsBn254.new_fr(
0x000000000000000000000000000000000000000000000000000000000000000a
);
vk.g2_x = PairingsBn254.new_g2(
[0x260e01b251f6f1c7e7ff4e580791dee8ea51d87a358e038b4efe30fac09383c1,
0x0118c4d5b837bcc2bc89b5b398b5974e9f5944073b32078b7e231fec938883b0],
[0x04fc6369f7110fe3d25156c1bb9a72859cf2a04641f99ba4ee413c80da6a5fe4,
0x22febda3c0c0632a56475b4214e5615e11e6dd3f96e6cea2854a87d4dacc5e55]
);
}
}
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 factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function initialize(address, address) external;
function mint(address to, uint amount) external;
function burn(address to, uint amount) external;
}
pragma solidity =0.5.16;
import './interfaces/IUniswapV2ERC20.sol';
import './libraries/UniswapSafeMath.sol';
contract UniswapV2ERC20 is IUniswapV2ERC20 {
using UniswapSafeMath for uint;
string public constant name = 'ZKSWAP V2';
string public constant symbol = 'ZKS-V2';
uint8 public constant decimals = 18;
uint public totalSupply;
mapping(address => uint) public balanceOf;
mapping(address => mapping(address => uint)) public allowance;
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
constructor() public {
uint chainId;
assembly {
chainId := chainid
}
}
function _mint(address to, uint value) internal {
totalSupply = totalSupply.add(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(address(0), to, value);
}
function _burn(address from, uint value) internal {
balanceOf[from] = balanceOf[from].sub(value);
totalSupply = totalSupply.sub(value);
emit Transfer(from, address(0), value);
}
function _approve(address owner, address spender, uint value) private {
allowance[owner][spender] = value;
emit Approval(owner, spender, value);
}
function _transfer(address from, address to, uint value) private {
balanceOf[from] = balanceOf[from].sub(value);
balanceOf[to] = balanceOf[to].add(value);
emit Transfer(from, to, value);
}
function approve(address spender, uint value) external returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
function transfer(address to, uint value) external returns (bool) {
_transfer(msg.sender, to, value);
return true;
}
function transferFrom(address from, address to, uint value) external returns (bool) {
if (allowance[from][msg.sender] != uint(-1)) {
allowance[from][msg.sender] = allowance[from][msg.sender].sub(value);
}
_transfer(from, to, value);
return true;
}
}
pragma solidity =0.5.16;
// a library for performing various math operations
library Math {
function min(uint x, uint y) internal pure returns (uint z) {
z = x < y ? x : y;
}
// 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;
}
}
}
pragma solidity =0.5.16;
// a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format))
// range: [0, 2**112 - 1]
// resolution: 1 / 2**112
library UQ112x112 {
uint224 constant Q112 = 2**112;
// encode a uint112 as a UQ112x112
function encode(uint112 y) internal pure returns (uint224 z) {
z = uint224(y) * Q112; // never overflows
}
// divide a UQ112x112 by a uint112, returning a UQ112x112
function uqdiv(uint224 x, uint112 y) internal pure returns (uint224 z) {
z = x / uint224(y);
}
}
pragma solidity >=0.5.0;
interface IUNISWAPERC20 {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
}
pragma solidity >=0.5.0;
interface IUniswapV2Callee {
function uniswapV2Call(address sender, uint amount0, uint amount1, bytes calldata data) external;
}
pragma solidity >=0.5.0 <0.7.0;
pragma experimental ABIEncoderV2;
import "./PlonkCoreLib.sol";
contract Plonk4AggVerifierWithAccessToDNext {
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant ZERO = 0;
uint256 constant ONE = 1;
uint256 constant TWO = 2;
uint256 constant THREE = 3;
uint256 constant FOUR = 4;
uint256 constant STATE_WIDTH = 4;
uint256 constant NUM_DIFFERENT_GATES = 2;
uint256 constant NUM_SETUP_POLYS_FOR_MAIN_GATE = 7;
uint256 constant NUM_SETUP_POLYS_RANGE_CHECK_GATE = 0;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1;
uint256 constant NUM_GATE_SELECTORS_OPENED_EXPLICITLY = 1;
uint256 constant RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK = 0x00ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint256 constant LIMB_WIDTH = 68;
struct VerificationKey {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[NUM_SETUP_POLYS_FOR_MAIN_GATE + NUM_SETUP_POLYS_RANGE_CHECK_GATE] gate_setup_commitments;
PairingsBn254.G1Point[NUM_DIFFERENT_GATES] gate_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH] copy_permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH-1] copy_permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct Proof {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH] wire_commitments;
PairingsBn254.G1Point copy_permutation_grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega;
PairingsBn254.Fr[NUM_GATE_SELECTORS_OPENED_EXPLICITLY] gate_selector_values_at_z;
PairingsBn254.Fr copy_grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH-1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierState {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function evaluate_vanishing(
uint256 domain_size,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory inputs_term = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
inputs_term.add_assign(tmp);
}
inputs_term.mul_assign(proof.gate_selector_values_at_z[0]);
rhs.add_assign(inputs_term);
// now we need 5th power
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.copy_grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function add_contribution_from_range_constraint_gates(
PartialVerifierState memory state,
Proof memory proof,
PairingsBn254.Fr memory current_alpha
) internal pure returns (PairingsBn254.Fr memory res) {
// now add contribution from range constraint gate
// we multiply selector commitment by all the factors (alpha*(c - 4d)(c - 4d - 1)(..-2)(..-3) + alpha^2 * (4b - c)()()() + {} + {})
PairingsBn254.Fr memory one_fr = PairingsBn254.new_fr(ONE);
PairingsBn254.Fr memory two_fr = PairingsBn254.new_fr(TWO);
PairingsBn254.Fr memory three_fr = PairingsBn254.new_fr(THREE);
PairingsBn254.Fr memory four_fr = PairingsBn254.new_fr(FOUR);
res = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t0 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t1 = PairingsBn254.new_fr(0);
PairingsBn254.Fr memory t2 = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < 3; i++) {
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[3 - i]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z[2 - i]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
}
// now also d_next - 4a
current_alpha.mul_assign(state.alpha);
// high - 4*low
// this is 4*low
t0 = PairingsBn254.copy(proof.wire_values_at_z[0]);
t0.mul_assign(four_fr);
// high
t1 = PairingsBn254.copy(proof.wire_values_at_z_omega[0]);
t1.sub_assign(t0);
// t0 is now t1 - {0,1,2,3}
// first unroll manually for -0;
t2 = PairingsBn254.copy(t1);
// -1
t0 = PairingsBn254.copy(t1);
t0.sub_assign(one_fr);
t2.mul_assign(t0);
// -2
t0 = PairingsBn254.copy(t1);
t0.sub_assign(two_fr);
t2.mul_assign(t0);
// -3
t0 = PairingsBn254.copy(t1);
t0.sub_assign(three_fr);
t2.mul_assign(t0);
t2.mul_assign(current_alpha);
res.add_assign(t2);
return res;
}
function reconstruct_linearization_commitment(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^{6} * (selector(x) - selector(z))
// + v^{7..9} * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^10 (z(x) - z(z*omega)) <- we need this power
// + v^11 * (d(x) - d(z*omega))
// ]
//
// we reconstruct linearization polynomial virtual selector
// for that purpose we first linearize over main gate (over all it's selectors)
// and multiply them by value(!) of the corresponding main gate selector
res = PairingsBn254.copy_g1(vk.gate_setup_commitments[STATE_WIDTH + 1]); // index of q_const(x)
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH; i++) {
tmp_g1 = vk.gate_setup_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.gate_setup_commitments[STATE_WIDTH+2].point_mul(proof.wire_values_at_z_omega[0]); // index of q_d_next(x)
res.point_add_assign(tmp_g1);
// multiply by main gate selector(z)
res.point_mul_assign(proof.gate_selector_values_at_z[0]); // these is only one explicitly opened selector
PairingsBn254.Fr memory current_alpha = PairingsBn254.new_fr(ONE);
// calculate scalar contribution from the range check gate
tmp_fr = add_contribution_from_range_constraint_gates(state, proof, current_alpha);
tmp_g1 = vk.gate_selector_commitments[1].point_mul(tmp_fr); // selector commitment for range constraint gate * scalar
res.point_add_assign(tmp_g1);
// proceed as normal to copy permutation
current_alpha.mul_assign(state.alpha); // alpha^5
PairingsBn254.Fr memory alpha_for_grand_product = PairingsBn254.copy(current_alpha);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.copy_permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.copy_permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i+1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(alpha_for_grand_product);
// alpha^n & L_{0}(z), and we bump current_alpha
current_alpha.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(current_alpha);
grand_product_part_at_z.add_assign(tmp_fr);
// prefactor for grand_product(x) is complete
// add to the linearization a part from the term
// - (a(z) + beta*perm_a + gamma)*()*()*z(z*omega) * beta * perm_d(X)
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.copy_grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(alpha_for_grand_product); // we multiply by the power of alpha from the argument
// actually multiply prefactors by z(x) and perm_d(x) and combine them
tmp_g1 = proof.copy_permutation_grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.copy_permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
// multiply them by v immedately as linearization has a factor of v^1
res.point_mul_assign(state.v);
// res now contains contribution from the gates linearization and
// copy permutation part
// now we need to add a part that is the rest
// for z(x*omega):
// - (a(z) + beta*perm_a + gamma)*()*()*(d(z) + gamma) * z(x*omega)
}
function aggregate_commitments(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point[2] memory res) {
PairingsBn254.G1Point memory d = reconstruct_linearization_commitment(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint i = 0; i < NUM_GATE_SELECTORS_OPENED_EXPLICITLY; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.gate_selector_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint i = 0; i < vk.copy_permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.copy_permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
// now do prefactor for grand_product(x*omega)
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
commitment_aggregation.point_add_assign(proof.copy_permutation_grand_product_commitment.point_mul(tmp_fr));
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint i = 0; i < proof.gate_selector_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.gate_selector_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.copy_grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
res[0] = pair_with_generator;
res[1] = pair_with_x;
return res;
}
function verify_initial(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs == 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.copy_permutation_grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
state.cached_lagrange_evals = new PairingsBn254.Fr[](1);
state.cached_lagrange_evals[0] = evaluate_lagrange_poly_out_of_domain(
0,
vk.domain_size,
vk.omega, state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
transcript.update_with_fr(proof.gate_selector_values_at_z[0]);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.copy_grand_product_at_z_omega);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function aggregate_for_verification(Proof memory proof, VerificationKey memory vk) internal view returns (bool valid, PairingsBn254.G1Point[2] memory part) {
PartialVerifierState memory state;
valid = verify_initial(state, proof, vk);
if (valid == false) {
return (valid, part);
}
part = aggregate_commitments(state, proof, vk);
(valid, part);
}
function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) {
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
valid = PairingsBn254.pairingProd2(recursive_proof_part[0], PairingsBn254.P2(), recursive_proof_part[1], vk.g2_x);
return valid;
}
function verify_recursive(
Proof memory proof,
VerificationKey memory vk,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[] memory subproofs_limbs
) internal view returns (bool) {
(uint256 recursive_input, PairingsBn254.G1Point[2] memory aggregated_g1s) = reconstruct_recursive_public_input(
recursive_vks_root, max_valid_index, recursive_vks_indexes,
individual_vks_inputs, subproofs_limbs
);
assert(recursive_input == proof.input_values[0]);
(bool valid, PairingsBn254.G1Point[2] memory recursive_proof_part) = aggregate_for_verification(proof, vk);
if (valid == false) {
return false;
}
// aggregated_g1s = inner
// recursive_proof_part = outer
PairingsBn254.G1Point[2] memory combined = combine_inner_and_outer(aggregated_g1s, recursive_proof_part);
valid = PairingsBn254.pairingProd2(combined[0], PairingsBn254.P2(), combined[1], vk.g2_x);
return valid;
}
function combine_inner_and_outer(PairingsBn254.G1Point[2] memory inner, PairingsBn254.G1Point[2] memory outer)
internal
view
returns (PairingsBn254.G1Point[2] memory result)
{
// reuse the transcript primitive
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
transcript.update_with_g1(inner[0]);
transcript.update_with_g1(inner[1]);
transcript.update_with_g1(outer[0]);
transcript.update_with_g1(outer[1]);
PairingsBn254.Fr memory challenge = transcript.get_challenge();
// 1 * inner + challenge * outer
result[0] = PairingsBn254.copy_g1(inner[0]);
result[1] = PairingsBn254.copy_g1(inner[1]);
PairingsBn254.G1Point memory tmp = outer[0].point_mul(challenge);
result[0].point_add_assign(tmp);
tmp = outer[1].point_mul(challenge);
result[1].point_add_assign(tmp);
return result;
}
function reconstruct_recursive_public_input(
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[] memory subproofs_aggregated
) internal pure returns (uint256 recursive_input, PairingsBn254.G1Point[2] memory reconstructed_g1s) {
assert(recursive_vks_indexes.length == individual_vks_inputs.length);
bytes memory concatenated = abi.encodePacked(recursive_vks_root);
uint8 index;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
index = recursive_vks_indexes[i];
assert(index <= max_valid_index);
concatenated = abi.encodePacked(concatenated, index);
}
uint256 input;
for (uint256 i = 0; i < recursive_vks_indexes.length; i++) {
input = individual_vks_inputs[i];
assert(input < r_mod);
concatenated = abi.encodePacked(concatenated, input);
}
concatenated = abi.encodePacked(concatenated, subproofs_aggregated);
bytes32 commitment = sha256(concatenated);
recursive_input = uint256(commitment) & RECURSIVE_CIRCUIT_INPUT_COMMITMENT_MASK;
reconstructed_g1s[0] = PairingsBn254.new_g1_checked(
subproofs_aggregated[0] + (subproofs_aggregated[1] << LIMB_WIDTH) + (subproofs_aggregated[2] << 2*LIMB_WIDTH) + (subproofs_aggregated[3] << 3*LIMB_WIDTH),
subproofs_aggregated[4] + (subproofs_aggregated[5] << LIMB_WIDTH) + (subproofs_aggregated[6] << 2*LIMB_WIDTH) + (subproofs_aggregated[7] << 3*LIMB_WIDTH)
);
reconstructed_g1s[1] = PairingsBn254.new_g1_checked(
subproofs_aggregated[8] + (subproofs_aggregated[9] << LIMB_WIDTH) + (subproofs_aggregated[10] << 2*LIMB_WIDTH) + (subproofs_aggregated[11] << 3*LIMB_WIDTH),
subproofs_aggregated[12] + (subproofs_aggregated[13] << LIMB_WIDTH) + (subproofs_aggregated[14] << 2*LIMB_WIDTH) + (subproofs_aggregated[15] << 3*LIMB_WIDTH)
);
return (recursive_input, reconstructed_g1s);
}
}
contract AggVerifierWithDeserialize is Plonk4AggVerifierWithAccessToDNext {
uint256 constant SERIALIZED_PROOF_LENGTH = 34;
function deserialize_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof
) internal pure returns(Proof memory proof) {
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
}
proof.copy_permutation_grand_product_commitment = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
for (uint256 i = 0; i < proof.gate_selector_values_at_z.length; i++) {
proof.gate_selector_values_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
proof.copy_grand_product_at_z_omega = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
}
function verify_serialized_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid = verify(proof, vk);
return valid;
}
function verify_serialized_proof_with_recursion(
uint256[] memory public_inputs,
uint256[] memory serialized_proof,
uint256 recursive_vks_root,
uint8 max_valid_index,
uint8[] memory recursive_vks_indexes,
uint256[] memory individual_vks_inputs,
uint256[] memory subproofs_limbs,
VerificationKey memory vk
) public view returns (bool) {
require(vk.num_inputs == public_inputs.length);
Proof memory proof = deserialize_proof(public_inputs, serialized_proof);
bool valid = verify_recursive(proof, vk, recursive_vks_root, max_valid_index, recursive_vks_indexes, individual_vks_inputs, subproofs_limbs);
return valid;
}
}
pragma solidity >=0.5.0 <0.7.0;
import "./PlonkCoreLib.sol";
contract Plonk4SingleVerifierWithAccessToDNext {
using PairingsBn254 for PairingsBn254.G1Point;
using PairingsBn254 for PairingsBn254.G2Point;
using PairingsBn254 for PairingsBn254.Fr;
using TranscriptLibrary for TranscriptLibrary.Transcript;
uint256 constant STATE_WIDTH = 4;
uint256 constant ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP = 1;
struct VerificationKey {
uint256 domain_size;
uint256 num_inputs;
PairingsBn254.Fr omega;
PairingsBn254.G1Point[STATE_WIDTH+2] selector_commitments; // STATE_WIDTH for witness + multiplication + constant
PairingsBn254.G1Point[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] next_step_selector_commitments;
PairingsBn254.G1Point[STATE_WIDTH] permutation_commitments;
PairingsBn254.Fr[STATE_WIDTH-1] permutation_non_residues;
PairingsBn254.G2Point g2_x;
}
struct Proof {
uint256[] input_values;
PairingsBn254.G1Point[STATE_WIDTH] wire_commitments;
PairingsBn254.G1Point grand_product_commitment;
PairingsBn254.G1Point[STATE_WIDTH] quotient_poly_commitments;
PairingsBn254.Fr[STATE_WIDTH] wire_values_at_z;
PairingsBn254.Fr[ACCESSIBLE_STATE_POLYS_ON_NEXT_STEP] wire_values_at_z_omega;
PairingsBn254.Fr grand_product_at_z_omega;
PairingsBn254.Fr quotient_polynomial_at_z;
PairingsBn254.Fr linearization_polynomial_at_z;
PairingsBn254.Fr[STATE_WIDTH-1] permutation_polynomials_at_z;
PairingsBn254.G1Point opening_at_z_proof;
PairingsBn254.G1Point opening_at_z_omega_proof;
}
struct PartialVerifierState {
PairingsBn254.Fr alpha;
PairingsBn254.Fr beta;
PairingsBn254.Fr gamma;
PairingsBn254.Fr v;
PairingsBn254.Fr u;
PairingsBn254.Fr z;
PairingsBn254.Fr[] cached_lagrange_evals;
}
function evaluate_lagrange_poly_out_of_domain(
uint256 poly_num,
uint256 domain_size,
PairingsBn254.Fr memory omega,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
require(poly_num < domain_size);
PairingsBn254.Fr memory one = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory omega_power = omega.pow(poly_num);
res = at.pow(domain_size);
res.sub_assign(one);
require(res.value != 0); // Vanishing polynomial can not be zero at point `at`
res.mul_assign(omega_power);
PairingsBn254.Fr memory den = PairingsBn254.copy(at);
den.sub_assign(omega_power);
den.mul_assign(PairingsBn254.new_fr(domain_size));
den = den.inverse();
res.mul_assign(den);
}
function evaluate_vanishing(
uint256 domain_size,
PairingsBn254.Fr memory at
) internal view returns (PairingsBn254.Fr memory res) {
res = at.pow(domain_size);
res.sub_assign(PairingsBn254.new_fr(1));
}
function verify_at_z(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.Fr memory lhs = evaluate_vanishing(vk.domain_size, state.z);
require(lhs.value != 0); // we can not check a polynomial relationship if point `z` is in the domain
lhs.mul_assign(proof.quotient_polynomial_at_z);
PairingsBn254.Fr memory quotient_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory rhs = PairingsBn254.copy(proof.linearization_polynomial_at_z);
// public inputs
PairingsBn254.Fr memory tmp = PairingsBn254.new_fr(0);
for (uint256 i = 0; i < proof.input_values.length; i++) {
tmp.assign(state.cached_lagrange_evals[i]);
tmp.mul_assign(PairingsBn254.new_fr(proof.input_values[i]));
rhs.add_assign(tmp);
}
quotient_challenge.mul_assign(state.alpha);
PairingsBn254.Fr memory z_part = PairingsBn254.copy(proof.grand_product_at_z_omega);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp.assign(proof.permutation_polynomials_at_z[i]);
tmp.mul_assign(state.beta);
tmp.add_assign(state.gamma);
tmp.add_assign(proof.wire_values_at_z[i]);
z_part.mul_assign(tmp);
}
tmp.assign(state.gamma);
// we need a wire value of the last polynomial in enumeration
tmp.add_assign(proof.wire_values_at_z[STATE_WIDTH - 1]);
z_part.mul_assign(tmp);
z_part.mul_assign(quotient_challenge);
rhs.sub_assign(z_part);
quotient_challenge.mul_assign(state.alpha);
tmp.assign(state.cached_lagrange_evals[0]);
tmp.mul_assign(quotient_challenge);
rhs.sub_assign(tmp);
return lhs.value == rhs.value;
}
function reconstruct_d(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (PairingsBn254.G1Point memory res) {
// we compute what power of v is used as a delinearization factor in batch opening of
// commitments. Let's label W(x) = 1 / (x - z) *
// [
// t_0(x) + z^n * t_1(x) + z^2n * t_2(x) + z^3n * t_3(x) - t(z)
// + v (r(x) - r(z))
// + v^{2..5} * (witness(x) - witness(z))
// + v^(6..8) * (permutation(x) - permutation(z))
// ]
// W'(x) = 1 / (x - z*omega) *
// [
// + v^9 (z(x) - z(z*omega)) <- we need this power
// + v^10 * (d(x) - d(z*omega))
// ]
//
// we pay a little for a few arithmetic operations to not introduce another constant
uint256 power_for_z_omega_opening = 1 + 1 + STATE_WIDTH + STATE_WIDTH - 1;
res = PairingsBn254.copy_g1(vk.selector_commitments[STATE_WIDTH + 1]);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(0);
// addition gates
for (uint256 i = 0; i < STATE_WIDTH; i++) {
tmp_g1 = vk.selector_commitments[i].point_mul(proof.wire_values_at_z[i]);
res.point_add_assign(tmp_g1);
}
// multiplication gate
tmp_fr.assign(proof.wire_values_at_z[0]);
tmp_fr.mul_assign(proof.wire_values_at_z[1]);
tmp_g1 = vk.selector_commitments[STATE_WIDTH].point_mul(tmp_fr);
res.point_add_assign(tmp_g1);
// d_next
tmp_g1 = vk.next_step_selector_commitments[0].point_mul(proof.wire_values_at_z_omega[0]);
res.point_add_assign(tmp_g1);
// z * non_res * beta + gamma + a
PairingsBn254.Fr memory grand_product_part_at_z = PairingsBn254.copy(state.z);
grand_product_part_at_z.mul_assign(state.beta);
grand_product_part_at_z.add_assign(proof.wire_values_at_z[0]);
grand_product_part_at_z.add_assign(state.gamma);
for (uint256 i = 0; i < vk.permutation_non_residues.length; i++) {
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.permutation_non_residues[i]);
tmp_fr.mul_assign(state.beta);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i+1]);
grand_product_part_at_z.mul_assign(tmp_fr);
}
grand_product_part_at_z.mul_assign(state.alpha);
tmp_fr.assign(state.cached_lagrange_evals[0]);
tmp_fr.mul_assign(state.alpha);
tmp_fr.mul_assign(state.alpha);
grand_product_part_at_z.add_assign(tmp_fr);
PairingsBn254.Fr memory grand_product_part_at_z_omega = state.v.pow(power_for_z_omega_opening);
grand_product_part_at_z_omega.mul_assign(state.u);
PairingsBn254.Fr memory last_permutation_part_at_z = PairingsBn254.new_fr(1);
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
tmp_fr.assign(state.beta);
tmp_fr.mul_assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.add_assign(state.gamma);
tmp_fr.add_assign(proof.wire_values_at_z[i]);
last_permutation_part_at_z.mul_assign(tmp_fr);
}
last_permutation_part_at_z.mul_assign(state.beta);
last_permutation_part_at_z.mul_assign(proof.grand_product_at_z_omega);
last_permutation_part_at_z.mul_assign(state.alpha);
// add to the linearization
tmp_g1 = proof.grand_product_commitment.point_mul(grand_product_part_at_z);
tmp_g1.point_sub_assign(vk.permutation_commitments[STATE_WIDTH - 1].point_mul(last_permutation_part_at_z));
res.point_add_assign(tmp_g1);
res.point_mul_assign(state.v);
res.point_add_assign(proof.grand_product_commitment.point_mul(grand_product_part_at_z_omega));
}
function verify_commitments(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
PairingsBn254.G1Point memory d = reconstruct_d(state, proof, vk);
PairingsBn254.Fr memory z_in_domain_size = state.z.pow(vk.domain_size);
PairingsBn254.G1Point memory tmp_g1 = PairingsBn254.P1();
PairingsBn254.Fr memory aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.G1Point memory commitment_aggregation = PairingsBn254.copy_g1(proof.quotient_poly_commitments[0]);
PairingsBn254.Fr memory tmp_fr = PairingsBn254.new_fr(1);
for (uint i = 1; i < proof.quotient_poly_commitments.length; i++) {
tmp_fr.mul_assign(z_in_domain_size);
tmp_g1 = proof.quotient_poly_commitments[i].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
commitment_aggregation.point_add_assign(d);
for (uint i = 0; i < proof.wire_commitments.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = proof.wire_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
for (uint i = 0; i < vk.permutation_commitments.length - 1; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_g1 = vk.permutation_commitments[i].point_mul(aggregation_challenge);
commitment_aggregation.point_add_assign(tmp_g1);
}
aggregation_challenge.mul_assign(state.v);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
tmp_g1 = proof.wire_commitments[STATE_WIDTH - 1].point_mul(tmp_fr);
commitment_aggregation.point_add_assign(tmp_g1);
// collect opening values
aggregation_challenge = PairingsBn254.new_fr(1);
PairingsBn254.Fr memory aggregated_value = PairingsBn254.copy(proof.quotient_polynomial_at_z);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.linearization_polynomial_at_z);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
for (uint i = 0; i < proof.wire_values_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
for (uint i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.permutation_polynomials_at_z[i]);
tmp_fr.mul_assign(aggregation_challenge);
aggregated_value.add_assign(tmp_fr);
}
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.grand_product_at_z_omega);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
aggregation_challenge.mul_assign(state.v);
tmp_fr.assign(proof.wire_values_at_z_omega[0]);
tmp_fr.mul_assign(aggregation_challenge);
tmp_fr.mul_assign(state.u);
aggregated_value.add_assign(tmp_fr);
commitment_aggregation.point_sub_assign(PairingsBn254.P1().point_mul(aggregated_value));
PairingsBn254.G1Point memory pair_with_generator = commitment_aggregation;
pair_with_generator.point_add_assign(proof.opening_at_z_proof.point_mul(state.z));
tmp_fr.assign(state.z);
tmp_fr.mul_assign(vk.omega);
tmp_fr.mul_assign(state.u);
pair_with_generator.point_add_assign(proof.opening_at_z_omega_proof.point_mul(tmp_fr));
PairingsBn254.G1Point memory pair_with_x = proof.opening_at_z_omega_proof.point_mul(state.u);
pair_with_x.point_add_assign(proof.opening_at_z_proof);
pair_with_x.negate();
return PairingsBn254.pairingProd2(pair_with_generator, PairingsBn254.P2(), pair_with_x, vk.g2_x);
}
function verify_initial(
PartialVerifierState memory state,
Proof memory proof,
VerificationKey memory vk
) internal view returns (bool) {
require(proof.input_values.length == vk.num_inputs);
require(vk.num_inputs == 1);
TranscriptLibrary.Transcript memory transcript = TranscriptLibrary.new_transcript();
for (uint256 i = 0; i < vk.num_inputs; i++) {
transcript.update_with_u256(proof.input_values[i]);
}
for (uint256 i = 0; i < proof.wire_commitments.length; i++) {
transcript.update_with_g1(proof.wire_commitments[i]);
}
state.beta = transcript.get_challenge();
state.gamma = transcript.get_challenge();
transcript.update_with_g1(proof.grand_product_commitment);
state.alpha = transcript.get_challenge();
for (uint256 i = 0; i < proof.quotient_poly_commitments.length; i++) {
transcript.update_with_g1(proof.quotient_poly_commitments[i]);
}
state.z = transcript.get_challenge();
state.cached_lagrange_evals = new PairingsBn254.Fr[](1);
state.cached_lagrange_evals[0] = evaluate_lagrange_poly_out_of_domain(
0,
vk.domain_size,
vk.omega, state.z
);
bool valid = verify_at_z(state, proof, vk);
if (valid == false) {
return false;
}
for (uint256 i = 0; i < proof.wire_values_at_z.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z[i]);
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
transcript.update_with_fr(proof.wire_values_at_z_omega[i]);
}
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
transcript.update_with_fr(proof.permutation_polynomials_at_z[i]);
}
transcript.update_with_fr(proof.quotient_polynomial_at_z);
transcript.update_with_fr(proof.linearization_polynomial_at_z);
transcript.update_with_fr(proof.grand_product_at_z_omega);
state.v = transcript.get_challenge();
transcript.update_with_g1(proof.opening_at_z_proof);
transcript.update_with_g1(proof.opening_at_z_omega_proof);
state.u = transcript.get_challenge();
return true;
}
// This verifier is for a PLONK with a state width 4
// and main gate equation
// q_a(X) * a(X) +
// q_b(X) * b(X) +
// q_c(X) * c(X) +
// q_d(X) * d(X) +
// q_m(X) * a(X) * b(X) +
// q_constants(X)+
// q_d_next(X) * d(X*omega)
// where q_{}(X) are selectors a, b, c, d - state (witness) polynomials
// q_d_next(X) "peeks" into the next row of the trace, so it takes
// the same d(X) polynomial, but shifted
function verify(Proof memory proof, VerificationKey memory vk) internal view returns (bool) {
PartialVerifierState memory state;
bool valid = verify_initial(state, proof, vk);
if (valid == false) {
return false;
}
valid = verify_commitments(state, proof, vk);
return valid;
}
}
contract SingleVerifierWithDeserialize is Plonk4SingleVerifierWithAccessToDNext {
uint256 constant SERIALIZED_PROOF_LENGTH = 33;
function deserialize_proof(
uint256[] memory public_inputs,
uint256[] memory serialized_proof
) internal pure returns(Proof memory proof) {
require(serialized_proof.length == SERIALIZED_PROOF_LENGTH);
proof.input_values = new uint256[](public_inputs.length);
for (uint256 i = 0; i < public_inputs.length; i++) {
proof.input_values[i] = public_inputs[i];
}
uint256 j = 0;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
}
proof.grand_product_commitment = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.quotient_poly_commitments[i] = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
}
for (uint256 i = 0; i < STATE_WIDTH; i++) {
proof.wire_values_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
for (uint256 i = 0; i < proof.wire_values_at_z_omega.length; i++) {
proof.wire_values_at_z_omega[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
proof.grand_product_at_z_omega = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.quotient_polynomial_at_z = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
proof.linearization_polynomial_at_z = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
for (uint256 i = 0; i < proof.permutation_polynomials_at_z.length; i++) {
proof.permutation_polynomials_at_z[i] = PairingsBn254.new_fr(
serialized_proof[j]
);
j += 1;
}
proof.opening_at_z_proof = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
j += 2;
proof.opening_at_z_omega_proof = PairingsBn254.new_g1_checked(
serialized_proof[j],
serialized_proof[j+1]
);
}
}
pragma solidity >=0.5.0;
interface IUniswapV2ERC20 {
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);
}
pragma solidity =0.5.16;
// a library for performing overflow-safe math, courtesy of DappHub (https://github.com/dapphub/ds-math)
library UniswapSafeMath {
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, 'ds-math-add-overflow');
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, 'ds-math-sub-underflow');
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, 'ds-math-mul-overflow');
}
}
pragma solidity >=0.5.0 <0.7.0;
library PairingsBn254 {
uint256 constant q_mod = 21888242871839275222246405745257275088696311157297823662689037894645226208583;
uint256 constant r_mod = 21888242871839275222246405745257275088548364400416034343698204186575808495617;
uint256 constant bn254_b_coeff = 3;
struct G1Point {
uint256 X;
uint256 Y;
}
struct Fr {
uint256 value;
}
function new_fr(uint256 fr) internal pure returns (Fr memory) {
require(fr < r_mod);
return Fr({value: fr});
}
function copy(Fr memory self) internal pure returns (Fr memory n) {
n.value = self.value;
}
function assign(Fr memory self, Fr memory other) internal pure {
self.value = other.value;
}
function inverse(Fr memory fr) internal view returns (Fr memory) {
require(fr.value != 0);
return pow(fr, r_mod-2);
}
function add_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, other.value, r_mod);
}
function sub_assign(Fr memory self, Fr memory other) internal pure {
self.value = addmod(self.value, r_mod - other.value, r_mod);
}
function mul_assign(Fr memory self, Fr memory other) internal pure {
self.value = mulmod(self.value, other.value, r_mod);
}
function pow(Fr memory self, uint256 power) internal view returns (Fr memory) {
uint256[6] memory input = [32, 32, 32, self.value, power, r_mod];
uint256[1] memory result;
bool success;
assembly {
success := staticcall(gas(), 0x05, input, 0xc0, result, 0x20)
}
require(success);
return Fr({value: result[0]});
}
// Encoding of field elements is: X[0] * z + X[1]
struct G2Point {
uint[2] X;
uint[2] Y;
}
function P1() internal pure returns (G1Point memory) {
return G1Point(1, 2);
}
function new_g1(uint256 x, uint256 y) internal pure returns (G1Point memory) {
return G1Point(x, y);
}
function new_g1_checked(uint256 x, uint256 y) internal pure returns (G1Point memory) {
if (x == 0 && y == 0) {
// point of infinity is (0,0)
return G1Point(x, y);
}
// check encoding
require(x < q_mod);
require(y < q_mod);
// check on curve
uint256 lhs = mulmod(y, y, q_mod); // y^2
uint256 rhs = mulmod(x, x, q_mod); // x^2
rhs = mulmod(rhs, x, q_mod); // x^3
rhs = addmod(rhs, bn254_b_coeff, q_mod); // x^3 + b
require(lhs == rhs);
return G1Point(x, y);
}
function new_g2(uint256[2] memory x, uint256[2] memory y) internal pure returns (G2Point memory) {
return G2Point(x, y);
}
function copy_g1(G1Point memory self) internal pure returns (G1Point memory result) {
result.X = self.X;
result.Y = self.Y;
}
function P2() internal pure returns (G2Point memory) {
// for some reason ethereum expects to have c1*v + c0 form
return G2Point(
[0x198e9393920d483a7260bfb731fb5d25f1aa493335a9e71297e485b7aef312c2,
0x1800deef121f1e76426a00665e5c4479674322d4f75edadd46debd5cd992f6ed],
[0x090689d0585ff075ec9e99ad690c3395bc4b313370b38ef355acdadcd122975b,
0x12c85ea5db8c6deb4aab71808dcb408fe3d1e7690c43d37b4ce6cc0166fa7daa]
);
}
function negate(G1Point memory self) internal pure {
// The prime q in the base field F_q for G1
if (self.Y == 0) {
require(self.X == 0);
return;
}
self.Y = q_mod - self.Y;
}
function point_add(G1Point memory p1, G1Point memory p2)
internal view returns (G1Point memory r)
{
point_add_into_dest(p1, p2, r);
return r;
}
function point_add_assign(G1Point memory p1, G1Point memory p2)
internal view
{
point_add_into_dest(p1, p2, p1);
}
function point_add_into_dest(G1Point memory p1, G1Point memory p2, G1Point memory dest)
internal view
{
if (p2.X == 0 && p2.Y == 0) {
// we add zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we add into zero, and we add non-zero point
dest.X = p2.X;
dest.Y = p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_sub_assign(G1Point memory p1, G1Point memory p2)
internal view
{
point_sub_into_dest(p1, p2, p1);
}
function point_sub_into_dest(G1Point memory p1, G1Point memory p2, G1Point memory dest)
internal view
{
if (p2.X == 0 && p2.Y == 0) {
// we subtracted zero, nothing happens
dest.X = p1.X;
dest.Y = p1.Y;
return;
} else if (p1.X == 0 && p1.Y == 0) {
// we subtract from zero, and we subtract non-zero point
dest.X = p2.X;
dest.Y = q_mod - p2.Y;
return;
} else {
uint256[4] memory input;
input[0] = p1.X;
input[1] = p1.Y;
input[2] = p2.X;
input[3] = q_mod - p2.Y;
bool success = false;
assembly {
success := staticcall(gas(), 6, input, 0x80, dest, 0x40)
}
require(success);
}
}
function point_mul(G1Point memory p, Fr memory s)
internal view returns (G1Point memory r)
{
point_mul_into_dest(p, s, r);
return r;
}
function point_mul_assign(G1Point memory p, Fr memory s)
internal view
{
point_mul_into_dest(p, s, p);
}
function point_mul_into_dest(G1Point memory p, Fr memory s, G1Point memory dest)
internal view
{
uint[3] memory input;
input[0] = p.X;
input[1] = p.Y;
input[2] = s.value;
bool success;
assembly {
success := staticcall(gas(), 7, input, 0x60, dest, 0x40)
}
require(success);
}
function pairing(G1Point[] memory p1, G2Point[] memory p2)
internal view returns (bool)
{
require(p1.length == p2.length);
uint elements = p1.length;
uint inputSize = elements * 6;
uint[] memory input = new uint[](inputSize);
for (uint i = 0; i < elements; i++)
{
input[i * 6 + 0] = p1[i].X;
input[i * 6 + 1] = p1[i].Y;
input[i * 6 + 2] = p2[i].X[0];
input[i * 6 + 3] = p2[i].X[1];
input[i * 6 + 4] = p2[i].Y[0];
input[i * 6 + 5] = p2[i].Y[1];
}
uint[1] memory out;
bool success;
assembly {
success := staticcall(gas(), 8, add(input, 0x20), mul(inputSize, 0x20), out, 0x20)
}
require(success);
return out[0] != 0;
}
/// Convenience method for a pairing check for two pairs.
function pairingProd2(G1Point memory a1, G2Point memory a2, G1Point memory b1, G2Point memory b2)
internal view returns (bool)
{
G1Point[] memory p1 = new G1Point[](2);
G2Point[] memory p2 = new G2Point[](2);
p1[0] = a1;
p1[1] = b1;
p2[0] = a2;
p2[1] = b2;
return pairing(p1, p2);
}
}
library TranscriptLibrary {
// flip 0xe000000000000000000000000000000000000000000000000000000000000000;
uint256 constant FR_MASK = 0x1fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff;
uint32 constant DST_0 = 0;
uint32 constant DST_1 = 1;
uint32 constant DST_CHALLENGE = 2;
struct Transcript {
bytes32 state_0;
bytes32 state_1;
uint32 challenge_counter;
}
function new_transcript() internal pure returns (Transcript memory t) {
t.state_0 = bytes32(0);
t.state_1 = bytes32(0);
t.challenge_counter = 0;
}
function update_with_u256(Transcript memory self, uint256 value) internal pure {
bytes32 old_state_0 = self.state_0;
self.state_0 = keccak256(abi.encodePacked(DST_0, old_state_0, self.state_1, value));
self.state_1 = keccak256(abi.encodePacked(DST_1, old_state_0, self.state_1, value));
}
function update_with_fr(Transcript memory self, PairingsBn254.Fr memory value) internal pure {
update_with_u256(self, value.value);
}
function update_with_g1(Transcript memory self, PairingsBn254.G1Point memory p) internal pure {
update_with_u256(self, p.X);
update_with_u256(self, p.Y);
}
function get_challenge(Transcript memory self) internal pure returns(PairingsBn254.Fr memory challenge) {
bytes32 query = keccak256(abi.encodePacked(DST_CHALLENGE, self.state_0, self.state_1, self.challenge_counter));
self.challenge_counter += 1;
challenge = PairingsBn254.Fr({value: uint256(query) & FR_MASK});
}
}
|
Priority Queue request
|
function registerCreatePair(uint16 _tokenAID, address _tokenA, uint16 _tokenBID, address _tokenB, uint16 _tokenPair, address _pair) internal {
Operations.CreatePair memory op = Operations.CreatePair({
tokenA : _tokenAID,
tokenB : _tokenBID,
tokenPair : _tokenPair,
pair : _pair
});
bytes memory pubData = Operations.writeCreatePairPubdata(op);
bytes memory userData = abi.encodePacked(
);
addPriorityRequest(Operations.OpType.CreatePair, pubData, userData);
emit OnchainCreatePair(_tokenAID, _tokenBID, _tokenPair, _pair);
}
| 1,250,277 |
pragma solidity ^0.4.24;
interface ConflictResolutionInterface {
function minHouseStake(uint activeGames) external pure returns(uint);
function maxBalance() external pure returns(int);
function conflictEndFine() external pure returns(int);
function isValidBet(uint8 _gameType, uint _betNum, uint _betValue) external pure returns(bool);
function endGameConflict(
uint8 _gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
bytes32 _serverSeed,
bytes32 _userSeed
)
external
view
returns(int);
function serverForceGameEnd(
uint8 gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
uint _endInitiatedTime
)
external
view
returns(int);
function userForceGameEnd(
uint8 _gameType,
uint _betNum,
uint _betValue,
int _balance,
uint _stake,
uint _endInitiatedTime
)
external
view
returns(int);
}
library MathUtil {
/**
* @dev Returns the absolute value of _val.
* @param _val value
* @return The absolute value of _val.
*/
function abs(int _val) internal pure returns(uint) {
if (_val < 0) {
return uint(-_val);
} else {
return uint(_val);
}
}
/**
* @dev Calculate maximum.
*/
function max(uint _val1, uint _val2) internal pure returns(uint) {
return _val1 >= _val2 ? _val1 : _val2;
}
/**
* @dev Calculate minimum.
*/
function min(uint _val1, uint _val2) internal pure returns(uint) {
return _val1 <= _val2 ? _val1 : _val2;
}
}
contract Ownable {
address public owner;
address public pendingOwner;
event LogOwnerShipTransferred(address indexed previousOwner, address indexed newOwner);
event LogOwnerShipTransferInitiated(address indexed previousOwner, address indexed newOwner);
/**
* @dev Modifier, which throws if called by other account than owner.
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev Modifier throws if called by any account other than the pendingOwner.
*/
modifier onlyPendingOwner() {
require(msg.sender == pendingOwner);
_;
}
/**
* @dev Set contract creator as initial owner
*/
constructor() public {
owner = msg.sender;
pendingOwner = address(0);
}
/**
* @dev Allows the current owner to set the pendingOwner address.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
pendingOwner = _newOwner;
emit LogOwnerShipTransferInitiated(owner, _newOwner);
}
/**
* @dev PendingOwner can accept ownership.
*/
function claimOwnership() public onlyPendingOwner {
owner = pendingOwner;
pendingOwner = address(0);
emit LogOwnerShipTransferred(owner, pendingOwner);
}
}
contract Activatable is Ownable {
bool public activated = false;
/// @dev Event is fired if activated.
event LogActive();
/// @dev Modifier, which only allows function execution if activated.
modifier onlyActivated() {
require(activated);
_;
}
/// @dev Modifier, which only allows function execution if not activated.
modifier onlyNotActivated() {
require(!activated);
_;
}
/// @dev activate contract, can be only called once by the contract owner.
function activate() public onlyOwner onlyNotActivated {
activated = true;
emit LogActive();
}
}
contract ConflictResolutionManager is Ownable {
/// @dev Conflict resolution contract.
ConflictResolutionInterface public conflictRes;
/// @dev New Conflict resolution contract.
address public newConflictRes = 0;
/// @dev Time update of new conflict resolution contract was initiated.
uint public updateTime = 0;
/// @dev Min time before new conflict res contract can be activated after initiating update.
uint public constant MIN_TIMEOUT = 3 days;
/// @dev Min time before new conflict res contract can be activated after initiating update.
uint public constant MAX_TIMEOUT = 6 days;
/// @dev Update of conflict resolution contract was initiated.
event LogUpdatingConflictResolution(address newConflictResolutionAddress);
/// @dev New conflict resolution contract is active.
event LogUpdatedConflictResolution(address newConflictResolutionAddress);
/**
* @dev Constructor
* @param _conflictResAddress conflict resolution contract address.
*/
constructor(address _conflictResAddress) public {
conflictRes = ConflictResolutionInterface(_conflictResAddress);
}
/**
* @dev Initiate conflict resolution contract update.
* @param _newConflictResAddress New conflict resolution contract address.
*/
function updateConflictResolution(address _newConflictResAddress) public onlyOwner {
newConflictRes = _newConflictResAddress;
updateTime = block.timestamp;
emit LogUpdatingConflictResolution(_newConflictResAddress);
}
/**
* @dev Active new conflict resolution contract.
*/
function activateConflictResolution() public onlyOwner {
require(newConflictRes != 0);
require(updateTime != 0);
require(updateTime + MIN_TIMEOUT <= block.timestamp && block.timestamp <= updateTime + MAX_TIMEOUT);
conflictRes = ConflictResolutionInterface(newConflictRes);
newConflictRes = 0;
updateTime = 0;
emit LogUpdatedConflictResolution(newConflictRes);
}
}
contract Pausable is Activatable {
using SafeMath for uint;
/// @dev Is contract paused. Initial it is paused.
bool public paused = true;
/// @dev Time pause was called
uint public timePaused = block.timestamp;
/// @dev Modifier, which only allows function execution if not paused.
modifier onlyNotPaused() {
require(!paused, "paused");
_;
}
/// @dev Modifier, which only allows function execution if paused.
modifier onlyPaused() {
require(paused);
_;
}
/// @dev Modifier, which only allows function execution if paused longer than timeSpan.
modifier onlyPausedSince(uint timeSpan) {
require(paused && (timePaused.add(timeSpan) <= block.timestamp));
_;
}
/// @dev Event is fired if paused.
event LogPause();
/// @dev Event is fired if pause is ended.
event LogUnpause();
/**
* @dev Pause contract. No new game sessions can be created.
*/
function pause() public onlyOwner onlyNotPaused {
paused = true;
timePaused = block.timestamp;
emit LogPause();
}
/**
* @dev Unpause contract. Initial contract is paused and can only be unpaused after activating it.
*/
function unpause() public onlyOwner onlyPaused onlyActivated {
paused = false;
timePaused = 0;
emit LogUnpause();
}
}
contract Destroyable is Pausable {
/// @dev After pausing the contract for 20 days owner can selfdestruct it.
uint public constant TIMEOUT_DESTROY = 20 days;
/**
* @dev Destroy contract and transfer ether to owner.
*/
function destroy() public onlyOwner onlyPausedSince(TIMEOUT_DESTROY) {
selfdestruct(owner);
}
}
contract GameChannelBase is Destroyable, ConflictResolutionManager {
using SafeCast for int;
using SafeCast for uint;
using SafeMath for int;
using SafeMath for uint;
/// @dev Different game session states.
enum GameStatus {
ENDED, ///< @dev Game session is ended.
ACTIVE, ///< @dev Game session is active.
USER_INITIATED_END, ///< @dev User initiated non regular end.
SERVER_INITIATED_END ///< @dev Server initiated non regular end.
}
/// @dev Reason game session ended.
enum ReasonEnded {
REGULAR_ENDED, ///< @dev Game session is regularly ended.
SERVER_FORCED_END, ///< @dev User did not respond. Server forced end.
USER_FORCED_END, ///< @dev Server did not respond. User forced end.
CONFLICT_ENDED ///< @dev Server or user raised conflict ans pushed game state, opponent pushed same game state.
}
struct Game {
/// @dev Game session status.
GameStatus status;
/// @dev User's stake.
uint128 stake;
/// @dev Last game round info if not regularly ended.
/// If game session is ended normally this data is not used.
uint8 gameType;
uint32 roundId;
uint betNum;
uint betValue;
int balance;
bytes32 userSeed;
bytes32 serverSeed;
uint endInitiatedTime;
}
/// @dev Minimal time span between profit transfer.
uint public constant MIN_TRANSFER_TIMESPAN = 1 days;
/// @dev Maximal time span between profit transfer.
uint public constant MAX_TRANSFER_TIMSPAN = 6 * 30 days;
bytes32 public constant EIP712DOMAIN_TYPEHASH = keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
bytes32 public constant BET_TYPEHASH = keccak256(
"Bet(uint32 roundId,uint8 gameType,uint256 number,uint256 value,int256 balance,bytes32 serverHash,bytes32 userHash,uint256 gameId)"
);
bytes32 public DOMAIN_SEPERATOR;
/// @dev Current active game sessions.
uint public activeGames = 0;
/// @dev Game session id counter. Points to next free game session slot. So gameIdCntr -1 is the
// number of game sessions created.
uint public gameIdCntr = 1;
/// @dev Only this address can accept and end games.
address public serverAddress;
/// @dev Address to transfer profit to.
address public houseAddress;
/// @dev Current house stake.
uint public houseStake = 0;
/// @dev House profit since last profit transfer.
int public houseProfit = 0;
/// @dev Min value user needs to deposit for creating game session.
uint128 public minStake;
/// @dev Max value user can deposit for creating game session.
uint128 public maxStake;
/// @dev Timeout until next profit transfer is allowed.
uint public profitTransferTimeSpan = 14 days;
/// @dev Last time profit transferred to house.
uint public lastProfitTransferTimestamp;
/// @dev Maps gameId to game struct.
mapping (uint => Game) public gameIdGame;
/// @dev Maps user address to current user game id.
mapping (address => uint) public userGameId;
/// @dev Maps user address to pending returns.
mapping (address => uint) public pendingReturns;
/// @dev Modifier, which only allows to execute if house stake is high enough.
modifier onlyValidHouseStake(uint _activeGames) {
uint minHouseStake = conflictRes.minHouseStake(_activeGames);
require(houseStake >= minHouseStake, "inv houseStake");
_;
}
/// @dev Modifier to check if value send fulfills user stake requirements.
modifier onlyValidValue() {
require(minStake <= msg.value && msg.value <= maxStake, "inv stake");
_;
}
/// @dev Modifier, which only allows server to call function.
modifier onlyServer() {
require(msg.sender == serverAddress);
_;
}
/// @dev Modifier, which only allows to set valid transfer timeouts.
modifier onlyValidTransferTimeSpan(uint transferTimeout) {
require(transferTimeout >= MIN_TRANSFER_TIMESPAN
&& transferTimeout <= MAX_TRANSFER_TIMSPAN);
_;
}
/// @dev This event is fired when user creates game session.
event LogGameCreated(address indexed user, uint indexed gameId, uint128 stake, bytes32 indexed serverEndHash, bytes32 userEndHash);
/// @dev This event is fired when user requests conflict end.
event LogUserRequestedEnd(address indexed user, uint indexed gameId);
/// @dev This event is fired when server requests conflict end.
event LogServerRequestedEnd(address indexed user, uint indexed gameId);
/// @dev This event is fired when game session is ended.
event LogGameEnded(address indexed user, uint indexed gameId, uint32 roundId, int balance, ReasonEnded reason);
/// @dev this event is fired when owner modifies user's stake limits.
event LogStakeLimitsModified(uint minStake, uint maxStake);
/**
* @dev Contract constructor.
* @param _serverAddress Server address.
* @param _minStake Min value user needs to deposit to create game session.
* @param _maxStake Max value user can deposit to create game session.
* @param _conflictResAddress Conflict resolution contract address.
* @param _houseAddress House address to move profit to.
* @param _chainId Chain id for signature domain.
*/
constructor(
address _serverAddress,
uint128 _minStake,
uint128 _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _chainId
)
public
ConflictResolutionManager(_conflictResAddress)
{
require(_minStake > 0 && _minStake <= _maxStake);
serverAddress = _serverAddress;
houseAddress = _houseAddress;
lastProfitTransferTimestamp = block.timestamp;
minStake = _minStake;
maxStake = _maxStake;
DOMAIN_SEPERATOR = keccak256(abi.encode(
EIP712DOMAIN_TYPEHASH,
keccak256("Dicether"),
keccak256("2"),
_chainId,
address(this)
));
}
/**
* @dev Set gameIdCntr. Can be only set before activating contract.
*/
function setGameIdCntr(uint _gameIdCntr) public onlyOwner onlyNotActivated {
require(gameIdCntr > 0);
gameIdCntr = _gameIdCntr;
}
/**
* @notice Withdraw pending returns.
*/
function withdraw() public {
uint toTransfer = pendingReturns[msg.sender];
require(toTransfer > 0);
pendingReturns[msg.sender] = 0;
msg.sender.transfer(toTransfer);
}
/**
* @notice Transfer house profit to houseAddress.
*/
function transferProfitToHouse() public {
require(lastProfitTransferTimestamp.add(profitTransferTimeSpan) <= block.timestamp);
// update last transfer timestamp
lastProfitTransferTimestamp = block.timestamp;
if (houseProfit <= 0) {
// no profit to transfer
return;
}
uint toTransfer = houseProfit.castToUint();
houseProfit = 0;
houseStake = houseStake.sub(toTransfer);
houseAddress.transfer(toTransfer);
}
/**
* @dev Set profit transfer time span.
*/
function setProfitTransferTimeSpan(uint _profitTransferTimeSpan)
public
onlyOwner
onlyValidTransferTimeSpan(_profitTransferTimeSpan)
{
profitTransferTimeSpan = _profitTransferTimeSpan;
}
/**
* @dev Increase house stake by msg.value
*/
function addHouseStake() public payable onlyOwner {
houseStake = houseStake.add(msg.value);
}
/**
* @dev Withdraw house stake.
*/
function withdrawHouseStake(uint value) public onlyOwner {
uint minHouseStake = conflictRes.minHouseStake(activeGames);
require(value <= houseStake && houseStake.sub(value) >= minHouseStake);
require(houseProfit <= 0 || houseProfit.castToUint() <= houseStake.sub(value));
houseStake = houseStake.sub(value);
owner.transfer(value);
}
/**
* @dev Withdraw house stake and profit.
*/
function withdrawAll() public onlyOwner onlyPausedSince(3 days) {
houseProfit = 0;
uint toTransfer = houseStake;
houseStake = 0;
owner.transfer(toTransfer);
}
/**
* @dev Set new house address.
* @param _houseAddress New house address.
*/
function setHouseAddress(address _houseAddress) public onlyOwner {
houseAddress = _houseAddress;
}
/**
* @dev Set stake min and max value.
* @param _minStake Min stake.
* @param _maxStake Max stake.
*/
function setStakeRequirements(uint128 _minStake, uint128 _maxStake) public onlyOwner {
require(_minStake > 0 && _minStake <= _maxStake);
minStake = _minStake;
maxStake = _maxStake;
emit LogStakeLimitsModified(minStake, maxStake);
}
/**
* @dev Close game session.
* @param _game Game session data.
* @param _gameId Id of game session.
* @param _userAddress User's address of game session.
* @param _reason Reason for closing game session.
* @param _balance Game session balance.
*/
function closeGame(
Game storage _game,
uint _gameId,
uint32 _roundId,
address _userAddress,
ReasonEnded _reason,
int _balance
)
internal
{
_game.status = GameStatus.ENDED;
activeGames = activeGames.sub(1);
payOut(_userAddress, _game.stake, _balance);
emit LogGameEnded(_userAddress, _gameId, _roundId, _balance, _reason);
}
/**
* @dev End game by paying out user and server.
* @param _userAddress User's address.
* @param _stake User's stake.
* @param _balance User's balance.
*/
function payOut(address _userAddress, uint128 _stake, int _balance) internal {
int stakeInt = _stake;
int houseStakeInt = houseStake.castToInt();
assert(_balance <= conflictRes.maxBalance());
assert((stakeInt.add(_balance)) >= 0);
if (_balance > 0 && houseStakeInt < _balance) {
// Should never happen!
// House is bankrupt.
// Payout left money.
_balance = houseStakeInt;
}
houseProfit = houseProfit.sub(_balance);
int newHouseStake = houseStakeInt.sub(_balance);
houseStake = newHouseStake.castToUint();
uint valueUser = stakeInt.add(_balance).castToUint();
pendingReturns[_userAddress] += valueUser;
if (pendingReturns[_userAddress] > 0) {
safeSend(_userAddress);
}
}
/**
* @dev Send value of pendingReturns[_address] to _address.
* @param _address Address to send value to.
*/
function safeSend(address _address) internal {
uint valueToSend = pendingReturns[_address];
assert(valueToSend > 0);
pendingReturns[_address] = 0;
if (_address.send(valueToSend) == false) {
pendingReturns[_address] = valueToSend;
}
}
/**
* @dev Verify signature of given data. Throws on verification failure.
* @param _sig Signature of given data in the form of rsv.
* @param _address Address of signature signer.
*/
function verifySig(
uint32 _roundId,
uint8 _gameType,
uint _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _userHash,
uint _gameId,
address _contractAddress,
bytes _sig,
address _address
)
internal
view
{
// check if this is the correct contract
address contractAddress = this;
require(_contractAddress == contractAddress, "inv contractAddress");
bytes32 roundHash = calcHash(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_userHash,
_gameId
);
verify(
roundHash,
_sig,
_address
);
}
/**
* @dev Check if _sig is valid signature of _hash. Throws if invalid signature.
* @param _hash Hash to check signature of.
* @param _sig Signature of _hash.
* @param _address Address of signer.
*/
function verify(
bytes32 _hash,
bytes _sig,
address _address
)
internal
pure
{
(bytes32 r, bytes32 s, uint8 v) = signatureSplit(_sig);
address addressRecover = ecrecover(_hash, v, r, s);
require(addressRecover == _address, "inv sig");
}
/**
* @dev Calculate typed hash of given data (compare eth_signTypedData).
* @return Hash of given data.
*/
function calcHash(
uint32 _roundId,
uint8 _gameType,
uint _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _userHash,
uint _gameId
)
private
view
returns(bytes32)
{
bytes32 betHash = keccak256(abi.encode(
BET_TYPEHASH,
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_userHash,
_gameId
));
return keccak256(abi.encodePacked(
"\x19\x01",
DOMAIN_SEPERATOR,
betHash
));
}
/**
* @dev Split the given signature of the form rsv in r s v. v is incremented with 27 if
* it is below 2.
* @param _signature Signature to split.
* @return r s v
*/
function signatureSplit(bytes _signature)
private
pure
returns (bytes32 r, bytes32 s, uint8 v)
{
require(_signature.length == 65, "inv sig");
assembly {
r := mload(add(_signature, 32))
s := mload(add(_signature, 64))
v := and(mload(add(_signature, 65)), 0xff)
}
if (v < 2) {
v = v + 27;
}
}
}
contract GameChannelConflict is GameChannelBase {
using SafeCast for int;
using SafeCast for uint;
using SafeMath for int;
using SafeMath for uint;
/**
* @dev Contract constructor.
* @param _serverAddress Server address.
* @param _minStake Min value user needs to deposit to create game session.
* @param _maxStake Max value user can deposit to create game session.
* @param _conflictResAddress Conflict resolution contract address
* @param _houseAddress House address to move profit to
* @param _chainId Chain id for signature domain.
*/
constructor(
address _serverAddress,
uint128 _minStake,
uint128 _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _chainId
)
public
GameChannelBase(_serverAddress, _minStake, _maxStake, _conflictResAddress, _houseAddress, _chainId)
{
// nothing to do
}
/**
* @dev Used by server if user does not end game session.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _serverHash Hash of server seed for this bet.
* @param _userHash Hash of user seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _userSig User signature of this bet.
* @param _userAddress Address of user.
* @param _serverSeed Server seed for this bet.
* @param _userSeed User seed for this bet.
*/
function serverEndGameConflict(
uint32 _roundId,
uint8 _gameType,
uint _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _userHash,
uint _gameId,
address _contractAddress,
bytes _userSig,
address _userAddress,
bytes32 _serverSeed,
bytes32 _userSeed
)
public
onlyServer
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_userHash,
_gameId,
_contractAddress,
_userSig,
_userAddress
);
serverEndGameConflictImpl(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_userHash,
_serverSeed,
_userSeed,
_gameId,
_userAddress
);
}
/**
* @notice Can be used by user if server does not answer to the end game session request.
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _serverHash Hash of server seed for this bet.
* @param _userHash Hash of user seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _serverSig Server signature of this bet.
* @param _userSeed User seed for this bet.
*/
function userEndGameConflict(
uint32 _roundId,
uint8 _gameType,
uint _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _userHash,
uint _gameId,
address _contractAddress,
bytes _serverSig,
bytes32 _userSeed
)
public
{
verifySig(
_roundId,
_gameType,
_num,
_value,
_balance,
_serverHash,
_userHash,
_gameId,
_contractAddress,
_serverSig,
serverAddress
);
userEndGameConflictImpl(
_roundId,
_gameType,
_num,
_value,
_balance,
_userHash,
_userSeed,
_gameId,
msg.sender
);
}
/**
* @notice Cancel active game without playing. Useful if server stops responding before
* one game is played.
* @param _gameId Game session id.
*/
function userCancelActiveGame(uint _gameId) public {
address userAddress = msg.sender;
uint gameId = userGameId[userAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId, "inv gameId");
if (game.status == GameStatus.ACTIVE) {
game.endInitiatedTime = block.timestamp;
game.status = GameStatus.USER_INITIATED_END;
emit LogUserRequestedEnd(msg.sender, gameId);
} else if (game.status == GameStatus.SERVER_INITIATED_END && game.roundId == 0) {
cancelActiveGame(game, gameId, userAddress);
} else {
revert();
}
}
/**
* @dev Cancel active game without playing. Useful if user starts game session and
* does not play.
* @param _userAddress Users' address.
* @param _gameId Game session id.
*/
function serverCancelActiveGame(address _userAddress, uint _gameId) public onlyServer {
uint gameId = userGameId[_userAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId, "inv gameId");
if (game.status == GameStatus.ACTIVE) {
game.endInitiatedTime = block.timestamp;
game.status = GameStatus.SERVER_INITIATED_END;
emit LogServerRequestedEnd(msg.sender, gameId);
} else if (game.status == GameStatus.USER_INITIATED_END && game.roundId == 0) {
cancelActiveGame(game, gameId, _userAddress);
} else {
revert();
}
}
/**
* @dev Force end of game if user does not respond. Only possible after a certain period of time
* to give the user a chance to respond.
* @param _userAddress User's address.
*/
function serverForceGameEnd(address _userAddress, uint _gameId) public onlyServer {
uint gameId = userGameId[_userAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId, "inv gameId");
require(game.status == GameStatus.SERVER_INITIATED_END, "inv status");
// theoretically we have enough data to calculate winner
// but as user did not respond assume he has lost.
int newBalance = conflictRes.serverForceGameEnd(
game.gameType,
game.betNum,
game.betValue,
game.balance,
game.stake,
game.endInitiatedTime
);
closeGame(game, gameId, game.roundId, _userAddress, ReasonEnded.SERVER_FORCED_END, newBalance);
}
/**
* @notice Force end of game if server does not respond. Only possible after a certain period of time
* to give the server a chance to respond.
*/
function userForceGameEnd(uint _gameId) public {
address userAddress = msg.sender;
uint gameId = userGameId[userAddress];
Game storage game = gameIdGame[gameId];
require(gameId == _gameId, "inv gameId");
require(game.status == GameStatus.USER_INITIATED_END, "inv status");
int newBalance = conflictRes.userForceGameEnd(
game.gameType,
game.betNum,
game.betValue,
game.balance,
game.stake,
game.endInitiatedTime
);
closeGame(game, gameId, game.roundId, userAddress, ReasonEnded.USER_FORCED_END, newBalance);
}
/**
* @dev Conflict handling implementation. Stores game data and timestamp if game
* is active. If server has already marked conflict for game session the conflict
* resolution contract is used (compare conflictRes).
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _userHash Hash of user's seed for this bet.
* @param _userSeed User's seed for this bet.
* @param _gameId game Game session id.
* @param _userAddress User's address.
*/
function userEndGameConflictImpl(
uint32 _roundId,
uint8 _gameType,
uint _num,
uint _value,
int _balance,
bytes32 _userHash,
bytes32 _userSeed,
uint _gameId,
address _userAddress
)
private
{
uint gameId = userGameId[_userAddress];
Game storage game = gameIdGame[gameId];
int maxBalance = conflictRes.maxBalance();
int gameStake = game.stake;
require(gameId == _gameId, "inv gameId");
require(_roundId > 0, "inv roundId");
require(keccak256(abi.encodePacked(_userSeed)) == _userHash, "inv userSeed");
require(-gameStake <= _balance && _balance <= maxBalance, "inv balance"); // game.stake save to cast as uint128
require(conflictRes.isValidBet(_gameType, _num, _value), "inv bet");
require(gameStake.add(_balance).sub(_value.castToInt()) >= 0, "value too high"); // game.stake save to cast as uint128
if (game.status == GameStatus.SERVER_INITIATED_END && game.roundId == _roundId) {
game.userSeed = _userSeed;
endGameConflict(game, gameId, _userAddress);
} else if (game.status == GameStatus.ACTIVE
|| (game.status == GameStatus.SERVER_INITIATED_END && game.roundId < _roundId)) {
game.status = GameStatus.USER_INITIATED_END;
game.endInitiatedTime = block.timestamp;
game.roundId = _roundId;
game.gameType = _gameType;
game.betNum = _num;
game.betValue = _value;
game.balance = _balance;
game.userSeed = _userSeed;
game.serverSeed = bytes32(0);
emit LogUserRequestedEnd(msg.sender, gameId);
} else {
revert("inv state");
}
}
/**
* @dev Conflict handling implementation. Stores game data and timestamp if game
* is active. If user has already marked conflict for game session the conflict
* resolution contract is used (compare conflictRes).
* @param _roundId Round id of bet.
* @param _gameType Game type of bet.
* @param _num Number of bet.
* @param _value Value of bet.
* @param _balance Balance before this bet.
* @param _serverHash Hash of server's seed for this bet.
* @param _userHash Hash of user's seed for this bet.
* @param _serverSeed Server's seed for this bet.
* @param _userSeed User's seed for this bet.
* @param _userAddress User's address.
*/
function serverEndGameConflictImpl(
uint32 _roundId,
uint8 _gameType,
uint _num,
uint _value,
int _balance,
bytes32 _serverHash,
bytes32 _userHash,
bytes32 _serverSeed,
bytes32 _userSeed,
uint _gameId,
address _userAddress
)
private
{
uint gameId = userGameId[_userAddress];
Game storage game = gameIdGame[gameId];
int maxBalance = conflictRes.maxBalance();
int gameStake = game.stake;
require(gameId == _gameId, "inv gameId");
require(_roundId > 0, "inv roundId");
require(keccak256(abi.encodePacked(_serverSeed)) == _serverHash, "inv serverSeed");
require(keccak256(abi.encodePacked(_userSeed)) == _userHash, "inv userSeed");
require(-gameStake <= _balance && _balance <= maxBalance, "inv balance"); // game.stake save to cast as uint128
require(conflictRes.isValidBet(_gameType, _num, _value), "inv bet");
require(gameStake.add(_balance).sub(_value.castToInt()) >= 0, "too high value"); // game.stake save to cast as uin128
if (game.status == GameStatus.USER_INITIATED_END && game.roundId == _roundId) {
game.serverSeed = _serverSeed;
endGameConflict(game, gameId, _userAddress);
} else if (game.status == GameStatus.ACTIVE
|| (game.status == GameStatus.USER_INITIATED_END && game.roundId < _roundId)) {
game.status = GameStatus.SERVER_INITIATED_END;
game.endInitiatedTime = block.timestamp;
game.roundId = _roundId;
game.gameType = _gameType;
game.betNum = _num;
game.betValue = _value;
game.balance = _balance;
game.serverSeed = _serverSeed;
game.userSeed = _userSeed;
emit LogServerRequestedEnd(_userAddress, gameId);
} else {
revert("inv state");
}
}
/**
* @dev End conflicting game without placed bets.
* @param _game Game session data.
* @param _gameId Game session id.
* @param _userAddress User's address.
*/
function cancelActiveGame(Game storage _game, uint _gameId, address _userAddress) private {
// user need to pay a fee when conflict ended.
// this ensures a malicious, rich user can not just generate game sessions and then wait
// for us to end the game session and then confirm the session status, so
// we would have to pay a high gas fee without profit.
int newBalance = -conflictRes.conflictEndFine();
// do not allow balance below user stake
int stake = _game.stake;
if (newBalance < -stake) {
newBalance = -stake;
}
closeGame(_game, _gameId, 0, _userAddress, ReasonEnded.CONFLICT_ENDED, newBalance);
}
/**
* @dev End conflicting game.
* @param _game Game session data.
* @param _gameId Game session id.
* @param _userAddress User's address.
*/
function endGameConflict(Game storage _game, uint _gameId, address _userAddress) private {
int newBalance = conflictRes.endGameConflict(
_game.gameType,
_game.betNum,
_game.betValue,
_game.balance,
_game.stake,
_game.serverSeed,
_game.userSeed
);
closeGame(_game, _gameId, _game.roundId, _userAddress, ReasonEnded.CONFLICT_ENDED, newBalance);
}
}
contract GameChannel is GameChannelConflict {
/**
* @dev contract constructor
* @param _serverAddress Server address.
* @param _minStake Min value user needs to deposit to create game session.
* @param _maxStake Max value user can deposit to create game session.
* @param _conflictResAddress Conflict resolution contract address.
* @param _houseAddress House address to move profit to.
* @param _chainId Chain id for signature domain.
*/
constructor(
address _serverAddress,
uint128 _minStake,
uint128 _maxStake,
address _conflictResAddress,
address _houseAddress,
uint _chainId
)
public
GameChannelConflict(_serverAddress, _minStake, _maxStake, _conflictResAddress, _houseAddress, _chainId)
{
// nothing to do
}
/**
* @notice Create games session request. msg.value needs to be valid stake value.
* @param _userEndHash Last entry of users' hash chain.
* @param _previousGameId User's previous game id, initial 0.
* @param _createBefore Game can be only created before this timestamp.
* @param _serverEndHash Last entry of server's hash chain.
* @param _serverSig Server signature. See verifyCreateSig
*/
function createGame(
bytes32 _userEndHash,
uint _previousGameId,
uint _createBefore,
bytes32 _serverEndHash,
bytes _serverSig
)
public
payable
onlyValidValue
onlyValidHouseStake(activeGames + 1)
onlyNotPaused
{
uint previousGameId = userGameId[msg.sender];
Game storage game = gameIdGame[previousGameId];
require(game.status == GameStatus.ENDED, "prev game not ended");
require(previousGameId == _previousGameId, "inv gamePrevGameId");
require(block.timestamp < _createBefore, "expired");
verifyCreateSig(msg.sender, _previousGameId, _createBefore, _serverEndHash, _serverSig);
uint gameId = gameIdCntr++;
userGameId[msg.sender] = gameId;
Game storage newGame = gameIdGame[gameId];
newGame.stake = uint128(msg.value); // It's safe to cast msg.value as it is limited, see onlyValidValue
newGame.status = GameStatus.ACTIVE;
activeGames = activeGames.add(1);
// It's safe to cast msg.value as it is limited, see onlyValidValue
emit LogGameCreated(msg.sender, gameId, uint128(msg.value), _serverEndHash, _userEndHash);
}
/**
* @dev Regular end game session. Used if user and house have both
* accepted current game session state.
* The game session with gameId _gameId is closed
* and the user paid out. This functions is called by the server after
* the user requested the termination of the current game session.
* @param _roundId Round id of bet.
* @param _balance Current balance.
* @param _serverHash Hash of server's seed for this bet.
* @param _userHash Hash of user's seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _userAddress Address of user.
* @param _userSig User's signature of this bet.
*/
function serverEndGame(
uint32 _roundId,
int _balance,
bytes32 _serverHash,
bytes32 _userHash,
uint _gameId,
address _contractAddress,
address _userAddress,
bytes _userSig
)
public
onlyServer
{
verifySig(
_roundId,
0,
0,
0,
_balance,
_serverHash,
_userHash,
_gameId,
_contractAddress,
_userSig,
_userAddress
);
regularEndGame(_userAddress, _roundId, _balance, _gameId, _contractAddress);
}
/**
* @notice Regular end game session. Normally not needed as server ends game (@see serverEndGame).
* Can be used by user if server does not end game session.
* @param _roundId Round id of bet.
* @param _balance Current balance.
* @param _serverHash Hash of server's seed for this bet.
* @param _userHash Hash of user's seed for this bet.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
* @param _serverSig Server's signature of this bet.
*/
function userEndGame(
uint32 _roundId,
int _balance,
bytes32 _serverHash,
bytes32 _userHash,
uint _gameId,
address _contractAddress,
bytes _serverSig
)
public
{
verifySig(
_roundId,
0,
0,
0,
_balance,
_serverHash,
_userHash,
_gameId,
_contractAddress,
_serverSig,
serverAddress
);
regularEndGame(msg.sender, _roundId, _balance, _gameId, _contractAddress);
}
/**
* @dev Verify server signature.
* @param _userAddress User's address.
* @param _previousGameId User's previous game id, initial 0.
* @param _createBefore Game can be only created before this timestamp.
* @param _serverEndHash Last entry of server's hash chain.
* @param _serverSig Server signature.
*/
function verifyCreateSig(
address _userAddress,
uint _previousGameId,
uint _createBefore,
bytes32 _serverEndHash,
bytes _serverSig
)
private view
{
address contractAddress = this;
bytes32 hash = keccak256(abi.encodePacked(
contractAddress, _userAddress, _previousGameId, _createBefore, _serverEndHash
));
verify(hash, _serverSig, serverAddress);
}
/**
* @dev Regular end game session implementation. Used if user and house have both
* accepted current game session state. The game session with gameId _gameId is closed
* and the user paid out.
* @param _userAddress Address of user.
* @param _balance Current balance.
* @param _gameId Game session id.
* @param _contractAddress Address of this contract.
*/
function regularEndGame(
address _userAddress,
uint32 _roundId,
int _balance,
uint _gameId,
address _contractAddress
)
private
{
uint gameId = userGameId[_userAddress];
Game storage game = gameIdGame[gameId];
int maxBalance = conflictRes.maxBalance();
int gameStake = game.stake;
require(_gameId == gameId, "inv gameId");
require(_roundId > 0, "inv roundId");
// save to cast as game.stake hash fixed range
require(-gameStake <= _balance && _balance <= maxBalance, "inv balance");
require(game.status == GameStatus.ACTIVE, "inv status");
assert(_contractAddress == address(this));
closeGame(game, gameId, _roundId, _userAddress, ReasonEnded.REGULAR_ENDED, _balance);
}
}
library SafeCast {
/**
* Cast unsigned a to signed a.
*/
function castToInt(uint a) internal pure returns(int) {
assert(a < (1 << 255));
return int(a);
}
/**
* Cast signed a to unsigned a.
*/
function castToUint(int a) internal pure returns(uint) {
assert(a >= 0);
return uint(a);
}
}
library SafeMath {
/**
* @dev Multiplies two unsigned integers, 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 Multiplies two signed integers, throws on overflow.
*/
function mul(int256 a, int256 b) internal pure returns (int256) {
// 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;
}
int256 c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two unsigned integers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Integer division of two signed integers, truncating the quotient.
*/
function div(int256 a, int256 b) internal pure returns (int256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// Overflow only happens when the smallest negative int is multiplied by -1.
int256 INT256_MIN = int256((uint256(1) << 255));
assert(a != INT256_MIN || b != - 1);
return a / b;
}
/**
* @dev Subtracts two unsigned integers, 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 Subtracts two signed integers, throws on overflow.
*/
function sub(int256 a, int256 b) internal pure returns (int256) {
int256 c = a - b;
assert((b >= 0 && c <= a) || (b < 0 && c > a));
return c;
}
/**
* @dev Adds two unsigned integers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
/**
* @dev Adds two signed integers, throws on overflow.
*/
function add(int256 a, int256 b) internal pure returns (int256) {
int256 c = a + b;
assert((b >= 0 && c >= a) || (b < 0 && c < a));
return c;
}
}
|
Unpause contract. Initial contract is paused and can only be unpaused after activating it./
|
function unpause() public onlyOwner onlyPaused onlyActivated {
paused = false;
timePaused = 0;
emit LogUnpause();
}
| 10,632,713 |
// hevm: flattened sources of contracts/Alchemist.sol
pragma solidity ^0.4.24;
////// contracts/openzeppelin/IERC20.sol
/* pragma solidity ^0.4.24; */
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
////// contracts/Alchemist.sol
/* pragma solidity ^0.4.24; */
/* import "./openzeppelin/IERC20.sol"; */
contract Alchemist {
address public LEAD;
address public GOLD;
constructor(address _lead, address _gold) public {
LEAD = _lead;
GOLD = _gold;
}
function transmute(uint _mass) external {
require(
IERC20(LEAD).transferFrom(msg.sender, address(this), _mass),
"LEAD transfer failed"
);
require(
IERC20(GOLD).transfer(msg.sender, _mass),
"GOLD transfer failed"
);
}
}
|
ERC20 interface/
|
interface IERC20 {
function totalSupply() external view returns (uint256);
function balanceOf(address who) external view returns (uint256);
function allowance(address owner, address spender) external view returns (uint256);
function transfer(address to, uint256 value) external returns (bool);
function approve(address spender, uint256 value) external returns (bool);
function transferFrom(address from, address to, uint256 value) external returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
pragma solidity ^0.4.24;
}
| 12,575,715 |
// File: @openzeppelin/contracts/token/ERC20/IERC20.sol
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: @openzeppelin/contracts/math/SafeMath.sol
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: contracts/interfaces/IAToken.sol
pragma solidity 0.7.5;
interface IAToken is IERC20 {
// solhint-disable-next-line func-name-mixedcase
function UNDERLYING_ASSET_ADDRESS() external returns (address);
}
// File: contracts/interfaces/IOwnable.sol
pragma solidity 0.7.5;
interface IOwnable {
function owner() external view returns (address);
}
// File: contracts/interfaces/ILendingPool.sol
pragma solidity 0.7.5;
interface ILendingPool {
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external returns (uint256);
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external returns (uint256);
// workaround to omit usage of abicoder v2
// see real signature at https://github.com/aave/protocol-v2/blob/master/contracts/protocol/libraries/types/DataTypes.sol
function getReserveData(address asset) external returns (address[12] memory);
}
// File: contracts/interfaces/IStakedTokenIncentivesController.sol
pragma solidity 0.7.5;
interface IStakedTokenIncentivesController {
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external;
function getRewardsBalance(address[] calldata assets, address user) external view returns (uint256);
function configureAssets(address[] calldata assets, uint256[] calldata emissionsPerSecond) external;
function setDistributionEnd(uint256 distributionEnd) external;
function initialize(address addressesProvider) external;
}
// File: contracts/interfaces/ILegacyERC20.sol
pragma solidity 0.7.5;
interface ILegacyERC20 {
function approve(address spender, uint256 amount) external; // returns (bool);
}
// File: @openzeppelin/contracts/utils/Address.sol
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/upgradeable_contracts/modules/OwnableModule.sol
pragma solidity 0.7.5;
/**
* @title OwnableModule
* @dev Common functionality for multi-token extension non-upgradeable module.
*/
contract OwnableModule {
address public owner;
/**
* @dev Initializes this contract.
* @param _owner address of the owner that is allowed to perform additional actions on the particular module.
*/
constructor(address _owner) {
owner = _owner;
}
/**
* @dev Throws if sender is not the owner of this contract.
*/
modifier onlyOwner {
require(msg.sender == owner);
_;
}
/**
* @dev Changes the owner of this contract.
* @param _newOwner address of the new owner.
*/
function transferOwnership(address _newOwner) external onlyOwner {
owner = _newOwner;
}
}
// File: contracts/upgradeable_contracts/modules/MediatorOwnableModule.sol
pragma solidity 0.7.5;
/**
* @title MediatorOwnableModule
* @dev Common functionality for non-upgradeable Omnibridge extension module.
*/
contract MediatorOwnableModule is OwnableModule {
address public mediator;
/**
* @dev Initializes this contract.
* @param _mediator address of the deployed Omnibridge extension for which this module is deployed.
* @param _owner address of the owner that is allowed to perform additional actions on the particular module.
*/
constructor(address _mediator, address _owner) OwnableModule(_owner) {
require(Address.isContract(_mediator));
mediator = _mediator;
}
/**
* @dev Throws if sender is not the Omnibridge extension.
*/
modifier onlyMediator {
require(msg.sender == mediator);
_;
}
}
// File: @openzeppelin/contracts/token/ERC20/SafeERC20.sol
pragma solidity ^0.7.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File: contracts/interfaces/IInterestReceiver.sol
pragma solidity 0.7.5;
interface IInterestReceiver {
function onInterestReceived(address _token) external;
}
// File: contracts/interfaces/IInterestImplementation.sol
pragma solidity 0.7.5;
interface IInterestImplementation {
event InterestEnabled(address indexed token, address xToken);
event InterestDustUpdated(address indexed token, uint96 dust);
event InterestReceiverUpdated(address indexed token, address receiver);
event MinInterestPaidUpdated(address indexed token, uint256 amount);
event PaidInterest(address indexed token, address to, uint256 value);
event ForceDisable(address indexed token, uint256 tokensAmount, uint256 xTokensAmount, uint256 investedAmount);
function isInterestSupported(address _token) external view returns (bool);
function invest(address _token, uint256 _amount) external;
function withdraw(address _token, uint256 _amount) external;
function investedAmount(address _token) external view returns (uint256);
}
// File: contracts/upgradeable_contracts/modules/interest/BaseInterestERC20.sol
pragma solidity 0.7.5;
/**
* @title BaseInterestERC20
* @dev This contract contains common logic for investing ERC20 tokens into different interest-earning protocols.
*/
abstract contract BaseInterestERC20 is IInterestImplementation {
using SafeERC20 for IERC20;
/**
* @dev Ensures that caller is an EOA.
* Functions with such modifier cannot be called from other contract (as well as from GSN-like approaches)
*/
modifier onlyEOA {
// solhint-disable-next-line avoid-tx-origin
require(msg.sender == tx.origin);
/* solcov ignore next */
_;
}
/**
* @dev Internal function transferring interest tokens to the interest receiver.
* Calls a callback on the receiver, interest receiver is a contract.
* @param _receiver address of the tokens receiver.
* @param _token address of the token contract to send.
* @param _amount amount of tokens to transfer.
*/
function _transferInterest(
address _receiver,
address _token,
uint256 _amount
) internal {
require(_receiver != address(0));
IERC20(_token).safeTransfer(_receiver, _amount);
if (Address.isContract(_receiver)) {
IInterestReceiver(_receiver).onInterestReceived(_token);
}
emit PaidInterest(_token, _receiver, _amount);
}
}
// File: contracts/upgradeable_contracts/modules/interest/AAVEInterestERC20.sol
pragma solidity 0.7.5;
/**
* @title AAVEInterestERC20
* @dev This contract contains token-specific logic for investing ERC20 tokens into AAVE protocol.
*/
contract AAVEInterestERC20 is BaseInterestERC20, MediatorOwnableModule {
using SafeMath for uint256;
using SafeERC20 for IERC20;
using SafeERC20 for IAToken;
struct InterestParams {
IAToken aToken;
uint96 dust;
uint256 investedAmount;
address interestReceiver;
uint256 minInterestPaid;
}
mapping(address => InterestParams) public interestParams;
uint256 public minAavePaid;
address public aaveReceiver;
constructor(
address _omnibridge,
address _owner,
uint256 _minAavePaid,
address _aaveReceiver
) MediatorOwnableModule(_omnibridge, _owner) {
minAavePaid = _minAavePaid;
aaveReceiver = _aaveReceiver;
}
/**
* @dev Tells the module interface version that this contract supports.
* @return major value of the version
* @return minor value of the version
* @return patch value of the version
*/
function getModuleInterfacesVersion()
external
pure
returns (
uint64 major,
uint64 minor,
uint64 patch
)
{
return (1, 0, 0);
}
/**
* @dev Tells the address of the LendingPool contract in the Ethereum Mainnet.
*/
function lendingPool() public pure virtual returns (ILendingPool) {
return ILendingPool(0x7d2768dE32b0b80b7a3454c06BdAc94A69DDc7A9);
}
/**
* @dev Tells the address of the StakedTokenIncentivesController contract in the Ethereum Mainnet.
*/
function incentivesController() public pure virtual returns (IStakedTokenIncentivesController) {
return IStakedTokenIncentivesController(0xd784927Ff2f95ba542BfC824c8a8a98F3495f6b5);
}
/**
* @dev Tells the address of the StkAAVE token contract in the Ethereum Mainnet.
*/
function stkAAVEToken() public pure virtual returns (address) {
return 0x4da27a545c0c5B758a6BA100e3a049001de870f5;
}
/**
* @dev Enables support for interest earning through a specific aToken.
* @param _token address of the token contract for which to enable interest.
* @param _dust small amount of underlying tokens that cannot be paid as an interest. Accounts for possible truncation errors.
* @param _interestReceiver address of the interest receiver for underlying token.
* @param _minInterestPaid min amount of underlying tokens to be paid as an interest.
*/
function enableInterestToken(
address _token,
uint96 _dust,
address _interestReceiver,
uint256 _minInterestPaid
) external onlyOwner {
IAToken aToken = IAToken(lendingPool().getReserveData(_token)[7]);
require(aToken.UNDERLYING_ASSET_ADDRESS() == _token);
// disallow reinitialization of tokens that were already initialized and invested
require(interestParams[_token].investedAmount == 0);
interestParams[_token] = InterestParams(aToken, _dust, 0, _interestReceiver, _minInterestPaid);
// SafeERC20.safeApprove does not work here in case of possible interest reinitialization,
// since it does not allow positive->positive allowance change. However, it would be safe to make such change here.
ILegacyERC20(_token).approve(address(lendingPool()), uint256(-1));
emit InterestEnabled(_token, address(aToken));
emit InterestDustUpdated(_token, _dust);
emit InterestReceiverUpdated(_token, _interestReceiver);
emit MinInterestPaidUpdated(_token, _minInterestPaid);
}
/**
* @dev Tells the current amount of underlying tokens that was invested into the AAVE protocol.
* @param _token address of the underlying token.
* @return currently invested value.
*/
function investedAmount(address _token) external view override returns (uint256) {
return interestParams[_token].investedAmount;
}
/**
* @dev Tells if interest earning is supported for the specific underlying token contract.
* @param _token address of the token contract.
* @return true, if interest earning is supported for the given token.
*/
function isInterestSupported(address _token) external view override returns (bool) {
return address(interestParams[_token].aToken) != address(0);
}
/**
* @dev Invests the given amount of tokens to the AAVE protocol.
* Only Omnibridge contract is allowed to call this method.
* Converts _amount of TOKENs into aTOKENs.
* @param _token address of the invested token contract.
* @param _amount amount of tokens to invest.
*/
function invest(address _token, uint256 _amount) external override onlyMediator {
InterestParams storage params = interestParams[_token];
params.investedAmount = params.investedAmount.add(_amount);
lendingPool().deposit(_token, _amount, address(this), 0);
}
/**
* @dev Withdraws at least min(_amount, investedAmount) of tokens from the AAVE protocol.
* Only Omnibridge contract is allowed to call this method.
* Converts aTOKENs into _amount of TOKENs.
* @param _token address of the invested token contract.
* @param _amount minimal amount of tokens to withdraw.
*/
function withdraw(address _token, uint256 _amount) external override onlyMediator {
InterestParams storage params = interestParams[_token];
uint256 invested = params.investedAmount;
uint256 redeemed = _safeWithdraw(_token, _amount > invested ? invested : _amount);
params.investedAmount = redeemed > invested ? 0 : invested - redeemed;
IERC20(_token).safeTransfer(mediator, redeemed);
}
/**
* @dev Tells the current accumulated interest on the invested tokens, that can be withdrawn and payed to the interest receiver.
* @param _token address of the invested token contract.
* @return amount of accumulated interest.
*/
function interestAmount(address _token) public view returns (uint256) {
InterestParams storage params = interestParams[_token];
(IAToken aToken, uint96 dust) = (params.aToken, params.dust);
uint256 balance = aToken.balanceOf(address(this));
// small portion of tokens are reserved for possible truncation/round errors
uint256 reserved = params.investedAmount.add(dust);
return balance > reserved ? balance - reserved : 0;
}
/**
* @dev Pays collected interest for the underlying token.
* Anyone can call this function.
* Earned interest is withdrawn and transferred to the specified interest receiver account.
* @param _token address of the invested token contract in which interest should be paid.
*/
function payInterest(address _token) external onlyEOA {
InterestParams storage params = interestParams[_token];
uint256 interest = interestAmount(_token);
require(interest >= params.minInterestPaid);
_transferInterest(params.interestReceiver, address(_token), _safeWithdraw(_token, interest));
}
/**
* @dev Tells the amount of earned stkAAVE tokens for supplying assets into the protocol that can be withdrawn.
* Intended to be called via eth_call to obtain the current accumulated value for stkAAVE.
* @param _assets aTokens addresses to claim stkAAVE for.
* @return amount of accumulated stkAAVE tokens across given markets.
*/
function aaveAmount(address[] calldata _assets) public view returns (uint256) {
return incentivesController().getRewardsBalance(_assets, address(this));
}
/**
* @dev Claims stkAAVE token received by supplying underlying tokens and transfers it to the associated AAVE receiver.
* @param _assets aTokens addresses to claim stkAAVE for.
*/
function claimAaveAndPay(address[] calldata _assets) external onlyEOA {
uint256 balance = aaveAmount(_assets);
require(balance >= minAavePaid);
incentivesController().claimRewards(_assets, balance, address(this));
_transferInterest(aaveReceiver, stkAAVEToken(), balance);
}
/**
* @dev Last-resort function for returning assets to the Omnibridge contract in case of some failures in the logic.
* Disables this contract and transfers locked tokens back to the mediator.
* Only owner is allowed to call this method.
* @param _token address of the invested token contract that should be disabled.
*/
function forceDisable(address _token) external onlyOwner {
InterestParams storage params = interestParams[_token];
IAToken aToken = params.aToken;
uint256 aTokenBalance = 0;
// try to redeem all aTokens
// it is safe to specify uint256(-1) as max amount of redeemed tokens
// since the withdraw method of the pool contract will return the entire balance
try lendingPool().withdraw(_token, uint256(-1), mediator) {} catch {
aTokenBalance = aToken.balanceOf(address(this));
aToken.safeTransfer(mediator, aTokenBalance);
}
uint256 balance = IERC20(_token).balanceOf(address(this));
IERC20(_token).safeTransfer(mediator, balance);
IERC20(_token).safeApprove(address(lendingPool()), 0);
emit ForceDisable(_token, balance, aTokenBalance, params.investedAmount);
delete interestParams[_token];
}
/**
* @dev Updates dust parameter for the particular token.
* Only owner is allowed to call this method.
* @param _token address of the invested token contract.
* @param _dust new amount of underlying tokens that cannot be paid as an interest. Accounts for possible truncation errors.
*/
function setDust(address _token, uint96 _dust) external onlyOwner {
interestParams[_token].dust = _dust;
emit InterestDustUpdated(_token, _dust);
}
/**
* @dev Updates address of the interest receiver. Can be any address, EOA or contract.
* Set to 0x00..00 to disable interest transfers.
* Only owner is allowed to call this method.
* @param _token address of the invested token contract.
* @param _receiver address of the interest receiver.
*/
function setInterestReceiver(address _token, address _receiver) external onlyOwner {
interestParams[_token].interestReceiver = _receiver;
emit InterestReceiverUpdated(_token, _receiver);
}
/**
* @dev Updates min interest amount that can be transferred in single call.
* Only owner is allowed to call this method.
* @param _token address of the invested token contract.
* @param _minInterestPaid new amount of TOKENS and can be transferred to the interest receiver in single operation.
*/
function setMinInterestPaid(address _token, uint256 _minInterestPaid) external onlyOwner {
interestParams[_token].minInterestPaid = _minInterestPaid;
emit MinInterestPaidUpdated(_token, _minInterestPaid);
}
/**
* @dev Updates min stkAAVE amount that can be transferred in single call.
* Only owner is allowed to call this method.
* @param _minAavePaid new amount of stkAAVE and can be transferred to the interest receiver in single operation.
*/
function setMinAavePaid(uint256 _minAavePaid) external onlyOwner {
minAavePaid = _minAavePaid;
emit MinInterestPaidUpdated(address(stkAAVEToken()), _minAavePaid);
}
/**
* @dev Updates address of the accumulated stkAAVE receiver. Can be any address, EOA or contract.
* Set to 0x00..00 to disable stkAAVE claims and transfers.
* Only owner is allowed to call this method.
* @param _receiver address of the interest receiver.
*/
function setAaveReceiver(address _receiver) external onlyOwner {
aaveReceiver = _receiver;
emit InterestReceiverUpdated(address(stkAAVEToken()), _receiver);
}
/**
* @dev Internal function for securely withdrawing assets from the underlying protocol.
* @param _token address of the invested token contract.
* @param _amount minimal amount of underlying tokens to withdraw from AAVE.
* @return amount of redeemed tokens, at least as much as was requested.
*/
function _safeWithdraw(address _token, uint256 _amount) private returns (uint256) {
uint256 balance = IERC20(_token).balanceOf(address(this));
lendingPool().withdraw(_token, _amount, address(this));
uint256 redeemed = IERC20(_token).balanceOf(address(this)) - balance;
require(redeemed >= _amount);
return redeemed;
}
}
|
solhint-disable-next-line func-name-mixedcase
|
interface IAToken is IERC20 {
function UNDERLYING_ASSET_ADDRESS() external returns (address);
}
| 13,419,474 |
./partial_match/1/0xe6F4d9711121e5304b30aC2Aae57E3b085ad3c4d/sources/src/ERC20Pool.sol
|
@inheritdoc IERC20PoolImmutables
|
function collateralScale() external pure override returns (uint256) {
return _getArgUint256(COLLATERAL_SCALE);
}
| 3,629,716 |
/**
*Submitted for verification at Etherscan.io on 2021-06-10
*/
pragma solidity ^0.5.17;
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath
* @dev Math operations with safety checks that revert on error
*/
library SafeMath {
string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint256 _a, uint256 _b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (_a == 0) {
return 0;
}
uint256 c = _a * _b;
require(c / _a == _b, ERROR_MUL_OVERFLOW);
return c;
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint256 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 _a, uint256 _b) internal pure returns (uint256) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint256 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint256 _a, uint256 _b) internal pure returns (uint256) {
uint256 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract IERC20 {
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
function totalSupply() external view returns (uint256);
function balanceOf(address _who) external view returns (uint256);
function allowance(address _owner, address _spender) external view returns (uint256);
function transfer(address _to, uint256 _value) external returns (bool);
function approve(address _spender, uint256 _value) external returns (bool);
function transferFrom(address _from, address _to, uint256 _value) external returns (bool);
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/SafeERC20.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
library SafeERC20 {
/**
* @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeTransfer(IERC20 _token, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferCallData = abi.encodeWithSelector(
_token.transfer.selector,
_to,
_amount
);
return invokeAndCheckSuccess(address(_token), transferCallData);
}
/**
* @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeTransferFrom(IERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) {
bytes memory transferFromCallData = abi.encodeWithSelector(
_token.transferFrom.selector,
_from,
_to,
_amount
);
return invokeAndCheckSuccess(address(_token), transferFromCallData);
}
/**
* @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false).
* Note that this makes an external call to the provided token and expects it to be already
* verified as a contract.
*/
function safeApprove(IERC20 _token, address _spender, uint256 _amount) internal returns (bool) {
bytes memory approveCallData = abi.encodeWithSelector(
_token.approve.selector,
_spender,
_amount
);
return invokeAndCheckSuccess(address(_token), approveCallData);
}
function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) {
bool ret;
assembly {
let ptr := mload(0x40) // free memory pointer
let success := call(
gas, // forward all gas
_addr, // address
0, // no value
add(_calldata, 0x20), // calldata start
mload(_calldata), // calldata length
ptr, // write output over free memory
0x20 // uint256 return
)
if gt(success, 0) {
// Check number of bytes returned from last function call
switch returndatasize
// No bytes returned: assume success
case 0 {
ret := 1
}
// 32 bytes returned: check if non-zero
case 0x20 {
// Only return success if returned data was true
// Already have output in ptr
ret := eq(mload(ptr), 1)
}
// Not sure what was returned: don't mark as success
default { }
}
}
return ret;
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface ITreasury {
/**
* @dev Assign a certain amount of tokens to an account
* @param _token ERC20 token to be assigned
* @param _to Address of the recipient that will be assigned the tokens to
* @param _amount Amount of tokens to be assigned to the recipient
*/
function assign(IERC20 _token, address _to, uint256 _amount) external;
/**
* @dev Withdraw a certain amount of tokens
* @param _token ERC20 token to be withdrawn
* @param _from Address withdrawing the tokens from
* @param _to Address of the recipient that will receive the tokens
* @param _amount Amount of tokens to be withdrawn from the sender
*/
function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external;
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/IsContract.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract IsContract {
/*
* NOTE: this should NEVER be used for authentication
* (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize).
*
* This is only intended to be used as a sanity check that an address is actually a contract,
* RATHER THAN an address not being a contract.
*/
function isContract(address _target) internal view returns (bool) {
if (_target == address(0)) {
return false;
}
uint256 size;
assembly { size := extcodesize(_target) }
return size > 0;
}
}
contract ACL {
string private constant ERROR_BAD_FREEZE = "ACL_BAD_FREEZE";
string private constant ERROR_ROLE_ALREADY_FROZEN = "ACL_ROLE_ALREADY_FROZEN";
string private constant ERROR_INVALID_BULK_INPUT = "ACL_INVALID_BULK_INPUT";
enum BulkOp { Grant, Revoke, Freeze }
address internal constant FREEZE_FLAG = address(1);
address internal constant ANY_ADDR = address(-1);
// List of all roles assigned to different addresses
mapping (bytes32 => mapping (address => bool)) public roles;
event Granted(bytes32 indexed id, address indexed who);
event Revoked(bytes32 indexed id, address indexed who);
event Frozen(bytes32 indexed id);
/**
* @dev Tell whether an address has a role assigned
* @param _who Address being queried
* @param _id ID of the role being checked
* @return True if the requested address has assigned the given role, false otherwise
*/
function hasRole(address _who, bytes32 _id) public view returns (bool) {
return roles[_id][_who] || roles[_id][ANY_ADDR];
}
/**
* @dev Tell whether a role is frozen
* @param _id ID of the role being checked
* @return True if the given role is frozen, false otherwise
*/
function isRoleFrozen(bytes32 _id) public view returns (bool) {
return roles[_id][FREEZE_FLAG];
}
/**
* @dev Internal function to grant a role to a given address
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function _grant(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
require(_who != FREEZE_FLAG, ERROR_BAD_FREEZE);
if (!hasRole(_who, _id)) {
roles[_id][_who] = true;
emit Granted(_id, _who);
}
}
/**
* @dev Internal function to revoke a role from a given address
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function _revoke(bytes32 _id, address _who) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
if (hasRole(_who, _id)) {
roles[_id][_who] = false;
emit Revoked(_id, _who);
}
}
/**
* @dev Internal function to freeze a role
* @param _id ID of the role to be frozen
*/
function _freeze(bytes32 _id) internal {
require(!isRoleFrozen(_id), ERROR_ROLE_ALREADY_FROZEN);
roles[_id][FREEZE_FLAG] = true;
emit Frozen(_id);
}
/**
* @dev Internal function to enact a bulk list of ACL operations
*/
function _bulk(BulkOp[] memory _op, bytes32[] memory _id, address[] memory _who) internal {
require(_op.length == _id.length && _op.length == _who.length, ERROR_INVALID_BULK_INPUT);
for (uint256 i = 0; i < _op.length; i++) {
BulkOp op = _op[i];
if (op == BulkOp.Grant) {
_grant(_id[i], _who[i]);
} else if (op == BulkOp.Revoke) {
_revoke(_id[i], _who[i]);
} else if (op == BulkOp.Freeze) {
_freeze(_id[i]);
}
}
}
}
contract ModuleIds {
// DisputeManager module ID - keccak256(abi.encodePacked("DISPUTE_MANAGER"))
bytes32 internal constant MODULE_ID_DISPUTE_MANAGER = 0x14a6c70f0f6d449c014c7bbc9e68e31e79e8474fb03b7194df83109a2d888ae6;
// GuardiansRegistry module ID - keccak256(abi.encodePacked("GUARDIANS_REGISTRY"))
bytes32 internal constant MODULE_ID_GUARDIANS_REGISTRY = 0x8af7b7118de65da3b974a3fd4b0c702b66442f74b9dff6eaed1037254c0b79fe;
// Voting module ID - keccak256(abi.encodePacked("VOTING"))
bytes32 internal constant MODULE_ID_VOTING = 0x7cbb12e82a6d63ff16fe43977f43e3e2b247ecd4e62c0e340da8800a48c67346;
// PaymentsBook module ID - keccak256(abi.encodePacked("PAYMENTS_BOOK"))
bytes32 internal constant MODULE_ID_PAYMENTS_BOOK = 0xfa275b1417437a2a2ea8e91e9fe73c28eaf0a28532a250541da5ac0d1892b418;
// Treasury module ID - keccak256(abi.encodePacked("TREASURY"))
bytes32 internal constant MODULE_ID_TREASURY = 0x06aa03964db1f7257357ef09714a5f0ca3633723df419e97015e0c7a3e83edb7;
}
interface IModulesLinker {
/**
* @notice Update the implementations of a list of modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external;
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/lib/math/SafeMath64.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
/**
* @title SafeMath64
* @dev Math operations for uint64 with safety checks that revert on error
*/
library SafeMath64 {
string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW";
string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW";
string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW";
string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO";
/**
* @dev Multiplies two numbers, reverts on overflow.
*/
function mul(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint256 c = uint256(_a) * uint256(_b);
require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way)
return uint64(c);
}
/**
* @dev Integer division of two numbers truncating the quotient, reverts on division by zero.
*/
function div(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0
uint64 c = _a / _b;
// assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint64 _a, uint64 _b) internal pure returns (uint64) {
require(_b <= _a, ERROR_SUB_UNDERFLOW);
uint64 c = _a - _b;
return c;
}
/**
* @dev Adds two numbers, reverts on overflow.
*/
function add(uint64 _a, uint64 _b) internal pure returns (uint64) {
uint64 c = _a + _b;
require(c >= _a, ERROR_ADD_OVERFLOW);
return c;
}
/**
* @dev Divides two numbers and returns the remainder (unsigned integer modulo),
* reverts when dividing by zero.
*/
function mod(uint64 a, uint64 b) internal pure returns (uint64) {
require(b != 0, ERROR_DIV_ZERO);
return a % b;
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/Uint256Helpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
library Uint256Helpers {
uint256 private constant MAX_UINT8 = uint8(-1);
uint256 private constant MAX_UINT64 = uint64(-1);
string private constant ERROR_UINT8_NUMBER_TOO_BIG = "UINT8_NUMBER_TOO_BIG";
string private constant ERROR_UINT64_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG";
function toUint8(uint256 a) internal pure returns (uint8) {
require(a <= MAX_UINT8, ERROR_UINT8_NUMBER_TOO_BIG);
return uint8(a);
}
function toUint64(uint256 a) internal pure returns (uint64) {
require(a <= MAX_UINT64, ERROR_UINT64_NUMBER_TOO_BIG);
return uint64(a);
}
}
// Brought from https://github.com/aragon/aragonOS/blob/v4.3.0/contracts/common/TimeHelpers.sol
// Adapted to use pragma ^0.5.17 and satisfy our linter rules
contract TimeHelpers {
using Uint256Helpers for uint256;
/**
* @dev Returns the current block number.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber() internal view returns (uint256) {
return block.number;
}
/**
* @dev Returns the current block number, converted to uint64.
* Using a function rather than `block.number` allows us to easily mock the block number in
* tests.
*/
function getBlockNumber64() internal view returns (uint64) {
return getBlockNumber().toUint64();
}
/**
* @dev Returns the current timestamp.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp() internal view returns (uint256) {
return block.timestamp; // solium-disable-line security/no-block-members
}
/**
* @dev Returns the current timestamp, converted to uint64.
* Using a function rather than `block.timestamp` allows us to easily mock it in
* tests.
*/
function getTimestamp64() internal view returns (uint64) {
return getTimestamp().toUint64();
}
}
interface IClock {
/**
* @dev Ensure that the current term of the clock is up-to-date
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64);
/**
* @dev Transition up to a certain number of terms to leave the clock up-to-date
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64);
/**
* @dev Ensure that a certain term has its randomness set
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32);
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64);
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64);
/**
* @dev Tell the number of terms the clock should transition to be up-to-date
* @return Number of terms the clock should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64);
/**
* @dev Tell the information related to a term based on its ID
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness);
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view returns (bytes32);
}
contract CourtClock is IClock, TimeHelpers {
using SafeMath64 for uint64;
string private constant ERROR_TERM_DOES_NOT_EXIST = "CLK_TERM_DOES_NOT_EXIST";
string private constant ERROR_TERM_DURATION_TOO_LONG = "CLK_TERM_DURATION_TOO_LONG";
string private constant ERROR_TERM_RANDOMNESS_NOT_YET = "CLK_TERM_RANDOMNESS_NOT_YET";
string private constant ERROR_TERM_RANDOMNESS_UNAVAILABLE = "CLK_TERM_RANDOMNESS_UNAVAILABLE";
string private constant ERROR_BAD_FIRST_TERM_START_TIME = "CLK_BAD_FIRST_TERM_START_TIME";
string private constant ERROR_TOO_MANY_TRANSITIONS = "CLK_TOO_MANY_TRANSITIONS";
string private constant ERROR_INVALID_TRANSITION_TERMS = "CLK_INVALID_TRANSITION_TERMS";
string private constant ERROR_CANNOT_DELAY_STARTED_COURT = "CLK_CANNOT_DELAY_STARTED_PROT";
string private constant ERROR_CANNOT_DELAY_PAST_START_TIME = "CLK_CANNOT_DELAY_PAST_START_TIME";
// Maximum number of term transitions a callee may have to assume in order to call certain functions that require the Court being up-to-date
uint64 internal constant MAX_AUTO_TERM_TRANSITIONS_ALLOWED = 1;
// Max duration in seconds that a term can last
uint64 internal constant MAX_TERM_DURATION = 365 days;
// Max time until first term starts since contract is deployed
uint64 internal constant MAX_FIRST_TERM_DELAY_PERIOD = 2 * MAX_TERM_DURATION;
struct Term {
uint64 startTime; // Timestamp when the term started
uint64 randomnessBN; // Block number for entropy
bytes32 randomness; // Entropy from randomnessBN block hash
}
// Duration in seconds for each term of the Court
uint64 private termDuration;
// Last ensured term id
uint64 private termId;
// List of Court terms indexed by id
mapping (uint64 => Term) private terms;
event Heartbeat(uint64 previousTermId, uint64 currentTermId);
event StartTimeDelayed(uint64 previousStartTime, uint64 currentStartTime);
/**
* @dev Ensure a certain term has already been processed
* @param _termId Identification number of the term to be checked
*/
modifier termExists(uint64 _termId) {
require(_termId <= termId, ERROR_TERM_DOES_NOT_EXIST);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
*/
constructor(uint64[2] memory _termParams) public {
uint64 _termDuration = _termParams[0];
uint64 _firstTermStartTime = _termParams[1];
require(_termDuration < MAX_TERM_DURATION, ERROR_TERM_DURATION_TOO_LONG);
require(_firstTermStartTime >= getTimestamp64() + _termDuration, ERROR_BAD_FIRST_TERM_START_TIME);
require(_firstTermStartTime <= getTimestamp64() + MAX_FIRST_TERM_DELAY_PERIOD, ERROR_BAD_FIRST_TERM_START_TIME);
termDuration = _termDuration;
// No need for SafeMath: we already checked values above
terms[0].startTime = _firstTermStartTime - _termDuration;
}
/**
* @notice Ensure that the current term of the Court is up-to-date. If the Court is outdated by more than `MAX_AUTO_TERM_TRANSITIONS_ALLOWED`
* terms, the heartbeat function must be called manually instead.
* @return Identification number of the current term
*/
function ensureCurrentTerm() external returns (uint64) {
return _ensureCurrentTerm();
}
/**
* @notice Transition up to `_maxRequestedTransitions` terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the term ID after executing the heartbeat transitions
*/
function heartbeat(uint64 _maxRequestedTransitions) external returns (uint64) {
return _heartbeat(_maxRequestedTransitions);
}
/**
* @notice Ensure that a certain term has its randomness set. As we allow to draft disputes requested for previous terms, if there
* were mined more than 256 blocks for the current term, the blockhash of its randomness BN is no longer available, given
* round will be able to be drafted in the following term.
* @return Randomness of the current term
*/
function ensureCurrentTermRandomness() external returns (bytes32) {
// If the randomness for the given term was already computed, return
uint64 currentTermId = termId;
Term storage term = terms[currentTermId];
bytes32 termRandomness = term.randomness;
if (termRandomness != bytes32(0)) {
return termRandomness;
}
// Compute term randomness
bytes32 newRandomness = _computeTermRandomness(currentTermId);
require(newRandomness != bytes32(0), ERROR_TERM_RANDOMNESS_UNAVAILABLE);
term.randomness = newRandomness;
return newRandomness;
}
/**
* @dev Tell the term duration of the Court
* @return Duration in seconds of the Court term
*/
function getTermDuration() external view returns (uint64) {
return termDuration;
}
/**
* @dev Tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function getLastEnsuredTermId() external view returns (uint64) {
return _lastEnsuredTermId();
}
/**
* @dev Tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function getCurrentTermId() external view returns (uint64) {
return _currentTermId();
}
/**
* @dev Tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function getNeededTermTransitions() external view returns (uint64) {
return _neededTermTransitions();
}
/**
* @dev Tell the information related to a term based on its ID. Note that if the term has not been reached, the
* information returned won't be computed yet. This function allows querying future terms that were not computed yet.
* @param _termId ID of the term being queried
* @return startTime Term start time
* @return randomnessBN Block number used for randomness in the requested term
* @return randomness Randomness computed for the requested term
*/
function getTerm(uint64 _termId) external view returns (uint64 startTime, uint64 randomnessBN, bytes32 randomness) {
Term storage term = terms[_termId];
return (term.startTime, term.randomnessBN, term.randomness);
}
/**
* @dev Tell the randomness of a term even if it wasn't computed yet
* @param _termId Identification number of the term being queried
* @return Randomness of the requested term
*/
function getTermRandomness(uint64 _termId) external view termExists(_termId) returns (bytes32) {
return _computeTermRandomness(_termId);
}
/**
* @dev Internal function to ensure that the current term of the Court is up-to-date. If the Court is outdated by more than
* `MAX_AUTO_TERM_TRANSITIONS_ALLOWED` terms, the heartbeat function must be called manually.
* @return Identification number of the resultant term ID after executing the corresponding transitions
*/
function _ensureCurrentTerm() internal returns (uint64) {
// Check the required number of transitions does not exceeds the max allowed number to be processed automatically
uint64 requiredTransitions = _neededTermTransitions();
require(requiredTransitions <= MAX_AUTO_TERM_TRANSITIONS_ALLOWED, ERROR_TOO_MANY_TRANSITIONS);
// If there are no transitions pending, return the last ensured term id
if (uint256(requiredTransitions) == 0) {
return termId;
}
// Process transition if there is at least one pending
return _heartbeat(requiredTransitions);
}
/**
* @dev Internal function to transition the Court terms up to a requested number of terms
* @param _maxRequestedTransitions Max number of term transitions allowed by the sender
* @return Identification number of the resultant term ID after executing the requested transitions
*/
function _heartbeat(uint64 _maxRequestedTransitions) internal returns (uint64) {
// Transition the minimum number of terms between the amount requested and the amount actually needed
uint64 neededTransitions = _neededTermTransitions();
uint256 transitions = uint256(_maxRequestedTransitions < neededTransitions ? _maxRequestedTransitions : neededTransitions);
require(transitions > 0, ERROR_INVALID_TRANSITION_TERMS);
uint64 blockNumber = getBlockNumber64();
uint64 previousTermId = termId;
uint64 currentTermId = previousTermId;
for (uint256 transition = 1; transition <= transitions; transition++) {
// Term IDs are incremented by one based on the number of time periods since the Court started. Since time is represented in uint64,
// even if we chose the minimum duration possible for a term (1 second), we can ensure terms will never reach 2^64 since time is
// already assumed to fit in uint64.
Term storage previousTerm = terms[currentTermId++];
Term storage currentTerm = terms[currentTermId];
_onTermTransitioned(currentTermId);
// Set the start time of the new term. Note that we are using a constant term duration value to guarantee
// equally long terms, regardless of heartbeats.
currentTerm.startTime = previousTerm.startTime.add(termDuration);
// In order to draft a random number of guardians in a term, we use a randomness factor for each term based on a
// block number that is set once the term has started. Note that this information could not be known beforehand.
currentTerm.randomnessBN = blockNumber + 1;
}
termId = currentTermId;
emit Heartbeat(previousTermId, currentTermId);
return currentTermId;
}
/**
* @dev Internal function to delay the first term start time only if it wasn't reached yet
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function _delayStartTime(uint64 _newFirstTermStartTime) internal {
require(_currentTermId() == 0, ERROR_CANNOT_DELAY_STARTED_COURT);
Term storage term = terms[0];
uint64 currentFirstTermStartTime = term.startTime.add(termDuration);
require(_newFirstTermStartTime > currentFirstTermStartTime, ERROR_CANNOT_DELAY_PAST_START_TIME);
// No need for SafeMath: we already checked above that `_newFirstTermStartTime` > `currentFirstTermStartTime` >= `termDuration`
term.startTime = _newFirstTermStartTime - termDuration;
emit StartTimeDelayed(currentFirstTermStartTime, _newFirstTermStartTime);
}
/**
* @dev Internal function to notify when a term has been transitioned. This function must be overridden to provide custom behavior.
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal;
/**
* @dev Internal function to tell the last ensured term identification number
* @return Identification number of the last ensured term
*/
function _lastEnsuredTermId() internal view returns (uint64) {
return termId;
}
/**
* @dev Internal function to tell the current term identification number. Note that there may be pending term transitions.
* @return Identification number of the current term
*/
function _currentTermId() internal view returns (uint64) {
return termId.add(_neededTermTransitions());
}
/**
* @dev Internal function to tell the number of terms the Court should transition to be up-to-date
* @return Number of terms the Court should transition to be up-to-date
*/
function _neededTermTransitions() internal view returns (uint64) {
// Note that the Court is always initialized providing a start time for the first-term in the future. If that's the case,
// no term transitions are required.
uint64 currentTermStartTime = terms[termId].startTime;
if (getTimestamp64() < currentTermStartTime) {
return uint64(0);
}
// No need for SafeMath: we already know that the start time of the current term is in the past
return (getTimestamp64() - currentTermStartTime) / termDuration;
}
/**
* @dev Internal function to compute the randomness that will be used to draft guardians for the given term. This
* function assumes the given term exists. To determine the randomness factor for a term we use the hash of a
* block number that is set once the term has started to ensure it cannot be known beforehand. Note that the
* hash function being used only works for the 256 most recent block numbers.
* @param _termId Identification number of the term being queried
* @return Randomness computed for the given term
*/
function _computeTermRandomness(uint64 _termId) internal view returns (bytes32) {
Term storage term = terms[_termId];
require(getBlockNumber64() > term.randomnessBN, ERROR_TERM_RANDOMNESS_NOT_YET);
return blockhash(term.randomnessBN);
}
}
library PctHelpers {
using SafeMath for uint256;
uint256 internal constant PCT_BASE = 10000; // ‱ (1 / 10,000)
function isValid(uint16 _pct) internal pure returns (bool) {
return _pct <= PCT_BASE;
}
function pct(uint256 self, uint16 _pct) internal pure returns (uint256) {
return self.mul(uint256(_pct)) / PCT_BASE;
}
function pct256(uint256 self, uint256 _pct) internal pure returns (uint256) {
return self.mul(_pct) / PCT_BASE;
}
function pctIncrease(uint256 self, uint16 _pct) internal pure returns (uint256) {
// No need for SafeMath: for addition note that `PCT_BASE` is lower than (2^256 - 2^16)
return self.mul(PCT_BASE + uint256(_pct)) / PCT_BASE;
}
}
interface IConfig {
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
}
contract CourtConfigData {
struct Config {
FeesConfig fees; // Full fees-related config
DisputesConfig disputes; // Full disputes-related config
uint256 minActiveBalance; // Minimum amount of tokens guardians have to activate to participate in the Court
}
struct FeesConfig {
IERC20 token; // ERC20 token to be used for the fees of the Court
uint16 finalRoundReduction; // Permyriad of fees reduction applied for final appeal round (‱ - 1/10,000)
uint256 guardianFee; // Amount of tokens paid to draft a guardian to adjudicate a dispute
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
uint256 settleFee; // Amount of tokens paid per round to cover the costs of slashing guardians
}
struct DisputesConfig {
uint64 evidenceTerms; // Max submitting evidence period duration in terms
uint64 commitTerms; // Committing period duration in terms
uint64 revealTerms; // Revealing period duration in terms
uint64 appealTerms; // Appealing period duration in terms
uint64 appealConfirmTerms; // Confirmation appeal period duration in terms
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint64 firstRoundGuardiansNumber; // Number of guardians drafted on first round
uint64 appealStepFactor; // Factor in which the guardians number is increased on each appeal
uint64 finalRoundLockTerms; // Period a coherent guardian in the final round will remain locked
uint256 maxRegularAppealRounds; // Before the final appeal
uint256 appealCollateralFactor; // Permyriad multiple of dispute fees required to appeal a preliminary ruling (‱ - 1/10,000)
uint256 appealConfirmCollateralFactor; // Permyriad multiple of dispute fees required to confirm appeal (‱ - 1/10,000)
}
struct DraftConfig {
IERC20 feeToken; // ERC20 token to be used for the fees of the Court
uint16 penaltyPct; // Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
uint256 draftFee; // Amount of tokens paid per round to cover the costs of drafting guardians
}
}
contract CourtConfig is IConfig, CourtConfigData {
using SafeMath64 for uint64;
using PctHelpers for uint256;
string private constant ERROR_TOO_OLD_TERM = "CONF_TOO_OLD_TERM";
string private constant ERROR_INVALID_PENALTY_PCT = "CONF_INVALID_PENALTY_PCT";
string private constant ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT = "CONF_INVALID_FINAL_ROUND_RED_PCT";
string private constant ERROR_INVALID_MAX_APPEAL_ROUNDS = "CONF_INVALID_MAX_APPEAL_ROUNDS";
string private constant ERROR_LARGE_ROUND_PHASE_DURATION = "CONF_LARGE_ROUND_PHASE_DURATION";
string private constant ERROR_BAD_INITIAL_GUARDIANS_NUMBER = "CONF_BAD_INITIAL_GUARDIAN_NUMBER";
string private constant ERROR_BAD_APPEAL_STEP_FACTOR = "CONF_BAD_APPEAL_STEP_FACTOR";
string private constant ERROR_ZERO_COLLATERAL_FACTOR = "CONF_ZERO_COLLATERAL_FACTOR";
string private constant ERROR_ZERO_MIN_ACTIVE_BALANCE = "CONF_ZERO_MIN_ACTIVE_BALANCE";
// Max number of terms that each of the different adjudication states can last (if lasted 1h, this would be a year)
uint64 internal constant MAX_ADJ_STATE_DURATION = 8670;
// Cap the max number of regular appeal rounds
uint256 internal constant MAX_REGULAR_APPEAL_ROUNDS_LIMIT = 10;
// Future term ID in which a config change has been scheduled
uint64 private configChangeTermId;
// List of all the configs used in the Court
Config[] private configs;
// List of configs indexed by id
mapping (uint64 => uint256) private configIdByTerm;
event NewConfig(uint64 fromTermId, uint64 courtConfigId);
/**
* @dev Constructor function
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
{
// Leave config at index 0 empty for non-scheduled config changes
configs.length = 1;
_setConfig(
0,
0,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
);
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct);
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256);
/**
* @dev Tell the term identification number of the next scheduled config change
* @return Term identification number of the next scheduled config change
*/
function getConfigChangeTermId() external view returns (uint64) {
return configChangeTermId;
}
/**
* @dev Internal to make sure to set a config for the new term, it will copy the previous term config if none
* @param _termId Identification number of the new current term that has been transitioned
*/
function _ensureTermConfig(uint64 _termId) internal {
// If the term being transitioned had no config change scheduled, keep the previous one
uint256 currentConfigId = configIdByTerm[_termId];
if (currentConfigId == 0) {
uint256 previousConfigId = configIdByTerm[_termId.sub(1)];
configIdByTerm[_termId] = previousConfigId;
}
}
/**
* @dev Assumes that sender it's allowed (either it's from governor or it's on init)
* @param _termId Identification number of the current Court term
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees.
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _setConfig(
uint64 _termId,
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
internal
{
// If the current term is not zero, changes must be scheduled at least after the current period.
// No need to ensure delays for on-going disputes since these already use their creation term for that.
require(_termId == 0 || _fromTermId > _termId, ERROR_TOO_OLD_TERM);
// Make sure appeal collateral factors are greater than zero
require(_appealCollateralParams[0] > 0 && _appealCollateralParams[1] > 0, ERROR_ZERO_COLLATERAL_FACTOR);
// Make sure the given penalty and final round reduction pcts are not greater than 100%
require(PctHelpers.isValid(_pcts[0]), ERROR_INVALID_PENALTY_PCT);
require(PctHelpers.isValid(_pcts[1]), ERROR_INVALID_FINAL_ROUND_REDUCTION_PCT);
// Disputes must request at least one guardian to be drafted initially
require(_roundParams[0] > 0, ERROR_BAD_INITIAL_GUARDIANS_NUMBER);
// Prevent that further rounds have zero guardians
require(_roundParams[1] > 0, ERROR_BAD_APPEAL_STEP_FACTOR);
// Make sure the max number of appeals allowed does not reach the limit
uint256 _maxRegularAppealRounds = _roundParams[2];
bool isMaxAppealRoundsValid = _maxRegularAppealRounds > 0 && _maxRegularAppealRounds <= MAX_REGULAR_APPEAL_ROUNDS_LIMIT;
require(isMaxAppealRoundsValid, ERROR_INVALID_MAX_APPEAL_ROUNDS);
// Make sure each adjudication round phase duration is valid
for (uint i = 0; i < _roundStateDurations.length; i++) {
require(_roundStateDurations[i] > 0 && _roundStateDurations[i] < MAX_ADJ_STATE_DURATION, ERROR_LARGE_ROUND_PHASE_DURATION);
}
// Make sure min active balance is not zero
require(_minActiveBalance > 0, ERROR_ZERO_MIN_ACTIVE_BALANCE);
// If there was a config change already scheduled, reset it (in that case we will overwrite last array item).
// Otherwise, schedule a new config.
if (configChangeTermId > _termId) {
configIdByTerm[configChangeTermId] = 0;
} else {
configs.length++;
}
uint64 courtConfigId = uint64(configs.length - 1);
Config storage config = configs[courtConfigId];
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _maxRegularAppealRounds,
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
configIdByTerm[_fromTermId] = courtConfigId;
configChangeTermId = _fromTermId;
emit NewConfig(_fromTermId, courtConfigId);
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
* @return minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function _getConfigAt(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
FeesConfig storage feesConfig = config.fees;
feeToken = feesConfig.token;
fees = [feesConfig.guardianFee, feesConfig.draftFee, feesConfig.settleFee];
DisputesConfig storage disputesConfig = config.disputes;
roundStateDurations = [
disputesConfig.evidenceTerms,
disputesConfig.commitTerms,
disputesConfig.revealTerms,
disputesConfig.appealTerms,
disputesConfig.appealConfirmTerms
];
pcts = [disputesConfig.penaltyPct, feesConfig.finalRoundReduction];
roundParams = [
disputesConfig.firstRoundGuardiansNumber,
disputesConfig.appealStepFactor,
uint64(disputesConfig.maxRegularAppealRounds),
disputesConfig.finalRoundLockTerms
];
appealCollateralParams = [disputesConfig.appealCollateralFactor, disputesConfig.appealConfirmCollateralFactor];
minActiveBalance = config.minActiveBalance;
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function _getDraftConfig(uint64 _termId, uint64 _lastEnsuredTermId) internal view
returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct)
{
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return (config.fees.token, config.fees.draftFee, config.disputes.penaltyPct);
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Minimum amount of guardian tokens that can be activated at the given term
*/
function _getMinActiveBalance(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
Config storage config = _getConfigFor(_termId, _lastEnsuredTermId);
return config.minActiveBalance;
}
/**
* @dev Internal function to get the Court config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Court config for the given term
*/
function _getConfigFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (Config storage) {
uint256 id = _getConfigIdFor(_termId, _lastEnsuredTermId);
return configs[id];
}
/**
* @dev Internal function to get the Court config ID for a given term
* @param _termId Identification number of the term querying the Court config of
* @param _lastEnsuredTermId Identification number of the last ensured term of the Court
* @return Identification number of the config for the given terms
*/
function _getConfigIdFor(uint64 _termId, uint64 _lastEnsuredTermId) internal view returns (uint256) {
// If the given term is lower or equal to the last ensured Court term, it is safe to use a past Court config
if (_termId <= _lastEnsuredTermId) {
return configIdByTerm[_termId];
}
// If the given term is in the future but there is a config change scheduled before it, use the incoming config
uint64 scheduledChangeTermId = configChangeTermId;
if (scheduledChangeTermId <= _termId) {
return configIdByTerm[scheduledChangeTermId];
}
// If no changes are scheduled, use the Court config of the last ensured term
return configIdByTerm[_lastEnsuredTermId];
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface IArbitrator {
/**
* @dev Create a dispute over the Arbitrable sender with a number of possible rulings
* @param _possibleRulings Number of possible rulings allowed for the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(uint256 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _disputeId Id of the dispute in the Court
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence related to the dispute
*/
function submitEvidence(uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(uint256 _disputeId) external;
/**
* @notice Rule dispute #`_disputeId` if ready
* @param _disputeId Identification number of the dispute to be ruled
* @return subject Subject associated to the dispute
* @return ruling Ruling number computed for the given dispute
*/
function rule(uint256 _disputeId) external returns (address subject, uint256 ruling);
/**
* @dev Tell the dispute fees information to create a dispute
* @return recipient Address where the corresponding dispute fees must be transferred to
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees that must be allowed to the recipient
*/
function getDisputeFees() external view returns (address recipient, IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell the payments recipient address
* @return Address of the payments recipient module
*/
function getPaymentsRecipient() external view returns (address);
}
/*
* SPDX-License-Identifier: MIT
*/
/**
* @dev The Arbitrable instances actually don't require to follow any specific interface.
* Note that this is actually optional, although it does allow the Court to at least have a way to identify a specific set of instances.
*/
contract IArbitrable {
/**
* @dev Emitted when an IArbitrable instance's dispute is ruled by an IArbitrator
* @param arbitrator IArbitrator instance ruling the dispute
* @param disputeId Identification number of the dispute being ruled by the arbitrator
* @param ruling Ruling given by the arbitrator
*/
event Ruled(IArbitrator indexed arbitrator, uint256 indexed disputeId, uint256 ruling);
}
interface IDisputeManager {
enum DisputeState {
PreDraft,
Adjudicating,
Ruled
}
enum AdjudicationState {
Invalid,
Committing,
Revealing,
Appealing,
ConfirmingAppeal,
Ended
}
/**
* @dev Create a dispute to be drafted in a future term
* @param _subject Arbitrable instance creating the dispute
* @param _possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @param _metadata Optional metadata that can be used to provide additional information on the dispute to be created
* @return Dispute identification number
*/
function createDispute(IArbitrable _subject, uint8 _possibleRulings, bytes calldata _metadata) external returns (uint256);
/**
* @dev Submit evidence for a dispute
* @param _subject Arbitrable instance submitting the dispute
* @param _disputeId Identification number of the dispute receiving new evidence
* @param _submitter Address of the account submitting the evidence
* @param _evidence Data submitted for the evidence of the dispute
*/
function submitEvidence(IArbitrable _subject, uint256 _disputeId, address _submitter, bytes calldata _evidence) external;
/**
* @dev Close the evidence period of a dispute
* @param _subject IArbitrable instance requesting to close the evidence submission period
* @param _disputeId Identification number of the dispute to close its evidence submitting period
*/
function closeEvidencePeriod(IArbitrable _subject, uint256 _disputeId) external;
/**
* @dev Draft guardians for the next round of a dispute
* @param _disputeId Identification number of the dispute to be drafted
*/
function draft(uint256 _disputeId) external;
/**
* @dev Appeal round of a dispute in favor of a certain ruling
* @param _disputeId Identification number of the dispute being appealed
* @param _roundId Identification number of the dispute round being appealed
* @param _ruling Ruling appealing a dispute round in favor of
*/
function createAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Confirm appeal for a round of a dispute in favor of a ruling
* @param _disputeId Identification number of the dispute confirming an appeal of
* @param _roundId Identification number of the dispute round confirming an appeal of
* @param _ruling Ruling being confirmed against a dispute round appeal
*/
function confirmAppeal(uint256 _disputeId, uint256 _roundId, uint8 _ruling) external;
/**
* @dev Compute the final ruling for a dispute
* @param _disputeId Identification number of the dispute to compute its final ruling
* @return subject Arbitrable instance associated to the dispute
* @return finalRuling Final ruling decided for the given dispute
*/
function computeRuling(uint256 _disputeId) external returns (IArbitrable subject, uint8 finalRuling);
/**
* @dev Settle penalties for a round of a dispute
* @param _disputeId Identification number of the dispute to settle penalties for
* @param _roundId Identification number of the dispute round to settle penalties for
* @param _guardiansToSettle Maximum number of guardians to be slashed in this call
*/
function settlePenalties(uint256 _disputeId, uint256 _roundId, uint256 _guardiansToSettle) external;
/**
* @dev Claim rewards for a round of a dispute for guardian
* @dev For regular rounds, it will only reward winning guardians
* @param _disputeId Identification number of the dispute to settle rewards for
* @param _roundId Identification number of the dispute round to settle rewards for
* @param _guardian Address of the guardian to settle their rewards
*/
function settleReward(uint256 _disputeId, uint256 _roundId, address _guardian) external;
/**
* @dev Settle appeal deposits for a round of a dispute
* @param _disputeId Identification number of the dispute to settle appeal deposits for
* @param _roundId Identification number of the dispute round to settle appeal deposits for
*/
function settleAppealDeposit(uint256 _disputeId, uint256 _roundId) external;
/**
* @dev Tell the amount of token fees required to create a dispute
* @return feeToken ERC20 token used for the fees
* @return feeAmount Total amount of fees to be paid for a dispute at the given term
*/
function getDisputeFees() external view returns (IERC20 feeToken, uint256 feeAmount);
/**
* @dev Tell information of a certain dispute
* @param _disputeId Identification number of the dispute being queried
* @return subject Arbitrable subject being disputed
* @return possibleRulings Number of possible rulings allowed for the drafted guardians to vote on the dispute
* @return state Current state of the dispute being queried: pre-draft, adjudicating, or ruled
* @return finalRuling The winning ruling in case the dispute is finished
* @return lastRoundId Identification number of the last round created for the dispute
* @return createTermId Identification number of the term when the dispute was created
*/
function getDispute(uint256 _disputeId) external view
returns (IArbitrable subject, uint8 possibleRulings, DisputeState state, uint8 finalRuling, uint256 lastRoundId, uint64 createTermId);
/**
* @dev Tell information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return draftTerm Term from which the requested round can be drafted
* @return delayedTerms Number of terms the given round was delayed based on its requested draft term id
* @return guardiansNumber Number of guardians requested for the round
* @return selectedGuardians Number of guardians already selected for the requested round
* @return settledPenalties Whether or not penalties have been settled for the requested round
* @return collectedTokens Amount of guardian tokens that were collected from slashed guardians for the requested round
* @return coherentGuardians Number of guardians that voted in favor of the final ruling in the requested round
* @return state Adjudication state of the requested round
*/
function getRound(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 draftTerm,
uint64 delayedTerms,
uint64 guardiansNumber,
uint64 selectedGuardians,
uint256 guardianFees,
bool settledPenalties,
uint256 collectedTokens,
uint64 coherentGuardians,
AdjudicationState state
);
/**
* @dev Tell appeal-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @return maker Address of the account appealing the given round
* @return appealedRuling Ruling confirmed by the appealer of the given round
* @return taker Address of the account confirming the appeal of the given round
* @return opposedRuling Ruling confirmed by the appeal taker of the given round
*/
function getAppeal(uint256 _disputeId, uint256 _roundId) external view
returns (address maker, uint64 appealedRuling, address taker, uint64 opposedRuling);
/**
* @dev Tell information related to the next round due to an appeal of a certain round given.
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round requesting the appeal details of
* @return nextRoundStartTerm Term ID from which the next round will start
* @return nextRoundGuardiansNumber Guardians number for the next round
* @return newDisputeState New state for the dispute associated to the given round after the appeal
* @return feeToken ERC20 token used for the next round fees
* @return guardianFees Total amount of fees to be distributed between the winning guardians of the next round
* @return totalFees Total amount of fees for a regular round at the given term
* @return appealDeposit Amount to be deposit of fees for a regular round at the given term
* @return confirmAppealDeposit Total amount of fees for a regular round at the given term
*/
function getNextRoundDetails(uint256 _disputeId, uint256 _roundId) external view
returns (
uint64 nextRoundStartTerm,
uint64 nextRoundGuardiansNumber,
DisputeState newDisputeState,
IERC20 feeToken,
uint256 totalFees,
uint256 guardianFees,
uint256 appealDeposit,
uint256 confirmAppealDeposit
);
/**
* @dev Tell guardian-related information of a certain adjudication round
* @param _disputeId Identification number of the dispute being queried
* @param _roundId Identification number of the round being queried
* @param _guardian Address of the guardian being queried
* @return weight Guardian weight drafted for the requested round
* @return rewarded Whether or not the given guardian was rewarded based on the requested round
*/
function getGuardian(uint256 _disputeId, uint256 _roundId, address _guardian) external view returns (uint64 weight, bool rewarded);
}
contract Controller is IsContract, ModuleIds, CourtClock, CourtConfig, ACL {
string private constant ERROR_SENDER_NOT_GOVERNOR = "CTR_SENDER_NOT_GOVERNOR";
string private constant ERROR_INVALID_GOVERNOR_ADDRESS = "CTR_INVALID_GOVERNOR_ADDRESS";
string private constant ERROR_MODULE_NOT_SET = "CTR_MODULE_NOT_SET";
string private constant ERROR_MODULE_ALREADY_ENABLED = "CTR_MODULE_ALREADY_ENABLED";
string private constant ERROR_MODULE_ALREADY_DISABLED = "CTR_MODULE_ALREADY_DISABLED";
string private constant ERROR_DISPUTE_MANAGER_NOT_ACTIVE = "CTR_DISPUTE_MANAGER_NOT_ACTIVE";
string private constant ERROR_CUSTOM_FUNCTION_NOT_SET = "CTR_CUSTOM_FUNCTION_NOT_SET";
string private constant ERROR_IMPLEMENTATION_NOT_CONTRACT = "CTR_IMPLEMENTATION_NOT_CONTRACT";
string private constant ERROR_INVALID_IMPLS_INPUT_LENGTH = "CTR_INVALID_IMPLS_INPUT_LENGTH";
address private constant ZERO_ADDRESS = address(0);
/**
* @dev Governor of the whole system. Set of three addresses to recover funds, change configuration settings and setup modules
*/
struct Governor {
address funds; // This address can be unset at any time. It is allowed to recover funds from the ControlledRecoverable modules
address config; // This address is meant not to be unset. It is allowed to change the different configurations of the whole system
address modules; // This address can be unset at any time. It is allowed to plug/unplug modules from the system
}
/**
* @dev Module information
*/
struct Module {
bytes32 id; // ID associated to a module
bool disabled; // Whether the module is disabled
}
// Governor addresses of the system
Governor private governor;
// List of current modules registered for the system indexed by ID
mapping (bytes32 => address) internal currentModules;
// List of all historical modules registered for the system indexed by address
mapping (address => Module) internal allModules;
// List of custom function targets indexed by signature
mapping (bytes4 => address) internal customFunctions;
event ModuleSet(bytes32 id, address addr);
event ModuleEnabled(bytes32 id, address addr);
event ModuleDisabled(bytes32 id, address addr);
event CustomFunctionSet(bytes4 signature, address target);
event FundsGovernorChanged(address previousGovernor, address currentGovernor);
event ConfigGovernorChanged(address previousGovernor, address currentGovernor);
event ModulesGovernorChanged(address previousGovernor, address currentGovernor);
/**
* @dev Ensure the msg.sender is the funds governor
*/
modifier onlyFundsGovernor {
require(msg.sender == governor.funds, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyConfigGovernor {
require(msg.sender == governor.config, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the modules governor
*/
modifier onlyModulesGovernor {
require(msg.sender == governor.modules, ERROR_SENDER_NOT_GOVERNOR);
_;
}
/**
* @dev Ensure the given dispute manager is active
*/
modifier onlyActiveDisputeManager(IDisputeManager _disputeManager) {
require(!_isModuleDisabled(address(_disputeManager)), ERROR_DISPUTE_MANAGER_NOT_ACTIVE);
_;
}
/**
* @dev Constructor function
* @param _termParams Array containing:
* 0. _termDuration Duration in seconds per term
* 1. _firstTermStartTime Timestamp in seconds when the court will open (to give time for guardian on-boarding)
* @param _governors Array containing:
* 0. _fundsGovernor Address of the funds governor
* 1. _configGovernor Address of the config governor
* 2. _modulesGovernor Address of the modules governor
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
constructor(
uint64[2] memory _termParams,
address[3] memory _governors,
IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance
)
public
CourtClock(_termParams)
CourtConfig(_feeToken, _fees, _roundStateDurations, _pcts, _roundParams, _appealCollateralParams, _minActiveBalance)
{
_setFundsGovernor(_governors[0]);
_setConfigGovernor(_governors[1]);
_setModulesGovernor(_governors[2]);
}
/**
* @dev Fallback function allows to forward calls to a specific address in case it was previously registered
* Note the sender will be always the controller in case it is forwarded
*/
function () external payable {
address target = customFunctions[msg.sig];
require(target != address(0), ERROR_CUSTOM_FUNCTION_NOT_SET);
// solium-disable-next-line security/no-call-value
(bool success,) = address(target).call.value(msg.value)(msg.data);
assembly {
let size := returndatasize
let ptr := mload(0x40)
returndatacopy(ptr, 0, size)
let result := success
switch result case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
/**
* @notice Change Court configuration params
* @param _fromTermId Identification number of the term in which the config will be effective at
* @param _feeToken Address of the token contract that is used to pay for fees
* @param _fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @param _roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @param _pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked to each drafted guardians (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @param _roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @param _appealCollateralParams Array containing params for appeal collateral:
* 1. appealCollateralFactor Permyriad multiple of dispute fees required to appeal a preliminary ruling
* 2. appealConfirmCollateralFactor Permyriad multiple of dispute fees required to confirm appeal
* @param _minActiveBalance Minimum amount of guardian tokens that can be activated
*/
function setConfig(
uint64 _fromTermId,
IERC20 _feeToken,
uint256[3] calldata _fees,
uint64[5] calldata _roundStateDurations,
uint16[2] calldata _pcts,
uint64[4] calldata _roundParams,
uint256[2] calldata _appealCollateralParams,
uint256 _minActiveBalance
)
external
onlyConfigGovernor
{
uint64 currentTermId = _ensureCurrentTerm();
_setConfig(
currentTermId,
_fromTermId,
_feeToken,
_fees,
_roundStateDurations,
_pcts,
_roundParams,
_appealCollateralParams,
_minActiveBalance
);
}
/**
* @notice Delay the Court start time to `_newFirstTermStartTime`
* @param _newFirstTermStartTime New timestamp in seconds when the court will open
*/
function delayStartTime(uint64 _newFirstTermStartTime) external onlyConfigGovernor {
_delayStartTime(_newFirstTermStartTime);
}
/**
* @notice Change funds governor address to `_newFundsGovernor`
* @param _newFundsGovernor Address of the new funds governor to be set
*/
function changeFundsGovernor(address _newFundsGovernor) external onlyFundsGovernor {
require(_newFundsGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setFundsGovernor(_newFundsGovernor);
}
/**
* @notice Change config governor address to `_newConfigGovernor`
* @param _newConfigGovernor Address of the new config governor to be set
*/
function changeConfigGovernor(address _newConfigGovernor) external onlyConfigGovernor {
require(_newConfigGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setConfigGovernor(_newConfigGovernor);
}
/**
* @notice Change modules governor address to `_newModulesGovernor`
* @param _newModulesGovernor Address of the new governor to be set
*/
function changeModulesGovernor(address _newModulesGovernor) external onlyModulesGovernor {
require(_newModulesGovernor != ZERO_ADDRESS, ERROR_INVALID_GOVERNOR_ADDRESS);
_setModulesGovernor(_newModulesGovernor);
}
/**
* @notice Remove the funds governor. Set the funds governor to the zero address.
* @dev This action cannot be rolled back, once the funds governor has been unset, funds cannot be recovered from recoverable modules anymore
*/
function ejectFundsGovernor() external onlyFundsGovernor {
_setFundsGovernor(ZERO_ADDRESS);
}
/**
* @notice Remove the modules governor. Set the modules governor to the zero address.
* @dev This action cannot be rolled back, once the modules governor has been unset, system modules cannot be changed anymore
*/
function ejectModulesGovernor() external onlyModulesGovernor {
_setModulesGovernor(ZERO_ADDRESS);
}
/**
* @notice Grant `_id` role to `_who`
* @param _id ID of the role to be granted
* @param _who Address to grant the role to
*/
function grant(bytes32 _id, address _who) external onlyConfigGovernor {
_grant(_id, _who);
}
/**
* @notice Revoke `_id` role from `_who`
* @param _id ID of the role to be revoked
* @param _who Address to revoke the role from
*/
function revoke(bytes32 _id, address _who) external onlyConfigGovernor {
_revoke(_id, _who);
}
/**
* @notice Freeze `_id` role
* @param _id ID of the role to be frozen
*/
function freeze(bytes32 _id) external onlyConfigGovernor {
_freeze(_id);
}
/**
* @notice Enact a bulk list of ACL operations
*/
function bulk(BulkOp[] calldata _op, bytes32[] calldata _id, address[] calldata _who) external onlyConfigGovernor {
_bulk(_op, _id, _who);
}
/**
* @notice Set module `_id` to `_addr`
* @param _id ID of the module to be set
* @param _addr Address of the module to be set
*/
function setModule(bytes32 _id, address _addr) external onlyModulesGovernor {
_setModule(_id, _addr);
}
/**
* @notice Set and link many modules at once
* @param _newModuleIds List of IDs of the new modules to be set
* @param _newModuleAddresses List of addresses of the new modules to be set
* @param _newModuleLinks List of IDs of the modules that will be linked in the new modules being set
* @param _currentModulesToBeSynced List of addresses of current modules to be re-linked to the new modules being set
*/
function setModules(
bytes32[] calldata _newModuleIds,
address[] calldata _newModuleAddresses,
bytes32[] calldata _newModuleLinks,
address[] calldata _currentModulesToBeSynced
)
external
onlyModulesGovernor
{
// We only care about the modules being set, links are optional
require(_newModuleIds.length == _newModuleAddresses.length, ERROR_INVALID_IMPLS_INPUT_LENGTH);
// First set the addresses of the new modules or the modules to be updated
for (uint256 i = 0; i < _newModuleIds.length; i++) {
_setModule(_newModuleIds[i], _newModuleAddresses[i]);
}
// Then sync the links of the new modules based on the list of IDs specified (ideally the IDs of their dependencies)
_syncModuleLinks(_newModuleAddresses, _newModuleLinks);
// Finally sync the links of the existing modules to be synced to the new modules being set
_syncModuleLinks(_currentModulesToBeSynced, _newModuleIds);
}
/**
* @notice Sync modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules included in the sync
*/
function syncModuleLinks(address[] calldata _modulesToBeSynced, bytes32[] calldata _idsToBeSet)
external
onlyModulesGovernor
{
require(_idsToBeSet.length > 0 && _modulesToBeSynced.length > 0, ERROR_INVALID_IMPLS_INPUT_LENGTH);
_syncModuleLinks(_modulesToBeSynced, _idsToBeSet);
}
/**
* @notice Disable module `_addr`
* @dev Current modules can be disabled to allow pausing the court. However, these can be enabled back again, see `enableModule`
* @param _addr Address of the module to be disabled
*/
function disableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(!module.disabled, ERROR_MODULE_ALREADY_DISABLED);
module.disabled = true;
emit ModuleDisabled(module.id, _addr);
}
/**
* @notice Enable module `_addr`
* @param _addr Address of the module to be enabled
*/
function enableModule(address _addr) external onlyModulesGovernor {
Module storage module = allModules[_addr];
_ensureModuleExists(module);
require(module.disabled, ERROR_MODULE_ALREADY_ENABLED);
module.disabled = false;
emit ModuleEnabled(module.id, _addr);
}
/**
* @notice Set custom function `_sig` for `_target`
* @param _sig Signature of the function to be set
* @param _target Address of the target implementation to be registered for the given signature
*/
function setCustomFunction(bytes4 _sig, address _target) external onlyModulesGovernor {
customFunctions[_sig] = _target;
emit CustomFunctionSet(_sig, _target);
}
/**
* @dev Tell the full Court configuration parameters at a certain term
* @param _termId Identification number of the term querying the Court config of
* @return token Address of the token used to pay for fees
* @return fees Array containing:
* 0. guardianFee Amount of fee tokens that is paid per guardian per dispute
* 1. draftFee Amount of fee tokens per guardian to cover the drafting cost
* 2. settleFee Amount of fee tokens per guardian to cover round settlement cost
* @return roundStateDurations Array containing the durations in terms of the different phases of a dispute:
* 0. evidenceTerms Max submitting evidence period duration in terms
* 1. commitTerms Commit period duration in terms
* 2. revealTerms Reveal period duration in terms
* 3. appealTerms Appeal period duration in terms
* 4. appealConfirmationTerms Appeal confirmation period duration in terms
* @return pcts Array containing:
* 0. penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
* 1. finalRoundReduction Permyriad of fee reduction for the last appeal round (‱ - 1/10,000)
* @return roundParams Array containing params for rounds:
* 0. firstRoundGuardiansNumber Number of guardians to be drafted for the first round of disputes
* 1. appealStepFactor Increasing factor for the number of guardians of each round of a dispute
* 2. maxRegularAppealRounds Number of regular appeal rounds before the final round is triggered
* 3. finalRoundLockTerms Number of terms that a coherent guardian in a final round is disallowed to withdraw (to prevent 51% attacks)
* @return appealCollateralParams Array containing params for appeal collateral:
* 0. appealCollateralFactor Multiple of dispute fees required to appeal a preliminary ruling
* 1. appealConfirmCollateralFactor Multiple of dispute fees required to confirm appeal
*/
function getConfig(uint64 _termId) external view
returns (
IERC20 feeToken,
uint256[3] memory fees,
uint64[5] memory roundStateDurations,
uint16[2] memory pcts,
uint64[4] memory roundParams,
uint256[2] memory appealCollateralParams,
uint256 minActiveBalance
)
{
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getConfigAt(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the draft config at a certain term
* @param _termId Identification number of the term querying the draft config of
* @return feeToken Address of the token used to pay for fees
* @return draftFee Amount of fee tokens per guardian to cover the drafting cost
* @return penaltyPct Permyriad of min active tokens balance to be locked for each drafted guardian (‱ - 1/10,000)
*/
function getDraftConfig(uint64 _termId) external view returns (IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getDraftConfig(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the min active balance config at a certain term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of tokens guardians have to activate to participate in the Court
*/
function getMinActiveBalance(uint64 _termId) external view returns (uint256) {
uint64 lastEnsuredTermId = _lastEnsuredTermId();
return _getMinActiveBalance(_termId, lastEnsuredTermId);
}
/**
* @dev Tell the address of the funds governor
* @return Address of the funds governor
*/
function getFundsGovernor() external view returns (address) {
return governor.funds;
}
/**
* @dev Tell the address of the config governor
* @return Address of the config governor
*/
function getConfigGovernor() external view returns (address) {
return governor.config;
}
/**
* @dev Tell the address of the modules governor
* @return Address of the modules governor
*/
function getModulesGovernor() external view returns (address) {
return governor.modules;
}
/**
* @dev Tell if a given module is active
* @param _id ID of the module to be checked
* @param _addr Address of the module to be checked
* @return True if the given module address has the requested ID and is enabled
*/
function isActive(bytes32 _id, address _addr) external view returns (bool) {
Module storage module = allModules[_addr];
return module.id == _id && !module.disabled;
}
/**
* @dev Tell the current ID and disable status of a module based on a given address
* @param _addr Address of the requested module
* @return id ID of the module being queried
* @return disabled Whether the module has been disabled
*/
function getModuleByAddress(address _addr) external view returns (bytes32 id, bool disabled) {
Module storage module = allModules[_addr];
id = module.id;
disabled = module.disabled;
}
/**
* @dev Tell the current address and disable status of a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function getModule(bytes32 _id) external view returns (address addr, bool disabled) {
return _getModule(_id);
}
/**
* @dev Tell the information for the current DisputeManager module
* @return addr Current address of the DisputeManager module
* @return disabled Whether the module has been disabled
*/
function getDisputeManager() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_DISPUTE_MANAGER);
}
/**
* @dev Tell the information for the current GuardiansRegistry module
* @return addr Current address of the GuardiansRegistry module
* @return disabled Whether the module has been disabled
*/
function getGuardiansRegistry() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_GUARDIANS_REGISTRY);
}
/**
* @dev Tell the information for the current Voting module
* @return addr Current address of the Voting module
* @return disabled Whether the module has been disabled
*/
function getVoting() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_VOTING);
}
/**
* @dev Tell the information for the current PaymentsBook module
* @return addr Current address of the PaymentsBook module
* @return disabled Whether the module has been disabled
*/
function getPaymentsBook() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_PAYMENTS_BOOK);
}
/**
* @dev Tell the information for the current Treasury module
* @return addr Current address of the Treasury module
* @return disabled Whether the module has been disabled
*/
function getTreasury() external view returns (address addr, bool disabled) {
return _getModule(MODULE_ID_TREASURY);
}
/**
* @dev Tell the target registered for a custom function
* @param _sig Signature of the function being queried
* @return Address of the target where the function call will be forwarded
*/
function getCustomFunction(bytes4 _sig) external view returns (address) {
return customFunctions[_sig];
}
/**
* @dev Internal function to set the address of the funds governor
* @param _newFundsGovernor Address of the new config governor to be set
*/
function _setFundsGovernor(address _newFundsGovernor) internal {
emit FundsGovernorChanged(governor.funds, _newFundsGovernor);
governor.funds = _newFundsGovernor;
}
/**
* @dev Internal function to set the address of the config governor
* @param _newConfigGovernor Address of the new config governor to be set
*/
function _setConfigGovernor(address _newConfigGovernor) internal {
emit ConfigGovernorChanged(governor.config, _newConfigGovernor);
governor.config = _newConfigGovernor;
}
/**
* @dev Internal function to set the address of the modules governor
* @param _newModulesGovernor Address of the new modules governor to be set
*/
function _setModulesGovernor(address _newModulesGovernor) internal {
emit ModulesGovernorChanged(governor.modules, _newModulesGovernor);
governor.modules = _newModulesGovernor;
}
/**
* @dev Internal function to set an address as the current implementation for a module
* Note that the disabled condition is not affected, if the module was not set before it will be enabled by default
* @param _id Id of the module to be set
* @param _addr Address of the module to be set
*/
function _setModule(bytes32 _id, address _addr) internal {
require(isContract(_addr), ERROR_IMPLEMENTATION_NOT_CONTRACT);
currentModules[_id] = _addr;
allModules[_addr].id = _id;
emit ModuleSet(_id, _addr);
}
/**
* @dev Internal function to sync the modules for a list of modules IDs based on their current implementation address
* @param _modulesToBeSynced List of addresses of connected modules to be synced
* @param _idsToBeSet List of IDs of the modules to be linked
*/
function _syncModuleLinks(address[] memory _modulesToBeSynced, bytes32[] memory _idsToBeSet) internal {
address[] memory addressesToBeSet = new address[](_idsToBeSet.length);
// Load the addresses associated with the requested module ids
for (uint256 i = 0; i < _idsToBeSet.length; i++) {
address moduleAddress = _getModuleAddress(_idsToBeSet[i]);
Module storage module = allModules[moduleAddress];
_ensureModuleExists(module);
addressesToBeSet[i] = moduleAddress;
}
// Update the links of all the requested modules
for (uint256 j = 0; j < _modulesToBeSynced.length; j++) {
IModulesLinker(_modulesToBeSynced[j]).linkModules(_idsToBeSet, addressesToBeSet);
}
}
/**
* @dev Internal function to notify when a term has been transitioned
* @param _termId Identification number of the new current term that has been transitioned
*/
function _onTermTransitioned(uint64 _termId) internal {
_ensureTermConfig(_termId);
}
/**
* @dev Internal function to check if a module was set
* @param _module Module to be checked
*/
function _ensureModuleExists(Module storage _module) internal view {
require(_module.id != bytes32(0), ERROR_MODULE_NOT_SET);
}
/**
* @dev Internal function to tell the information for a module based on a given ID
* @param _id ID of the module being queried
* @return addr Current address of the requested module
* @return disabled Whether the module has been disabled
*/
function _getModule(bytes32 _id) internal view returns (address addr, bool disabled) {
addr = _getModuleAddress(_id);
disabled = _isModuleDisabled(addr);
}
/**
* @dev Tell the current address for a module by ID
* @param _id ID of the module being queried
* @return Current address of the requested module
*/
function _getModuleAddress(bytes32 _id) internal view returns (address) {
return currentModules[_id];
}
/**
* @dev Tell whether a module is disabled
* @param _addr Address of the module being queried
* @return True if the module is disabled, false otherwise
*/
function _isModuleDisabled(address _addr) internal view returns (bool) {
return allModules[_addr].disabled;
}
}
contract ConfigConsumer is CourtConfigData {
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig);
/**
* @dev Internal function to get the Court config for a certain term
* @param _termId Identification number of the term querying the Court config of
* @return Court config for the given term
*/
function _getConfigAt(uint64 _termId) internal view returns (Config memory) {
(IERC20 _feeToken,
uint256[3] memory _fees,
uint64[5] memory _roundStateDurations,
uint16[2] memory _pcts,
uint64[4] memory _roundParams,
uint256[2] memory _appealCollateralParams,
uint256 _minActiveBalance) = _courtConfig().getConfig(_termId);
Config memory config;
config.fees = FeesConfig({
token: _feeToken,
guardianFee: _fees[0],
draftFee: _fees[1],
settleFee: _fees[2],
finalRoundReduction: _pcts[1]
});
config.disputes = DisputesConfig({
evidenceTerms: _roundStateDurations[0],
commitTerms: _roundStateDurations[1],
revealTerms: _roundStateDurations[2],
appealTerms: _roundStateDurations[3],
appealConfirmTerms: _roundStateDurations[4],
penaltyPct: _pcts[0],
firstRoundGuardiansNumber: _roundParams[0],
appealStepFactor: _roundParams[1],
maxRegularAppealRounds: _roundParams[2],
finalRoundLockTerms: _roundParams[3],
appealCollateralFactor: _appealCollateralParams[0],
appealConfirmCollateralFactor: _appealCollateralParams[1]
});
config.minActiveBalance = _minActiveBalance;
return config;
}
/**
* @dev Internal function to get the draft config for a given term
* @param _termId Identification number of the term querying the draft config of
* @return Draft config for the given term
*/
function _getDraftConfig(uint64 _termId) internal view returns (DraftConfig memory) {
(IERC20 feeToken, uint256 draftFee, uint16 penaltyPct) = _courtConfig().getDraftConfig(_termId);
return DraftConfig({ feeToken: feeToken, draftFee: draftFee, penaltyPct: penaltyPct });
}
/**
* @dev Internal function to get the min active balance config for a given term
* @param _termId Identification number of the term querying the min active balance config of
* @return Minimum amount of guardian tokens that can be activated
*/
function _getMinActiveBalance(uint64 _termId) internal view returns (uint256) {
return _courtConfig().getMinActiveBalance(_termId);
}
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVotingOwner {
/**
* @dev Ensure votes can be committed for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
*/
function ensureCanCommit(uint256 _voteId) external;
/**
* @dev Ensure a certain voter can commit votes for a vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
*/
function ensureCanCommit(uint256 _voteId, address _voter) external;
/**
* @dev Ensure a certain voter can reveal votes for vote instance, revert otherwise
* @param _voteId ID of the vote instance to request the weight of a voter for
* @param _voter Address of the voter querying the weight of
* @return Weight of the requested guardian for the requested vote instance
*/
function ensureCanReveal(uint256 _voteId, address _voter) external returns (uint64);
}
/*
* SPDX-License-Identifier: MIT
*/
interface ICRVoting {
/**
* @dev Create a new vote instance
* @dev This function can only be called by the CRVoting owner
* @param _voteId ID of the new vote instance to be created
* @param _possibleOutcomes Number of possible outcomes for the new vote instance to be created
*/
function createVote(uint256 _voteId, uint8 _possibleOutcomes) external;
/**
* @dev Get the winning outcome of a vote instance
* @param _voteId ID of the vote instance querying the winning outcome of
* @return Winning outcome of the given vote instance or refused in case it's missing
*/
function getWinningOutcome(uint256 _voteId) external view returns (uint8);
/**
* @dev Get the tally of an outcome for a certain vote instance
* @param _voteId ID of the vote instance querying the tally of
* @param _outcome Outcome querying the tally of
* @return Tally of the outcome being queried for the given vote instance
*/
function getOutcomeTally(uint256 _voteId, uint8 _outcome) external view returns (uint256);
/**
* @dev Tell whether an outcome is valid for a given vote instance or not
* @param _voteId ID of the vote instance to check the outcome of
* @param _outcome Outcome to check if valid or not
* @return True if the given outcome is valid for the requested vote instance, false otherwise
*/
function isValidOutcome(uint256 _voteId, uint8 _outcome) external view returns (bool);
/**
* @dev Get the outcome voted by a voter for a certain vote instance
* @param _voteId ID of the vote instance querying the outcome of
* @param _voter Address of the voter querying the outcome of
* @return Outcome of the voter for the given vote instance
*/
function getVoterOutcome(uint256 _voteId, address _voter) external view returns (uint8);
/**
* @dev Tell whether a voter voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to query if a voter voted in favor of a certain outcome
* @param _outcome Outcome to query if the given voter voted in favor of
* @param _voter Address of the voter to query if voted in favor of the given outcome
* @return True if the given voter voted in favor of the given outcome, false otherwise
*/
function hasVotedInFavorOf(uint256 _voteId, uint8 _outcome, address _voter) external view returns (bool);
/**
* @dev Filter a list of voters based on whether they voted in favor of a certain outcome in a vote instance or not
* @param _voteId ID of the vote instance to be checked
* @param _outcome Outcome to filter the list of voters of
* @param _voters List of addresses of the voters to be filtered
* @return List of results to tell whether a voter voted in favor of the given outcome or not
*/
function getVotersInFavorOf(uint256 _voteId, uint8 _outcome, address[] calldata _voters) external view returns (bool[] memory);
}
/*
* SPDX-License-Identifier: MIT
*/
interface IGuardiansRegistry {
/**
* @dev Assign a requested amount of guardian tokens to a guardian
* @param _guardian Guardian to add an amount of tokens to
* @param _amount Amount of tokens to be added to the available balance of a guardian
*/
function assignTokens(address _guardian, uint256 _amount) external;
/**
* @dev Burn a requested amount of guardian tokens
* @param _amount Amount of tokens to be burned
*/
function burnTokens(uint256 _amount) external;
/**
* @dev Draft a set of guardians based on given requirements for a term id
* @param _params Array containing draft requirements:
* 0. bytes32 Term randomness
* 1. uint256 Dispute id
* 2. uint64 Current term id
* 3. uint256 Number of seats already filled
* 4. uint256 Number of seats left to be filled
* 5. uint64 Number of guardians required for the draft
* 6. uint16 Permyriad of the minimum active balance to be locked for the draft
*
* @return guardians List of guardians selected for the draft
* @return length Size of the list of the draft result
*/
function draft(uint256[7] calldata _params) external returns (address[] memory guardians, uint256 length);
/**
* @dev Slash a set of guardians based on their votes compared to the winning ruling
* @param _termId Current term id
* @param _guardians List of guardian addresses to be slashed
* @param _lockedAmounts List of amounts locked for each corresponding guardian that will be either slashed or returned
* @param _rewardedGuardians List of booleans to tell whether a guardian's active balance has to be slashed or not
* @return Total amount of slashed tokens
*/
function slashOrUnlock(uint64 _termId, address[] calldata _guardians, uint256[] calldata _lockedAmounts, bool[] calldata _rewardedGuardians)
external
returns (uint256 collectedTokens);
/**
* @dev Try to collect a certain amount of tokens from a guardian for the next term
* @param _guardian Guardian to collect the tokens from
* @param _amount Amount of tokens to be collected from the given guardian and for the requested term id
* @param _termId Current term id
* @return True if the guardian has enough unlocked tokens to be collected for the requested term, false otherwise
*/
function collectTokens(address _guardian, uint256 _amount, uint64 _termId) external returns (bool);
/**
* @dev Lock a guardian's withdrawals until a certain term ID
* @param _guardian Address of the guardian to be locked
* @param _termId Term ID until which the guardian's withdrawals will be locked
*/
function lockWithdrawals(address _guardian, uint64 _termId) external;
/**
* @dev Tell the active balance of a guardian for a given term id
* @param _guardian Address of the guardian querying the active balance of
* @param _termId Term ID querying the active balance for
* @return Amount of active tokens for guardian in the requested past term id
*/
function activeBalanceOfAt(address _guardian, uint64 _termId) external view returns (uint256);
/**
* @dev Tell the total amount of active guardian tokens at the given term id
* @param _termId Term ID querying the total active balance for
* @return Total amount of active guardian tokens at the given term id
*/
function totalActiveBalanceAt(uint64 _termId) external view returns (uint256);
}
/*
* SPDX-License-Identifier: MIT
*/
interface IPaymentsBook {
/**
* @dev Pay an amount of tokens
* @param _token Address of the token being paid
* @param _amount Amount of tokens being paid
* @param _payer Address paying on behalf of
* @param _data Optional data
*/
function pay(address _token, uint256 _amount, address _payer, bytes calldata _data) external payable;
}
contract Controlled is IModulesLinker, IsContract, ModuleIds, ConfigConsumer {
string private constant ERROR_MODULE_NOT_SET = "CTD_MODULE_NOT_SET";
string private constant ERROR_INVALID_MODULES_LINK_INPUT = "CTD_INVALID_MODULES_LINK_INPUT";
string private constant ERROR_CONTROLLER_NOT_CONTRACT = "CTD_CONTROLLER_NOT_CONTRACT";
string private constant ERROR_SENDER_NOT_ALLOWED = "CTD_SENDER_NOT_ALLOWED";
string private constant ERROR_SENDER_NOT_CONTROLLER = "CTD_SENDER_NOT_CONTROLLER";
string private constant ERROR_SENDER_NOT_CONFIG_GOVERNOR = "CTD_SENDER_NOT_CONFIG_GOVERNOR";
string private constant ERROR_SENDER_NOT_ACTIVE_VOTING = "CTD_SENDER_NOT_ACTIVE_VOTING";
string private constant ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER = "CTD_SEND_NOT_ACTIVE_DISPUTE_MGR";
string private constant ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER = "CTD_SEND_NOT_CURRENT_DISPUTE_MGR";
// Address of the controller
Controller public controller;
// List of modules linked indexed by ID
mapping (bytes32 => address) public linkedModules;
event ModuleLinked(bytes32 id, address addr);
/**
* @dev Ensure the msg.sender is the controller's config governor
*/
modifier onlyConfigGovernor {
require(msg.sender == _configGovernor(), ERROR_SENDER_NOT_CONFIG_GOVERNOR);
_;
}
/**
* @dev Ensure the msg.sender is the controller
*/
modifier onlyController() {
require(msg.sender == address(controller), ERROR_SENDER_NOT_CONTROLLER);
_;
}
/**
* @dev Ensure the msg.sender is an active DisputeManager module
*/
modifier onlyActiveDisputeManager() {
require(controller.isActive(MODULE_ID_DISPUTE_MANAGER, msg.sender), ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is the current DisputeManager module
*/
modifier onlyCurrentDisputeManager() {
(address addr, bool disabled) = controller.getDisputeManager();
require(msg.sender == addr, ERROR_SENDER_NOT_CURRENT_DISPUTE_MANAGER);
require(!disabled, ERROR_SENDER_NOT_ACTIVE_DISPUTE_MANAGER);
_;
}
/**
* @dev Ensure the msg.sender is an active Voting module
*/
modifier onlyActiveVoting() {
require(controller.isActive(MODULE_ID_VOTING, msg.sender), ERROR_SENDER_NOT_ACTIVE_VOTING);
_;
}
/**
* @dev This modifier will check that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
modifier authenticateSender(address _user) {
_authenticateSender(_user);
_;
}
/**
* @dev Constructor function
* @param _controller Address of the controller
*/
constructor(Controller _controller) public {
require(isContract(address(_controller)), ERROR_CONTROLLER_NOT_CONTRACT);
controller = _controller;
}
/**
* @notice Update the implementation links of a list of modules
* @dev The controller is expected to ensure the given addresses are correct modules
* @param _ids List of IDs of the modules to be updated
* @param _addresses List of module addresses to be updated
*/
function linkModules(bytes32[] calldata _ids, address[] calldata _addresses) external onlyController {
require(_ids.length == _addresses.length, ERROR_INVALID_MODULES_LINK_INPUT);
for (uint256 i = 0; i < _ids.length; i++) {
linkedModules[_ids[i]] = _addresses[i];
emit ModuleLinked(_ids[i], _addresses[i]);
}
}
/**
* @dev Internal function to ensure the Court term is up-to-date, it will try to update it if not
* @return Identification number of the current Court term
*/
function _ensureCurrentTerm() internal returns (uint64) {
return _clock().ensureCurrentTerm();
}
/**
* @dev Internal function to fetch the last ensured term ID of the Court
* @return Identification number of the last ensured term
*/
function _getLastEnsuredTermId() internal view returns (uint64) {
return _clock().getLastEnsuredTermId();
}
/**
* @dev Internal function to tell the current term identification number
* @return Identification number of the current term
*/
function _getCurrentTermId() internal view returns (uint64) {
return _clock().getCurrentTermId();
}
/**
* @dev Internal function to fetch the controller's config governor
* @return Address of the controller's config governor
*/
function _configGovernor() internal view returns (address) {
return controller.getConfigGovernor();
}
/**
* @dev Internal function to fetch the address of the DisputeManager module
* @return Address of the DisputeManager module
*/
function _disputeManager() internal view returns (IDisputeManager) {
return IDisputeManager(_getLinkedModule(MODULE_ID_DISPUTE_MANAGER));
}
/**
* @dev Internal function to fetch the address of the GuardianRegistry module implementation
* @return Address of the GuardianRegistry module implementation
*/
function _guardiansRegistry() internal view returns (IGuardiansRegistry) {
return IGuardiansRegistry(_getLinkedModule(MODULE_ID_GUARDIANS_REGISTRY));
}
/**
* @dev Internal function to fetch the address of the Voting module implementation
* @return Address of the Voting module implementation
*/
function _voting() internal view returns (ICRVoting) {
return ICRVoting(_getLinkedModule(MODULE_ID_VOTING));
}
/**
* @dev Internal function to fetch the address of the PaymentsBook module implementation
* @return Address of the PaymentsBook module implementation
*/
function _paymentsBook() internal view returns (IPaymentsBook) {
return IPaymentsBook(_getLinkedModule(MODULE_ID_PAYMENTS_BOOK));
}
/**
* @dev Internal function to fetch the address of the Treasury module implementation
* @return Address of the Treasury module implementation
*/
function _treasury() internal view returns (ITreasury) {
return ITreasury(_getLinkedModule(MODULE_ID_TREASURY));
}
/**
* @dev Internal function to tell the address linked for a module based on a given ID
* @param _id ID of the module being queried
* @return Linked address of the requested module
*/
function _getLinkedModule(bytes32 _id) internal view returns (address) {
address module = linkedModules[_id];
require(module != address(0), ERROR_MODULE_NOT_SET);
return module;
}
/**
* @dev Internal function to fetch the address of the Clock module from the controller
* @return Address of the Clock module
*/
function _clock() internal view returns (IClock) {
return IClock(controller);
}
/**
* @dev Internal function to fetch the address of the Config module from the controller
* @return Address of the Config module
*/
function _courtConfig() internal view returns (IConfig) {
return IConfig(controller);
}
/**
* @dev Ensure that the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
*/
function _authenticateSender(address _user) internal view {
require(_isSenderAllowed(_user), ERROR_SENDER_NOT_ALLOWED);
}
/**
* @dev Tell whether the sender is the user to act on behalf of or someone with the required permission
* @param _user Address of the user to act on behalf of
* @return True if the sender is the user to act on behalf of or someone with the required permission, false otherwise
*/
function _isSenderAllowed(address _user) internal view returns (bool) {
return msg.sender == _user || _hasRole(msg.sender);
}
/**
* @dev Tell whether an address holds the required permission to access the requested functionality
* @param _addr Address being checked
* @return True if the given address has the required permission to access the requested functionality, false otherwise
*/
function _hasRole(address _addr) internal view returns (bool) {
bytes32 roleId = keccak256(abi.encodePacked(address(this), msg.sig));
return controller.hasRole(_addr, roleId);
}
}
contract ControlledRecoverable is Controlled {
using SafeERC20 for IERC20;
string private constant ERROR_SENDER_NOT_FUNDS_GOVERNOR = "CTD_SENDER_NOT_FUNDS_GOVERNOR";
string private constant ERROR_INSUFFICIENT_RECOVER_FUNDS = "CTD_INSUFFICIENT_RECOVER_FUNDS";
string private constant ERROR_RECOVER_TOKEN_FUNDS_FAILED = "CTD_RECOVER_TOKEN_FUNDS_FAILED";
event RecoverFunds(address token, address recipient, uint256 balance);
/**
* @dev Ensure the msg.sender is the controller's funds governor
*/
modifier onlyFundsGovernor {
require(msg.sender == controller.getFundsGovernor(), ERROR_SENDER_NOT_FUNDS_GOVERNOR);
_;
}
/**
* @notice Transfer all `_token` tokens to `_to`
* @param _token Address of the token to be recovered
* @param _to Address of the recipient that will be receive all the funds of the requested token
*/
function recoverFunds(address _token, address payable _to) external payable onlyFundsGovernor {
uint256 balance;
if (_token == address(0)) {
balance = address(this).balance;
require(_to.send(balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED);
} else {
balance = IERC20(_token).balanceOf(address(this));
require(balance > 0, ERROR_INSUFFICIENT_RECOVER_FUNDS);
// No need to verify _token to be a contract as we have already checked the balance
require(IERC20(_token).safeTransfer(_to, balance), ERROR_RECOVER_TOKEN_FUNDS_FAILED);
}
emit RecoverFunds(_token, _to, balance);
}
}
contract CourtTreasury is ITreasury, ControlledRecoverable {
using SafeERC20 for IERC20;
using SafeMath for uint256;
string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "TREASURY_DEPOSIT_AMOUNT_ZERO";
string private constant ERROR_WITHDRAW_FAILED = "TREASURY_WITHDRAW_FAILED";
string private constant ERROR_WITHDRAW_AMOUNT_ZERO = "TREASURY_WITHDRAW_AMOUNT_ZERO";
string private constant ERROR_WITHDRAW_INVALID_AMOUNT = "TREASURY_WITHDRAW_INVALID_AMOUNT";
string private constant ERROR_WITHDRAWS_DISALLOWED = "TREASURY_WITHDRAWALS_DISALLOWED";
// List of balances indexed by token and holder address
mapping (address => mapping (address => uint256)) internal balances;
event Assign(IERC20 indexed token, address indexed from, address indexed to, uint256 amount);
event Withdraw(IERC20 indexed token, address indexed from, address indexed to, uint256 amount);
/**
* @dev Constructor function
* @param _controller Address of the controller
*/
constructor(Controller _controller) Controlled(_controller) public {
// solium-disable-previous-line no-empty-blocks
}
/**
* @notice Assign `@tokenAmount(_token, _amount)` to `_to`
* @param _token ERC20 token to be assigned
* @param _to Address of the recipient that will be assigned the tokens to
* @param _amount Amount of tokens to be assigned to the recipient
*/
function assign(IERC20 _token, address _to, uint256 _amount) external onlyActiveDisputeManager {
require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO);
address tokenAddress = address(_token);
balances[tokenAddress][_to] = balances[tokenAddress][_to].add(_amount);
emit Assign(_token, msg.sender, _to, _amount);
}
/**
* @notice Withdraw `@tokenAmount(_token, _amount)` from `_from` to `_to`
* @param _token ERC20 token to be withdrawn
* @param _from Address withdrawing the tokens from
* @param _to Address of the recipient that will receive the tokens
* @param _amount Amount of tokens to be withdrawn from the sender
*/
function withdraw(IERC20 _token, address _from, address _to, uint256 _amount) external authenticateSender(_from) {
_withdraw(_token, _from, _to, _amount);
}
/**
* @dev Tell the token balance of a certain holder
* @param _token ERC20 token balance being queried
* @param _holder Address of the holder querying the balance of
* @return Amount of tokens the holder owns
*/
function balanceOf(IERC20 _token, address _holder) external view returns (uint256) {
return _balanceOf(_token, _holder);
}
/**
* @dev Internal function to withdraw tokens from an account
* @param _token ERC20 token to be withdrawn
* @param _from Address where the tokens will be removed from
* @param _to Address of the recipient that will receive the corresponding tokens
* @param _amount Amount of tokens to be withdrawn from the sender
*/
function _withdraw(IERC20 _token, address _from, address _to, uint256 _amount) internal {
require(_amount > 0, ERROR_WITHDRAW_AMOUNT_ZERO);
uint256 balance = _balanceOf(_token, _from);
require(balance >= _amount, ERROR_WITHDRAW_INVALID_AMOUNT);
address tokenAddress = address(_token);
// No need for SafeMath: checked above
balances[tokenAddress][_from] = balance - _amount;
emit Withdraw(_token, _from, _to, _amount);
// No need to verify _token to be a contract as we are already requiring a positive balance
// on a token that is permissioned under the active DisputeManager
require(_token.safeTransfer(_to, _amount), ERROR_WITHDRAW_FAILED);
}
/**
* @dev Internal function to tell the token balance of a certain holder
* @param _token ERC20 token balance being queried
* @param _holder Address of the holder querying the balance of
* @return Amount of tokens the holder owns
*/
function _balanceOf(IERC20 _token, address _holder) internal view returns (uint256) {
return balances[address(_token)][_holder];
}
}
|
Tell the token balance of a certain holder _token ERC20 token balance being queried _holder Address of the holder querying the balance of return Amount of tokens the holder owns/
|
function balanceOf(IERC20 _token, address _holder) external view returns (uint256) {
return _balanceOf(_token, _holder);
}
| 6,793,829 |
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "./AloePool.sol";
contract AloePoolCapped is AloePool {
using SafeERC20 for IERC20;
address public immutable MULTISIG;
uint256 public maxTotalSupply = 100000000000000000000;
constructor(address predictions, address multisig) AloePool(predictions) {
MULTISIG = multisig;
}
modifier restricted() {
require(msg.sender == MULTISIG, "Not authorized");
_;
}
function deposit(
uint256 amount0Max,
uint256 amount1Max,
uint256 amount0Min,
uint256 amount1Min
)
public
override
lock
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
(shares, amount0, amount1) = super.deposit(amount0Max, amount1Max, amount0Min, amount1Min);
require(totalSupply() <= maxTotalSupply, "Aloe: Pool already full");
}
/**
* @notice Removes tokens accidentally sent to this vault.
*/
function sweep(
IERC20 token,
uint256 amount,
address to
) external restricted {
require(token != TOKEN0 && token != TOKEN1, "Not sweepable");
token.safeTransfer(to, amount);
}
/**
* @notice Used to change deposit cap for a guarded launch or to ensure
* vault doesn't grow too large relative to the UNI_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 restricted {
maxTotalSupply = _maxTotalSupply;
}
function toggleRebalances() external restricted {
allowRebalances = !allowRebalances;
}
function setK(uint48 _K) external restricted {
K = _K;
}
}
// 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'
// 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) + 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
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "./libraries/FullMath.sol";
import "./libraries/LiquidityAmounts.sol";
import "./libraries/Math.sol";
import "./libraries/TickMath.sol";
import "./interfaces/IAloePredictions.sol";
import "./interfaces/IAloePredictionsImmutables.sol";
import "./AloePoolERC20.sol";
import "./UniswapMinter.sol";
uint256 constant TWO_144 = 2**144;
struct PDF {
bool isInverted;
uint176 mean;
uint128 sigmaL;
uint128 sigmaU;
}
contract AloePool is AloePoolERC20, UniswapMinter {
using SafeERC20 for IERC20;
event Deposit(address indexed sender, uint256 shares, uint256 amount0, uint256 amount1);
event Withdraw(address indexed sender, uint256 shares, uint256 amount0, uint256 amount1);
event Snapshot(int24 tick, uint256 totalAmount0, uint256 totalAmount1, uint256 totalSupply);
/// @dev The number of standard deviations to +/- from mean when setting position bounds
uint48 public K = 5;
/// @dev The number of seconds to look back when computing current price. Makes manipulation harder
uint32 public constant CURRENT_PRICE_WINDOW = 360;
/// @dev The predictions market that provides this pool with next-price distribution data
IAloePredictions public immutable PREDICTIONS;
/// @dev The most recent predictions market epoch during which this pool was rebalanced
uint24 public epoch;
/// @dev The elastic position stretches to accomodate unpredictable price movements
Ticks public elastic;
/// @dev The cushion position consumes leftover funds after `elastic` is stretched
Ticks public cushion;
/// @dev The excess position is made up of funds that didn't fit into `elastic` when rebalancing
Ticks public excess;
/// @dev The current statistics from prediction market (representing a probability density function)
PDF public pdf;
/// @dev Whether the pool had excess token0 as of the most recent rebalance
bool public didHaveExcessToken0;
/// @dev For reentrancy check
bool private locked;
bool public allowRebalances = true;
modifier lock() {
require(!locked, "Aloe: Locked");
locked = true;
_;
locked = false;
}
constructor(address predictions)
AloePoolERC20()
UniswapMinter(IUniswapV3Pool(IAloePredictionsImmutables(predictions).UNI_POOL()))
{
PREDICTIONS = IAloePredictions(predictions);
}
/**
* @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 getReserves() public view returns (uint256 reserve0, uint256 reserve1) {
reserve0 = TOKEN0.balanceOf(address(this));
reserve1 = TOKEN1.balanceOf(address(this));
uint256 temp0;
uint256 temp1;
(temp0, temp1) = _collectableAmountsAsOfLastPoke(elastic);
reserve0 += temp0;
reserve1 += temp1;
(temp0, temp1) = _collectableAmountsAsOfLastPoke(cushion);
reserve0 += temp0;
reserve1 += temp1;
(temp0, temp1) = _collectableAmountsAsOfLastPoke(excess);
reserve0 += temp0;
reserve1 += temp1;
}
function getNextElasticTicks() public view returns (Ticks memory) {
// Define the window over which we want to fetch price
uint32[] memory secondsAgos = new uint32[](2);
secondsAgos[0] = CURRENT_PRICE_WINDOW;
secondsAgos[1] = 0;
// Fetch price and account for possible inversion
(int56[] memory tickCumulatives, ) = UNI_POOL.observe(secondsAgos);
uint176 price =
TickMath.getSqrtRatioAtTick(
int24((tickCumulatives[1] - tickCumulatives[0]) / int56(uint56(CURRENT_PRICE_WINDOW)))
);
if (pdf.isInverted) price = type(uint160).max / price;
price = uint176(FullMath.mulDiv(price, price, TWO_144));
return _getNextElasticTicks(price, pdf.mean, pdf.sigmaL, pdf.sigmaU, pdf.isInverted);
}
function _getNextElasticTicks(
uint176 price,
uint176 mean,
uint128 sigmaL,
uint128 sigmaU,
bool areInverted
) private view returns (Ticks memory ticks) {
uint48 n;
uint176 widthL;
uint176 widthU;
if (price < mean) {
n = uint48((mean - price) / sigmaL);
widthL = uint176(sigmaL) * uint176(K + n);
widthU = uint176(sigmaU) * uint176(K);
} else {
n = uint48((price - mean) / sigmaU);
widthL = uint176(sigmaL) * uint176(K);
widthU = uint176(sigmaU) * uint176(K + n);
}
uint176 l = mean > widthL ? mean - widthL : 1;
uint176 u = mean < type(uint176).max - widthU ? mean + widthU : type(uint176).max;
uint160 sqrtPriceX96;
if (areInverted) {
sqrtPriceX96 = uint160(uint256(type(uint128).max) / Math.sqrt(u << 80));
ticks.lower = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
sqrtPriceX96 = uint160(uint256(type(uint128).max) / Math.sqrt(l << 80));
ticks.upper = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
} else {
sqrtPriceX96 = uint160(Math.sqrt(l << 80) << 32);
ticks.lower = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
sqrtPriceX96 = uint160(Math.sqrt(u << 80) << 32);
ticks.upper = TickMath.getTickAtSqrtRatio(sqrtPriceX96);
}
}
/**
* @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.
* @dev LOCK MODIFIER IS APPLIED IN AloePoolCapped!!!
* @param amount0Max Max amount of TOKEN0 to deposit
* @param amount1Max Max amount of TOKEN1 to deposit
* @param amount0Min Ensure `amount0` is greater than this
* @param amount1Min Ensure `amount1` is greater than this
* @return shares Number of shares minted
* @return amount0 Amount of TOKEN0 deposited
* @return amount1 Amount of TOKEN1 deposited
*/
function deposit(
uint256 amount0Max,
uint256 amount1Max,
uint256 amount0Min,
uint256 amount1Min
)
public
virtual
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
require(amount0Max != 0 || amount1Max != 0, "Aloe: 0 deposit");
_uniswapPoke(elastic);
_uniswapPoke(cushion);
_uniswapPoke(excess);
(shares, amount0, amount1) = _computeLPShares(amount0Max, amount1Max);
require(shares != 0, "Aloe: 0 shares");
require(amount0 >= amount0Min, "Aloe: amount0 too low");
require(amount1 >= amount1Min, "Aloe: amount1 too low");
// 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
_mint(msg.sender, shares);
emit Deposit(msg.sender, shares, amount0, amount1);
}
/// @dev Calculates the largest possible `amount0` and `amount1` such that
/// they're in the same proportion as total amounts, but not greater than
/// `amount0Max` and `amount1Max` respectively.
function _computeLPShares(uint256 amount0Max, uint256 amount1Max)
internal
view
returns (
uint256 shares,
uint256 amount0,
uint256 amount1
)
{
uint256 totalSupply = totalSupply();
(uint256 reserve0, uint256 reserve1) = getReserves();
// If total supply > 0, pool can't be empty
assert(totalSupply == 0 || reserve0 != 0 || reserve1 != 0);
if (totalSupply == 0) {
// For first deposit, just use the amounts desired
amount0 = amount0Max;
amount1 = amount1Max;
shares = amount0 > amount1 ? amount0 : amount1; // max
} else if (reserve0 == 0) {
amount1 = amount1Max;
shares = FullMath.mulDiv(amount1, totalSupply, reserve1);
} else if (reserve1 == 0) {
amount0 = amount0Max;
shares = FullMath.mulDiv(amount0, totalSupply, reserve0);
} else {
amount0 = FullMath.mulDiv(amount1Max, reserve0, reserve1);
if (amount0 < amount0Max) {
amount1 = amount1Max;
shares = FullMath.mulDiv(amount1, totalSupply, reserve1);
} else {
amount0 = amount0Max;
amount1 = FullMath.mulDiv(amount0, reserve1, reserve0);
shares = FullMath.mulDiv(amount0, totalSupply, reserve0);
}
}
}
/**
* @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
* @return amount0 Amount of TOKEN0 sent to recipient
* @return amount1 Amount of TOKEN1 sent to recipient
*/
function withdraw(
uint256 shares,
uint256 amount0Min,
uint256 amount1Min
) external lock returns (uint256 amount0, uint256 amount1) {
require(shares != 0, "Aloe: 0 shares");
uint256 totalSupply = totalSupply() + 1;
// Calculate token amounts proportional to unused balances
amount0 = FullMath.mulDiv(TOKEN0.balanceOf(address(this)), shares, totalSupply);
amount1 = FullMath.mulDiv(TOKEN1.balanceOf(address(this)), shares, totalSupply);
// Withdraw proportion of liquidity from Uniswap pool
uint256 temp0;
uint256 temp1;
(temp0, temp1) = _uniswapExitFraction(shares, totalSupply, elastic);
amount0 += temp0;
amount1 += temp1;
(temp0, temp1) = _uniswapExitFraction(shares, totalSupply, cushion);
amount0 += temp0;
amount1 += temp1;
(temp0, temp1) = _uniswapExitFraction(shares, totalSupply, excess);
amount0 += temp0;
amount1 += temp1;
// Check constraints
require(amount0 >= amount0Min, "Aloe: amount0 too low");
require(amount1 >= amount1Min, "Aloe: amount1 too low");
// Transfer tokens
if (amount0 != 0) TOKEN0.safeTransfer(msg.sender, amount0);
if (amount1 != 0) TOKEN1.safeTransfer(msg.sender, amount1);
// Burn shares
_burn(msg.sender, shares);
emit Withdraw(msg.sender, shares, amount0, amount1);
}
/// @dev Withdraws share of liquidity in a range from Uniswap pool. All fee earnings
/// will be collected and left unused afterwards
function _uniswapExitFraction(
uint256 numerator,
uint256 denominator,
Ticks memory ticks
) internal returns (uint256 amount0, uint256 amount1) {
assert(numerator < denominator);
(uint128 liquidity, , , , ) = _position(ticks);
liquidity = uint128(FullMath.mulDiv(liquidity, numerator, denominator));
uint256 earned0;
uint256 earned1;
(amount0, amount1, earned0, earned1) = _uniswapExit(ticks, liquidity);
// Add share of fees
amount0 += FullMath.mulDiv(earned0, numerator, denominator);
amount1 += FullMath.mulDiv(earned1, numerator, denominator);
}
function rebalance() external lock {
require(allowRebalances, "Disabled");
uint24 _epoch = PREDICTIONS.epoch();
require(_epoch > epoch, "Aloe: Too early");
// Update P.D.F from prediction market
(pdf.isInverted, pdf.mean, pdf.sigmaL, pdf.sigmaU) = PREDICTIONS.current();
epoch = _epoch;
int24 tickSpacing = TICK_SPACING;
(uint160 sqrtPriceX96, int24 tick, , , , , ) = UNI_POOL.slot0();
// Exit all current Uniswap positions
{
(uint128 liquidityElastic, , , , ) = _position(elastic);
(uint128 liquidityCushion, , , , ) = _position(cushion);
(uint128 liquidityExcess, , , , ) = _position(excess);
_uniswapExit(elastic, liquidityElastic);
_uniswapExit(cushion, liquidityCushion);
_uniswapExit(excess, liquidityExcess);
}
// Emit snapshot to record balances and supply
uint256 balance0 = TOKEN0.balanceOf(address(this));
uint256 balance1 = TOKEN1.balanceOf(address(this));
emit Snapshot(tick, balance0, balance1, totalSupply());
// Place elastic order on Uniswap
Ticks memory elasticNew = _coerceTicksToSpacing(getNextElasticTicks());
uint128 liquidity = _liquidityForAmounts(elasticNew, sqrtPriceX96, balance0, balance1);
delete lastMintedAmount0;
delete lastMintedAmount1;
_uniswapEnter(elasticNew, liquidity);
elastic = elasticNew;
// Place excess order on Uniswap
Ticks memory active = _coerceTicksToSpacing(Ticks(tick, tick));
if (lastMintedAmount0 * balance1 < lastMintedAmount1 * balance0) {
_placeExcessUpper(active, TOKEN0.balanceOf(address(this)), tickSpacing);
didHaveExcessToken0 = true;
} else {
_placeExcessLower(active, TOKEN1.balanceOf(address(this)), tickSpacing);
didHaveExcessToken0 = false;
}
}
function shouldStretch() external view returns (bool) {
Ticks memory elasticNew = _coerceTicksToSpacing(getNextElasticTicks());
return elasticNew.lower != elastic.lower || elasticNew.upper != elastic.upper;
}
function stretch() external lock {
require(allowRebalances, "Disabled");
int24 tickSpacing = TICK_SPACING;
(uint160 sqrtPriceX96, int24 tick, , , , , ) = UNI_POOL.slot0();
// Check if stretching is necessary
Ticks memory elasticNew = _coerceTicksToSpacing(getNextElasticTicks());
require(elasticNew.lower != elastic.lower || elasticNew.upper != elastic.upper, "Aloe: Already stretched");
// Exit previous elastic and cushion, and place as much value as possible in new elastic
(uint256 elastic0, uint256 elastic1, , , uint256 available0, uint256 available1) =
_exit2Enter1(sqrtPriceX96, elastic, cushion, elasticNew);
elastic = elasticNew;
// Place new cushion
Ticks memory active = _coerceTicksToSpacing(Ticks(tick, tick));
if (lastMintedAmount0 * elastic1 < lastMintedAmount1 * elastic0) {
_placeCushionUpper(active, available0, tickSpacing);
} else {
_placeCushionLower(active, available1, tickSpacing);
}
}
function snipe() external lock {
require(allowRebalances, "Disabled");
int24 tickSpacing = TICK_SPACING;
(uint160 sqrtPriceX96, int24 tick, , , , uint8 feeProtocol, ) = UNI_POOL.slot0();
(
uint256 excess0,
uint256 excess1,
uint256 maxReward0,
uint256 maxReward1,
uint256 available0,
uint256 available1
) = _exit2Enter1(sqrtPriceX96, excess, cushion, elastic);
Ticks memory active = _coerceTicksToSpacing(Ticks(tick, tick));
uint128 reward = UNI_FEE;
if (didHaveExcessToken0) {
// Reward caller
if (feeProtocol >> 4 != 0) reward -= UNI_FEE / (feeProtocol >> 4);
reward = (uint128(excess1) * reward) / 1e6;
assert(reward <= maxReward1);
if (reward != 0) TOKEN1.safeTransfer(msg.sender, reward);
// Replace excess and cushion positions
if (excess0 >= available0) {
// We converted so much token0 to token1 that the cushion has to go
// on the other side now
_placeExcessUpper(active, available0, tickSpacing);
_placeCushionLower(active, available1, tickSpacing);
} else {
// Both excess and cushion still have token0 to eat through
_placeExcessUpper(active, excess0, tickSpacing);
_placeCushionUpper(active, available0 - excess0, tickSpacing);
}
} else {
// Reward caller
if (feeProtocol % 16 != 0) reward -= UNI_FEE / (feeProtocol % 16);
reward = (uint128(excess0) * reward) / 1e6;
assert(reward <= maxReward0);
if (reward != 0) TOKEN0.safeTransfer(msg.sender, reward);
// Replace excess and cushion positions
if (excess1 >= available1) {
// We converted so much token1 to token0 that the cushion has to go
// on the other side now
_placeExcessLower(active, available1, tickSpacing);
_placeCushionUpper(active, available0, tickSpacing);
} else {
// Both excess and cushion still have token1 to eat through
_placeExcessLower(active, excess1, tickSpacing);
_placeCushionLower(active, available1 - excess1, tickSpacing);
}
}
}
/// @dev Exits positions a and b, and moves as much value as possible to position c.
/// Position a must have non-zero liquidity.
function _exit2Enter1(
uint160 sqrtPriceX96,
Ticks memory a,
Ticks memory b,
Ticks memory c
)
private
returns (
uint256 a0,
uint256 a1,
uint256 aEarned0,
uint256 aEarned1,
uint256 available0,
uint256 available1
)
{
// Exit position A
(uint128 liquidity, , , , ) = _position(a);
require(liquidity != 0, "Aloe: Expected liquidity");
(a0, a1, aEarned0, aEarned1) = _uniswapExit(a, liquidity);
// Exit position B if it exists
uint256 b0;
uint256 b1;
(liquidity, , , , ) = _position(b);
if (liquidity != 0) {
(b0, b1, , ) = _uniswapExit(b, liquidity);
}
// Add to position c
available0 = a0 + b0;
available1 = a1 + b1;
liquidity = _liquidityForAmounts(c, sqrtPriceX96, available0, available1);
delete lastMintedAmount0;
delete lastMintedAmount1;
_uniswapEnter(c, liquidity);
unchecked {
available0 = available0 > lastMintedAmount0 ? available0 - lastMintedAmount0 : 0;
available1 = available1 > lastMintedAmount1 ? available1 - lastMintedAmount1 : 0;
}
}
function _placeCushionLower(
Ticks memory active,
uint256 balance1,
int24 tickSpacing
) private {
Ticks memory _cushion;
(_cushion.lower, _cushion.upper) = (elastic.lower, active.lower);
if (_cushion.lower == _cushion.upper) _cushion.lower -= tickSpacing;
_uniswapEnter(_cushion, _liquidityForAmount1(_cushion, balance1));
cushion = _cushion;
}
function _placeCushionUpper(
Ticks memory active,
uint256 balance0,
int24 tickSpacing
) private {
Ticks memory _cushion;
(_cushion.lower, _cushion.upper) = (active.upper, elastic.upper);
if (_cushion.lower == _cushion.upper) _cushion.upper += tickSpacing;
_uniswapEnter(_cushion, _liquidityForAmount0(_cushion, balance0));
cushion = _cushion;
}
function _placeExcessLower(
Ticks memory active,
uint256 balance1,
int24 tickSpacing
) private {
Ticks memory _excess;
(_excess.lower, _excess.upper) = (active.lower - tickSpacing, active.lower);
_uniswapEnter(_excess, _liquidityForAmount1(_excess, balance1));
excess = _excess;
}
function _placeExcessUpper(
Ticks memory active,
uint256 balance0,
int24 tickSpacing
) private {
Ticks memory _excess;
(_excess.lower, _excess.upper) = (active.upper, active.upper + tickSpacing);
_uniswapEnter(_excess, _liquidityForAmount0(_excess, balance0));
excess = _excess;
}
function _coerceTicksToSpacing(Ticks memory ticks) private view returns (Ticks memory ticksCoerced) {
ticksCoerced.lower =
ticks.lower -
(ticks.lower < 0 ? TICK_SPACING + (ticks.lower % TICK_SPACING) : ticks.lower % TICK_SPACING);
ticksCoerced.upper =
ticks.upper +
(ticks.upper < 0 ? -ticks.upper % TICK_SPACING : TICK_SPACING - (ticks.upper % TICK_SPACING));
assert(ticksCoerced.lower <= ticks.lower);
assert(ticksCoerced.upper >= ticks.upper);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.delegatecall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import './pool/IUniswapV3PoolImmutables.sol';
import './pool/IUniswapV3PoolState.sol';
import './pool/IUniswapV3PoolDerivedState.sol';
import './pool/IUniswapV3PoolActions.sol';
import './pool/IUniswapV3PoolOwnerActions.sol';
import './pool/IUniswapV3PoolEvents.sol';
/// @title The interface for a Uniswap V3 Pool
/// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform
/// to the ERC20 specification
/// @dev The pool interface is broken up into many smaller pieces
interface IUniswapV3Pool is
IUniswapV3PoolImmutables,
IUniswapV3PoolState,
IUniswapV3PoolDerivedState,
IUniswapV3PoolActions,
IUniswapV3PoolOwnerActions,
IUniswapV3PoolEvents
{
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.4.0;
/// @title Contains 512-bit math functions
/// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision
/// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits
library FullMath {
/// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0
/// @param a The multiplicand
/// @param b The multiplier
/// @param denominator The divisor
/// @return result The 256-bit result
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv
function mulDiv(
uint256 a,
uint256 b,
uint256 denominator
) internal pure returns (uint256 result) {
unchecked {
// 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.
// https://ethereum.stackexchange.com/a/96646
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++;
}
}
/// @dev https://medium.com/wicketh/mathemagic-full-multiply-27650fec525d
function mul512(uint256 a, uint256 b) internal pure returns (uint256 r0, uint256 r1) {
assembly {
let mm := mulmod(a, b, not(0))
r0 := mul(a, b)
r1 := sub(sub(mm, r0), lt(mm, r0))
}
}
/// @dev Like `mul512`, but multiply a number by itself
function square512(uint256 a) internal pure returns (uint256 r0, uint256 r1) {
assembly {
let mm := mulmod(a, a, not(0))
r0 := mul(a, a)
r1 := sub(sub(mm, r0), lt(mm, r0))
}
}
/// @dev https://github.com/hifi-finance/prb-math/blob/main/contracts/PRBMathCommon.sol
function log2floor(uint256 x) internal pure returns (uint256 msb) {
unchecked {
if (x >= 2**128) {
x >>= 128;
msb += 128;
}
if (x >= 2**64) {
x >>= 64;
msb += 64;
}
if (x >= 2**32) {
x >>= 32;
msb += 32;
}
if (x >= 2**16) {
x >>= 16;
msb += 16;
}
if (x >= 2**8) {
x >>= 8;
msb += 8;
}
if (x >= 2**4) {
x >>= 4;
msb += 4;
}
if (x >= 2**2) {
x >>= 2;
msb += 2;
}
if (x >= 2**1) {
// No need to shift x any more.
msb += 1;
}
}
}
/// @dev https://graphics.stanford.edu/~seander/bithacks.html#IntegerLogDeBruijn
function log2ceil(uint256 x) internal pure returns (uint256 y) {
assembly {
let arg := x
x := sub(x, 1)
x := or(x, div(x, 0x02))
x := or(x, div(x, 0x04))
x := or(x, div(x, 0x10))
x := or(x, div(x, 0x100))
x := or(x, div(x, 0x10000))
x := or(x, div(x, 0x100000000))
x := or(x, div(x, 0x10000000000000000))
x := or(x, div(x, 0x100000000000000000000000000000000))
x := add(x, 1)
let m := mload(0x40)
mstore(m, 0xf8f9cbfae6cc78fbefe7cdc3a1793dfcf4f0e8bbd8cec470b6a28a7a5a3e1efd)
mstore(add(m, 0x20), 0xf5ecf1b3e9debc68e1d9cfabc5997135bfb7a7a3938b7b606b5b4b3f2f1f0ffe)
mstore(add(m, 0x40), 0xf6e4ed9ff2d6b458eadcdf97bd91692de2d4da8fd2d0ac50c6ae9a8272523616)
mstore(add(m, 0x60), 0xc8c0b887b0a8a4489c948c7f847c6125746c645c544c444038302820181008ff)
mstore(add(m, 0x80), 0xf7cae577eec2a03cf3bad76fb589591debb2dd67e0aa9834bea6925f6a4a2e0e)
mstore(add(m, 0xa0), 0xe39ed557db96902cd38ed14fad815115c786af479b7e83247363534337271707)
mstore(add(m, 0xc0), 0xc976c13bb96e881cb166a933a55e490d9d56952b8d4e801485467d2362422606)
mstore(add(m, 0xe0), 0x753a6d1b65325d0c552a4d1345224105391a310b29122104190a110309020100)
mstore(0x40, add(m, 0x100))
let magic := 0x818283848586878898a8b8c8d8e8f929395969799a9b9d9e9faaeb6bedeeff
let shift := 0x100000000000000000000000000000000000000000000000000000000000000
let a := div(mul(x, magic), shift)
y := div(mload(add(m, sub(255, a))), shift)
y := add(y, mul(256, gt(arg, 0x8000000000000000000000000000000000000000000000000000000000000000)))
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
import "./FixedPoint96.sol";
import "./FullMath.sol";
/// @title Liquidity amount functions
/// @notice Provides functions for computing liquidity amounts from token amounts and prices
library LiquidityAmounts {
/// @notice Downcasts uint256 to uint128
/// @param x The uint258 to be downcasted
/// @return y The passed value, downcasted to uint128
function toUint128(uint256 x) private pure returns (uint128 y) {
require((y = uint128(x)) == x);
}
/// @notice Computes the amount of liquidity received for a given amount of token0 and price range
/// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower))
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount0 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount0(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96);
return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the amount of liquidity received for a given amount of token1 and price range
/// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)).
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount1 The amount1 being sent in
/// @return liquidity The amount of returned liquidity
function getLiquidityForAmount1(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96));
}
/// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param amount0 The amount of token0 being sent in
/// @param amount1 The amount of token1 being sent in
/// @return liquidity The maximum amount of liquidity received
function getLiquidityForAmounts(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128 liquidity) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0);
uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1);
liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1;
} else {
liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1);
}
}
/// @notice Computes the amount of token0 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
function getAmount0ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return
FullMath.mulDiv(
uint256(liquidity) << FixedPoint96.RESOLUTION,
sqrtRatioBX96 - sqrtRatioAX96,
sqrtRatioBX96
) / sqrtRatioAX96;
}
/// @notice Computes the amount of token1 for a given amount of liquidity and a price range
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount1 The amount of token1
function getAmount1ForLiquidity(
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96);
}
/// @notice Computes the token0 and token1 value for a given amount of liquidity, the current
/// pool prices and the prices at the tick boundaries
/// @param sqrtRatioX96 A sqrt price representing the current pool prices
/// @param sqrtRatioAX96 A sqrt price representing the first tick boundary
/// @param sqrtRatioBX96 A sqrt price representing the second tick boundary
/// @param liquidity The liquidity being valued
/// @return amount0 The amount of token0
/// @return amount1 The amount of token1
function getAmountsForLiquidity(
uint160 sqrtRatioX96,
uint160 sqrtRatioAX96,
uint160 sqrtRatioBX96,
uint128 liquidity
) internal pure returns (uint256 amount0, uint256 amount1) {
if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96);
if (sqrtRatioX96 <= sqrtRatioAX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
} else if (sqrtRatioX96 < sqrtRatioBX96) {
amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity);
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity);
} else {
amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity);
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
library Math {
// babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method)
function sqrt(uint256 y) internal pure returns (uint256 z) {
unchecked {
if (y > 3) {
z = y;
uint256 x = y / 2 + 1;
while (x < z) {
z = x;
x = (y / x + x) / 2;
}
} else if (y != 0) {
z = 1;
}
}
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Math library for computing sqrt prices from ticks and vice versa
/// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports
/// prices between 2**-128 and 2**128
library TickMath {
/// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128
int24 internal constant MIN_TICK = -887272;
/// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128
int24 internal constant MAX_TICK = -MIN_TICK;
/// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK)
uint160 internal constant MIN_SQRT_RATIO = 4295128739;
/// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK)
uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342;
/// @notice Calculates sqrt(1.0001^tick) * 2^96
/// @dev Throws if |tick| > max tick
/// @param tick The input tick for the above formula
/// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0)
/// at the given tick
function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) {
uint256 absTick = tick < 0 ? uint256(-int256(tick)) : uint256(int256(tick));
require(absTick <= uint256(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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IAloePredictionsActions.sol";
import "./IAloePredictionsDerivedState.sol";
import "./IAloePredictionsEvents.sol";
import "./IAloePredictionsState.sol";
/// @title Aloe predictions market interface
/// @dev The interface is broken up into many smaller pieces
interface IAloePredictions is
IAloePredictionsActions,
IAloePredictionsDerivedState,
IAloePredictionsEvents,
IAloePredictionsState
{
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAloePredictionsImmutables {
/// @dev The maximum number of proposals that should be aggregated
function NUM_PROPOSALS_TO_AGGREGATE() external view returns (uint8);
/// @dev The number of standard deviations to +/- from the mean when computing ground truth bounds
function GROUND_TRUTH_STDDEV_SCALE() external view returns (uint256);
/// @dev The minimum length of an epoch, in seconds. Epochs may be longer if no one calls `advance`
function EPOCH_LENGTH_SECONDS() external view returns (uint32);
/// @dev The ALOE token used for staking
function ALOE() external view returns (address);
/// @dev The Uniswap pair for which predictions should be made
function UNI_POOL() external view returns (address);
/// @dev The incentive vault to use for staking extras and `advance()` reward
function INCENTIVE_VAULT() external view returns (address);
}
// SPDX-License-Identifier: UNLICENSED
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol";
contract AloePoolERC20 is ERC20Permit {
constructor() ERC20Permit("Aloe V1") ERC20("Aloe V1", "ALOE-V1") {}
}
// SPDX-License-Identifier: Unlicense
pragma solidity ^0.8.0;
import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol";
import "@uniswap/v3-core/contracts/interfaces/callback/IUniswapV3MintCallback.sol";
import "@uniswap/v3-core/contracts/interfaces/IUniswapV3Pool.sol";
import "./libraries/LiquidityAmounts.sol";
import "./libraries/TickMath.sol";
import "./structs/Ticks.sol";
contract UniswapMinter is IUniswapV3MintCallback {
using SafeERC20 for IERC20;
IUniswapV3Pool public immutable UNI_POOL;
uint24 public immutable UNI_FEE;
int24 public immutable TICK_SPACING;
IERC20 public immutable TOKEN0;
IERC20 public immutable TOKEN1;
uint256 internal lastMintedAmount0;
uint256 internal lastMintedAmount1;
constructor(IUniswapV3Pool uniPool) {
UNI_POOL = uniPool;
UNI_FEE = uniPool.fee();
TICK_SPACING = uniPool.tickSpacing();
TOKEN0 = IERC20(uniPool.token0());
TOKEN1 = IERC20(uniPool.token1());
}
/// @dev Do zero-burns to poke the Uniswap pools so earned fees are updated
function _uniswapPoke(Ticks memory ticks) internal {
(uint128 liquidity, , , , ) = _position(ticks);
if (liquidity == 0) return;
UNI_POOL.burn(ticks.lower, ticks.upper, 0);
}
/// @dev Deposits liquidity in a range on the Uniswap pool.
function _uniswapEnter(Ticks memory ticks, uint128 liquidity) internal {
if (liquidity == 0) return;
UNI_POOL.mint(address(this), ticks.lower, ticks.upper, liquidity, "");
}
/// @dev Withdraws liquidity from a range and collects all fees in the process.
function _uniswapExit(Ticks memory ticks, uint128 liquidity)
internal
returns (
uint256 burned0,
uint256 burned1,
uint256 earned0,
uint256 earned1
)
{
if (liquidity != 0) {
(burned0, burned1) = UNI_POOL.burn(ticks.lower, ticks.upper, liquidity);
}
// Collect all owed tokens including earned fees
(uint256 collected0, uint256 collected1) =
UNI_POOL.collect(address(this), ticks.lower, ticks.upper, type(uint128).max, type(uint128).max);
earned0 = collected0 - burned0;
earned1 = collected1 - burned1;
}
/**
* @notice Amounts of TOKEN0 and TOKEN1 held in vault's position. Includes
* owed fees, except those accrued since last poke.
*/
function _collectableAmountsAsOfLastPoke(Ticks memory ticks) public view returns (uint256, uint256) {
(uint128 liquidity, , , uint128 earnable0, uint128 earnable1) = _position(ticks);
(uint160 sqrtPriceX96, , , , , , ) = UNI_POOL.slot0();
(uint256 burnable0, uint256 burnable1) = _amountsForLiquidity(ticks, liquidity, sqrtPriceX96);
return (burnable0 + earnable0, burnable1 + earnable1);
}
/// @dev Wrapper around `IUniswapV3Pool.positions()`.
function _position(Ticks memory ticks)
internal
view
returns (
uint128, // liquidity
uint256, // feeGrowthInside0LastX128
uint256, // feeGrowthInside1LastX128
uint128, // tokensOwed0
uint128 // tokensOwed1
)
{
return UNI_POOL.positions(keccak256(abi.encodePacked(address(this), ticks.lower, ticks.upper)));
}
/// @dev Wrapper around `LiquidityAmounts.getAmountsForLiquidity()`.
function _amountsForLiquidity(Ticks memory ticks, uint128 liquidity, uint160 sqrtPriceX96) internal pure returns (uint256, uint256) {
return
LiquidityAmounts.getAmountsForLiquidity(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(ticks.lower),
TickMath.getSqrtRatioAtTick(ticks.upper),
liquidity
);
}
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmounts()`.
function _liquidityForAmounts(
Ticks memory ticks,
uint160 sqrtPriceX96,
uint256 amount0,
uint256 amount1
) internal pure returns (uint128) {
return
LiquidityAmounts.getLiquidityForAmounts(
sqrtPriceX96,
TickMath.getSqrtRatioAtTick(ticks.lower),
TickMath.getSqrtRatioAtTick(ticks.upper),
amount0,
amount1
);
}
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmount0()`.
function _liquidityForAmount0(Ticks memory ticks, uint256 amount0) internal pure returns (uint128) {
return
LiquidityAmounts.getLiquidityForAmount0(
TickMath.getSqrtRatioAtTick(ticks.lower),
TickMath.getSqrtRatioAtTick(ticks.upper),
amount0
);
}
/// @dev Wrapper around `LiquidityAmounts.getLiquidityForAmount1()`.
function _liquidityForAmount1(Ticks memory ticks, uint256 amount1) internal pure returns (uint128) {
return
LiquidityAmounts.getLiquidityForAmount1(
TickMath.getSqrtRatioAtTick(ticks.lower),
TickMath.getSqrtRatioAtTick(ticks.upper),
amount1
);
}
/// @dev Callback for Uniswap V3 pool.
function uniswapV3MintCallback(
uint256 amount0,
uint256 amount1,
bytes calldata data
) external override {
require(msg.sender == address(UNI_POOL), "Fake callback");
if (amount0 != 0) TOKEN0.safeTransfer(msg.sender, amount0);
if (amount1 != 0) TOKEN1.safeTransfer(msg.sender, amount1);
lastMintedAmount0 = amount0;
lastMintedAmount1 = amount1;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that never changes
/// @notice These parameters are fixed for a pool forever, i.e., the methods will always return the same values
interface IUniswapV3PoolImmutables {
/// @notice The contract that deployed the pool, which must adhere to the IUniswapV3Factory interface
/// @return The contract address
function factory() external view returns (address);
/// @notice The first of the two tokens of the pool, sorted by address
/// @return The token contract address
function token0() external view returns (address);
/// @notice The second of the two tokens of the pool, sorted by address
/// @return The token contract address
function token1() external view returns (address);
/// @notice The pool's fee in hundredths of a bip, i.e. 1e-6
/// @return The fee
function fee() external view returns (uint24);
/// @notice The pool tick spacing
/// @dev Ticks can only be used at multiples of this value, minimum of 1 and always positive
/// e.g.: a tickSpacing of 3 means ticks can be initialized every 3rd tick, i.e., ..., -6, -3, 0, 3, 6, ...
/// This value is an int24 to avoid casting even though it is always positive.
/// @return The tick spacing
function tickSpacing() external view returns (int24);
/// @notice The maximum amount of position liquidity that can use any tick in the range
/// @dev This parameter is enforced per tick to prevent liquidity from overflowing a uint128 at any point, and
/// also prevents out-of-range liquidity from being used to prevent adding in-range liquidity to a pool
/// @return The max amount of liquidity per tick
function maxLiquidityPerTick() external view returns (uint128);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that can change
/// @notice These methods compose the pool's state, and can change with any frequency including multiple times
/// per transaction
interface IUniswapV3PoolState {
/// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas
/// when accessed externally.
/// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value
/// tick The current tick of the pool, i.e. according to the last tick transition that was run.
/// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick
/// boundary.
/// observationIndex The index of the last oracle observation that was written,
/// observationCardinality The current maximum number of observations stored in the pool,
/// observationCardinalityNext The next maximum number of observations, to be updated when the observation.
/// feeProtocol The protocol fee for both tokens of the pool.
/// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0
/// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee.
/// unlocked Whether the pool is currently locked to reentrancy
function slot0()
external
view
returns (
uint160 sqrtPriceX96,
int24 tick,
uint16 observationIndex,
uint16 observationCardinality,
uint16 observationCardinalityNext,
uint8 feeProtocol,
bool unlocked
);
/// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal0X128() external view returns (uint256);
/// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool
/// @dev This value can overflow the uint256
function feeGrowthGlobal1X128() external view returns (uint256);
/// @notice The amounts of token0 and token1 that are owed to the protocol
/// @dev Protocol fees will never exceed uint128 max in either token
function protocolFees() external view returns (uint128 token0, uint128 token1);
/// @notice The currently in range liquidity available to the pool
/// @dev This value has no relationship to the total liquidity across all ticks
function liquidity() external view returns (uint128);
/// @notice Look up information about a specific tick in the pool
/// @param tick The tick to look up
/// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or
/// tick upper,
/// liquidityNet how much liquidity changes when the pool price crosses the tick,
/// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0,
/// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1,
/// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick
/// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick,
/// secondsOutside the seconds spent on the other side of the tick from the current tick,
/// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false.
/// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0.
/// In addition, these values are only relative and must be used only in comparison to previous snapshots for
/// a specific position.
function ticks(int24 tick)
external
view
returns (
uint128 liquidityGross,
int128 liquidityNet,
uint256 feeGrowthOutside0X128,
uint256 feeGrowthOutside1X128,
int56 tickCumulativeOutside,
uint160 secondsPerLiquidityOutsideX128,
uint32 secondsOutside,
bool initialized
);
/// @notice Returns 256 packed tick initialized boolean values. See TickBitmap for more information
function tickBitmap(int16 wordPosition) external view returns (uint256);
/// @notice Returns the information about a position by the position's key
/// @param key The position's key is a hash of a preimage composed by the owner, tickLower and tickUpper
/// @return _liquidity The amount of liquidity in the position,
/// Returns feeGrowthInside0LastX128 fee growth of token0 inside the tick range as of the last mint/burn/poke,
/// Returns feeGrowthInside1LastX128 fee growth of token1 inside the tick range as of the last mint/burn/poke,
/// Returns tokensOwed0 the computed amount of token0 owed to the position as of the last mint/burn/poke,
/// Returns tokensOwed1 the computed amount of token1 owed to the position as of the last mint/burn/poke
function positions(bytes32 key)
external
view
returns (
uint128 _liquidity,
uint256 feeGrowthInside0LastX128,
uint256 feeGrowthInside1LastX128,
uint128 tokensOwed0,
uint128 tokensOwed1
);
/// @notice Returns data about a specific observation index
/// @param index The element of the observations array to fetch
/// @dev You most likely want to use #observe() instead of this method to get an observation as of some amount of time
/// ago, rather than at a specific index in the array.
/// @return blockTimestamp The timestamp of the observation,
/// Returns tickCumulative the tick multiplied by seconds elapsed for the life of the pool as of the observation timestamp,
/// Returns secondsPerLiquidityCumulativeX128 the seconds per in range liquidity for the life of the pool as of the observation timestamp,
/// Returns initialized whether the observation has been initialized and the values are safe to use
function observations(uint256 index)
external
view
returns (
uint32 blockTimestamp,
int56 tickCumulative,
uint160 secondsPerLiquidityCumulativeX128,
bool initialized
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Pool state that is not stored
/// @notice Contains view functions to provide information about the pool that is computed rather than stored on the
/// blockchain. The functions here may have variable gas costs.
interface IUniswapV3PoolDerivedState {
/// @notice Returns the cumulative tick and liquidity as of each timestamp `secondsAgo` from the current block timestamp
/// @dev To get a time weighted average tick or liquidity-in-range, you must call this with two values, one representing
/// the beginning of the period and another for the end of the period. E.g., to get the last hour time-weighted average tick,
/// you must call it with secondsAgos = [3600, 0].
/// @dev The time weighted average tick represents the geometric time weighted average price of the pool, in
/// log base sqrt(1.0001) of token1 / token0. The TickMath library can be used to go from a tick value to a ratio.
/// @param secondsAgos From how long ago each cumulative tick and liquidity value should be returned
/// @return tickCumulatives Cumulative tick values as of each `secondsAgos` from the current block timestamp
/// @return secondsPerLiquidityCumulativeX128s Cumulative seconds per liquidity-in-range value as of each `secondsAgos` from the current block
/// timestamp
function observe(uint32[] calldata secondsAgos)
external
view
returns (int56[] memory tickCumulatives, uint160[] memory secondsPerLiquidityCumulativeX128s);
/// @notice Returns a snapshot of the tick cumulative, seconds per liquidity and seconds inside a tick range
/// @dev Snapshots must only be compared to other snapshots, taken over a period for which a position existed.
/// I.e., snapshots cannot be compared if a position is not held for the entire period between when the first
/// snapshot is taken and the second snapshot is taken.
/// @param tickLower The lower tick of the range
/// @param tickUpper The upper tick of the range
/// @return tickCumulativeInside The snapshot of the tick accumulator for the range
/// @return secondsPerLiquidityInsideX128 The snapshot of seconds per liquidity for the range
/// @return secondsInside The snapshot of seconds per liquidity for the range
function snapshotCumulativesInside(int24 tickLower, int24 tickUpper)
external
view
returns (
int56 tickCumulativeInside,
uint160 secondsPerLiquidityInsideX128,
uint32 secondsInside
);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissionless pool actions
/// @notice Contains pool methods that can be called by anyone
interface IUniswapV3PoolActions {
/// @notice Sets the initial price for the pool
/// @dev Price is represented as a sqrt(amountToken1/amountToken0) Q64.96 value
/// @param sqrtPriceX96 the initial sqrt price of the pool as a Q64.96
function initialize(uint160 sqrtPriceX96) external;
/// @notice Adds liquidity for the given recipient/tickLower/tickUpper position
/// @dev The caller of this method receives a callback in the form of IUniswapV3MintCallback#uniswapV3MintCallback
/// in which they must pay any token0 or token1 owed for the liquidity. The amount of token0/token1 due depends
/// on tickLower, tickUpper, the amount of liquidity, and the current price.
/// @param recipient The address for which the liquidity will be created
/// @param tickLower The lower tick of the position in which to add liquidity
/// @param tickUpper The upper tick of the position in which to add liquidity
/// @param amount The amount of liquidity to mint
/// @param data Any data that should be passed through to the callback
/// @return amount0 The amount of token0 that was paid to mint the given amount of liquidity. Matches the value in the callback
/// @return amount1 The amount of token1 that was paid to mint the given amount of liquidity. Matches the value in the callback
function mint(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount,
bytes calldata data
) external returns (uint256 amount0, uint256 amount1);
/// @notice Collects tokens owed to a position
/// @dev Does not recompute fees earned, which must be done either via mint or burn of any amount of liquidity.
/// Collect must be called by the position owner. To withdraw only token0 or only token1, amount0Requested or
/// amount1Requested may be set to zero. To withdraw all tokens owed, caller may pass any value greater than the
/// actual tokens owed, e.g. type(uint128).max. Tokens owed may be from accumulated swap fees or burned liquidity.
/// @param recipient The address which should receive the fees collected
/// @param tickLower The lower tick of the position for which to collect fees
/// @param tickUpper The upper tick of the position for which to collect fees
/// @param amount0Requested How much token0 should be withdrawn from the fees owed
/// @param amount1Requested How much token1 should be withdrawn from the fees owed
/// @return amount0 The amount of fees collected in token0
/// @return amount1 The amount of fees collected in token1
function collect(
address recipient,
int24 tickLower,
int24 tickUpper,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
/// @notice Burn liquidity from the sender and account tokens owed for the liquidity to the position
/// @dev Can be used to trigger a recalculation of fees owed to a position by calling with an amount of 0
/// @dev Fees must be collected separately via a call to #collect
/// @param tickLower The lower tick of the position for which to burn liquidity
/// @param tickUpper The upper tick of the position for which to burn liquidity
/// @param amount How much liquidity to burn
/// @return amount0 The amount of token0 sent to the recipient
/// @return amount1 The amount of token1 sent to the recipient
function burn(
int24 tickLower,
int24 tickUpper,
uint128 amount
) external returns (uint256 amount0, uint256 amount1);
/// @notice Swap token0 for token1, or token1 for token0
/// @dev The caller of this method receives a callback in the form of IUniswapV3SwapCallback#uniswapV3SwapCallback
/// @param recipient The address to receive the output of the swap
/// @param zeroForOne The direction of the swap, true for token0 to token1, false for token1 to token0
/// @param amountSpecified The amount of the swap, which implicitly configures the swap as exact input (positive), or exact output (negative)
/// @param sqrtPriceLimitX96 The Q64.96 sqrt price limit. If zero for one, the price cannot be less than this
/// value after the swap. If one for zero, the price cannot be greater than this value after the swap
/// @param data Any data to be passed through to the callback
/// @return amount0 The delta of the balance of token0 of the pool, exact when negative, minimum when positive
/// @return amount1 The delta of the balance of token1 of the pool, exact when negative, minimum when positive
function swap(
address recipient,
bool zeroForOne,
int256 amountSpecified,
uint160 sqrtPriceLimitX96,
bytes calldata data
) external returns (int256 amount0, int256 amount1);
/// @notice Receive token0 and/or token1 and pay it back, plus a fee, in the callback
/// @dev The caller of this method receives a callback in the form of IUniswapV3FlashCallback#uniswapV3FlashCallback
/// @dev Can be used to donate underlying tokens pro-rata to currently in-range liquidity providers by calling
/// with 0 amount{0,1} and sending the donation amount(s) from the callback
/// @param recipient The address which will receive the token0 and token1 amounts
/// @param amount0 The amount of token0 to send
/// @param amount1 The amount of token1 to send
/// @param data Any data to be passed through to the callback
function flash(
address recipient,
uint256 amount0,
uint256 amount1,
bytes calldata data
) external;
/// @notice Increase the maximum number of price and liquidity observations that this pool will store
/// @dev This method is no-op if the pool already has an observationCardinalityNext greater than or equal to
/// the input observationCardinalityNext.
/// @param observationCardinalityNext The desired minimum number of observations for the pool to store
function increaseObservationCardinalityNext(uint16 observationCardinalityNext) external;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Permissioned pool actions
/// @notice Contains pool methods that may only be called by the factory owner
interface IUniswapV3PoolOwnerActions {
/// @notice Set the denominator of the protocol's % share of the fees
/// @param feeProtocol0 new protocol fee for token0 of the pool
/// @param feeProtocol1 new protocol fee for token1 of the pool
function setFeeProtocol(uint8 feeProtocol0, uint8 feeProtocol1) external;
/// @notice Collect the protocol fee accrued to the pool
/// @param recipient The address to which collected protocol fees should be sent
/// @param amount0Requested The maximum amount of token0 to send, can be 0 to collect fees in only token1
/// @param amount1Requested The maximum amount of token1 to send, can be 0 to collect fees in only token0
/// @return amount0 The protocol fee collected in token0
/// @return amount1 The protocol fee collected in token1
function collectProtocol(
address recipient,
uint128 amount0Requested,
uint128 amount1Requested
) external returns (uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @title Events emitted by a pool
/// @notice Contains all events emitted by the pool
interface IUniswapV3PoolEvents {
/// @notice Emitted exactly once by a pool when #initialize is first called on the pool
/// @dev Mint/Burn/Swap cannot be emitted by the pool before Initialize
/// @param sqrtPriceX96 The initial sqrt price of the pool, as a Q64.96
/// @param tick The initial tick of the pool, i.e. log base 1.0001 of the starting price of the pool
event Initialize(uint160 sqrtPriceX96, int24 tick);
/// @notice Emitted when liquidity is minted for a given position
/// @param sender The address that minted the liquidity
/// @param owner The owner of the position and recipient of any minted liquidity
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity minted to the position range
/// @param amount0 How much token0 was required for the minted liquidity
/// @param amount1 How much token1 was required for the minted liquidity
event Mint(
address sender,
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted when fees are collected by the owner of a position
/// @dev Collect events may be emitted with zero amount0 and amount1 when the caller chooses not to collect fees
/// @param owner The owner of the position for which fees are collected
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount0 The amount of token0 fees collected
/// @param amount1 The amount of token1 fees collected
event Collect(
address indexed owner,
address recipient,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount0,
uint128 amount1
);
/// @notice Emitted when a position's liquidity is removed
/// @dev Does not withdraw any fees earned by the liquidity position, which must be withdrawn via #collect
/// @param owner The owner of the position for which liquidity is removed
/// @param tickLower The lower tick of the position
/// @param tickUpper The upper tick of the position
/// @param amount The amount of liquidity to remove
/// @param amount0 The amount of token0 withdrawn
/// @param amount1 The amount of token1 withdrawn
event Burn(
address indexed owner,
int24 indexed tickLower,
int24 indexed tickUpper,
uint128 amount,
uint256 amount0,
uint256 amount1
);
/// @notice Emitted by the pool for any swaps between token0 and token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the output of the swap
/// @param amount0 The delta of the token0 balance of the pool
/// @param amount1 The delta of the token1 balance of the pool
/// @param sqrtPriceX96 The sqrt(price) of the pool after the swap, as a Q64.96
/// @param liquidity The liquidity of the pool after the swap
/// @param tick The log base 1.0001 of price of the pool after the swap
event Swap(
address indexed sender,
address indexed recipient,
int256 amount0,
int256 amount1,
uint160 sqrtPriceX96,
uint128 liquidity,
int24 tick
);
/// @notice Emitted by the pool for any flashes of token0/token1
/// @param sender The address that initiated the swap call, and that received the callback
/// @param recipient The address that received the tokens from flash
/// @param amount0 The amount of token0 that was flashed
/// @param amount1 The amount of token1 that was flashed
/// @param paid0 The amount of token0 paid for the flash, which can exceed the amount0 plus the fee
/// @param paid1 The amount of token1 paid for the flash, which can exceed the amount1 plus the fee
event Flash(
address indexed sender,
address indexed recipient,
uint256 amount0,
uint256 amount1,
uint256 paid0,
uint256 paid1
);
/// @notice Emitted by the pool for increases to the number of observations that can be stored
/// @dev observationCardinalityNext is not the observation cardinality until an observation is written at the index
/// just before a mint/swap/burn.
/// @param observationCardinalityNextOld The previous value of the next observation cardinality
/// @param observationCardinalityNextNew The updated value of the next observation cardinality
event IncreaseObservationCardinalityNext(
uint16 observationCardinalityNextOld,
uint16 observationCardinalityNextNew
);
/// @notice Emitted when the protocol fee is changed by the pool
/// @param feeProtocol0Old The previous value of the token0 protocol fee
/// @param feeProtocol1Old The previous value of the token1 protocol fee
/// @param feeProtocol0New The updated value of the token0 protocol fee
/// @param feeProtocol1New The updated value of the token1 protocol fee
event SetFeeProtocol(uint8 feeProtocol0Old, uint8 feeProtocol1Old, uint8 feeProtocol0New, uint8 feeProtocol1New);
/// @notice Emitted when the collected protocol fees are withdrawn by the factory owner
/// @param sender The address that collects the protocol fees
/// @param recipient The address that receives the collected protocol fees
/// @param amount0 The amount of token0 protocol fees that is withdrawn
/// @param amount0 The amount of token1 protocol fees that is withdrawn
event CollectProtocol(address indexed sender, address indexed recipient, uint128 amount0, uint128 amount1);
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.4.0;
/// @title FixedPoint96
/// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format)
/// @dev Used in SqrtPriceMath.sol
library FixedPoint96 {
uint8 internal constant RESOLUTION = 96;
uint256 internal constant Q96 = 0x1000000000000000000000000;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAloePredictionsActions {
/// @notice Advances the epoch no more than once per hour
function advance() external;
/**
* @notice Allows users to submit proposals in `epoch`. These proposals specify aggregate position
* in `epoch + 1` and adjusted stakes become claimable in `epoch + 2`
* @param lower The Q128.48 price at the lower bound, unless `shouldInvertPrices`, in which case
* this should be `1 / (priceAtUpperBound * 2 ** 16)`
* @param upper The Q128.48 price at the upper bound, unless `shouldInvertPrices`, in which case
* this should be `1 / (priceAtLowerBound * 2 ** 16)`
* @param stake The amount of ALOE to stake on this proposal. Once submitted, you can't unsubmit!
* @return key The unique ID of this proposal, used to update bounds and claim reward
*/
function submitProposal(
uint176 lower,
uint176 upper,
uint80 stake
) external returns (uint40 key);
/**
* @notice Allows users to update bounds of a proposal they submitted previously. This only
* works if the epoch hasn't increased since submission
* @param key The key of the proposal that should be updated
* @param lower The Q128.48 price at the lower bound, unless `shouldInvertPrices`, in which case
* this should be `1 / (priceAtUpperBound * 2 ** 16)`
* @param upper The Q128.48 price at the upper bound, unless `shouldInvertPrices`, in which case
* this should be `1 / (priceAtLowerBound * 2 ** 16)`
*/
function updateProposal(
uint40 key,
uint176 lower,
uint176 upper
) external;
/**
* @notice Allows users to reclaim ALOE that they staked in previous epochs, as long as
* the epoch has ground truth information
* @dev ALOE is sent to `proposal.source` not `msg.sender`, so anyone can trigger a claim
* for anyone else
* @param key The key of the proposal that should be judged and rewarded
* @param extras An array of tokens for which extra incentives should be claimed
*/
function claimReward(uint40 key, address[] calldata extras) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../structs/Bounds.sol";
interface IAloePredictionsDerivedState {
/**
* @notice Statistics for the most recent crowdsourced probability density function, evaluated about current price
* @return areInverted Whether the reported values are for inverted prices
* @return mean Result of `computeMean()`
* @return sigmaL The sqrt of the lower semivariance
* @return sigmaU The sqrt of the upper semivariance
*/
function current()
external
view
returns (
bool areInverted,
uint176 mean,
uint128 sigmaL,
uint128 sigmaU
);
/// @notice The earliest time at which the epoch can end
function epochExpectedEndTime() external view returns (uint32);
/**
* @notice Aggregates proposals in the previous `epoch`. Only the top `NUM_PROPOSALS_TO_AGGREGATE`, ordered by
* stake, will be considered.
* @return mean The mean of the crowdsourced probability density function (1st Raw Moment)
*/
function computeMean() external view returns (uint176 mean);
/**
* @notice Aggregates proposals in the previous `epoch`. Only the top `NUM_PROPOSALS_TO_AGGREGATE`, ordered by
* stake, will be considered.
* @return lower The lower semivariance of the crowdsourced probability density function (2nd Central Moment, Lower)
* @return upper The upper semivariance of the crowdsourced probability density function (2nd Central Moment, Upper)
*/
function computeSemivariancesAbout(uint176 center) external view returns (uint256 lower, uint256 upper);
/**
* @notice Fetches Uniswap prices over 10 discrete intervals in the past hour. Computes mean and standard
* deviation of these samples, and returns "ground truth" bounds that should enclose ~95% of trading activity
* @return bounds The "ground truth" price range that will be used when computing rewards
* @return shouldInvertPricesNext Whether proposals in the next epoch should be submitted with inverted bounds
*/
function fetchGroundTruth() external view returns (Bounds memory bounds, bool shouldInvertPricesNext);
/**
* @notice Builds a memory array that can be passed to Uniswap V3's `observe` function to specify
* intervals over which mean prices should be fetched
* @return secondsAgos From how long ago each cumulative tick and liquidity value should be returned
*/
function selectedOracleTimetable() external pure returns (uint32[] memory secondsAgos);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
interface IAloePredictionsEvents {
event ProposalSubmitted(
address indexed source,
uint24 indexed epoch,
uint40 key,
uint176 lower,
uint176 upper,
uint80 stake
);
event ProposalUpdated(address indexed source, uint24 indexed epoch, uint40 key, uint176 lower, uint176 upper);
event FetchedGroundTruth(uint176 lower, uint176 upper, bool didInvertPrices);
event Advanced(uint24 epoch, uint32 epochStartTime);
event ClaimedReward(address indexed recipient, uint24 indexed epoch, uint40 key, uint80 amount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../structs/EpochSummary.sol";
import "../structs/Proposal.sol";
interface IAloePredictionsState {
/// @dev A mapping containing every proposal. These get deleted when claimed
function proposals(uint40 key)
external
view
returns (
address source,
uint24 submissionEpoch,
uint176 lower,
uint176 upper,
uint80 stake
);
/// @dev The unique ID that will be assigned to the next submitted proposal
function nextProposalKey() external view returns (uint40);
/// @dev The current epoch. May increase up to once per hour. Never decreases
function epoch() external view returns (uint24);
/// @dev The time at which the current epoch started
function epochStartTime() external view returns (uint32);
/// @dev Whether new proposals should be submitted with inverted prices
function shouldInvertPrices() external view returns (bool);
/// @dev Whether proposals in `epoch - 1` were submitted with inverted prices
function didInvertPrices() external view returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
struct Bounds {
// Q128.48 price at tickLower of a Uniswap position
uint176 lower;
// Q128.48 price at tickUpper of a Uniswap position
uint176 upper;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./Accumulators.sol";
import "./Bounds.sol";
struct EpochSummary {
Bounds groundTruth;
Accumulators accumulators;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
struct Proposal {
// The address that submitted the proposal
address source;
// The epoch in which the proposal was submitted
uint24 epoch;
// Q128.48 price at tickLower of proposed Uniswap position
uint176 lower;
// Q128.48 price at tickUpper of proposed Uniswap position
uint176 upper;
// The amount of ALOE held; fits in uint80 because max supply is 1000000 with 18 decimals
uint80 stake;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../libraries/UINT512.sol";
struct Accumulators {
// The number of (proposals added - proposals removed) during the epoch
uint40 proposalCount;
// The total amount of ALOE staked; fits in uint80 because max supply is 1000000 with 18 decimals
uint80 stakeTotal;
// For the remaining properties, read comments as if `stake`, `lower`, and `upper` are NumPy arrays.
// Each index represents a proposal, e.g. proposal 0 would be `(stake[0], lower[0], upper[0])`
// `(stake * (upper - lower)).sum()`
uint256 stake0thMomentRaw;
// `lower.sum()`
uint256 sumOfLowerBounds;
// `(stake * lower).sum()`
uint256 sumOfLowerBoundsWeighted;
// `upper.sum()`
uint256 sumOfUpperBounds;
// `(stake * upper).sum()`
uint256 sumOfUpperBoundsWeighted;
// `(np.square(lower) + np.square(upper)).sum()`
UINT512 sumOfSquaredBounds;
// `(stake * (np.square(lower) + np.square(upper))).sum()`
UINT512 sumOfSquaredBoundsWeighted;
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity ^0.8.0;
import "./FullMath.sol";
struct UINT512 {
// Least significant bits
uint256 LS;
// Most significant bits
uint256 MS;
}
library UINT512Math {
/// @dev Adds an (LS, MS) pair in place. Assumes result fits in uint512
function iadd(
UINT512 storage self,
uint256 LS,
uint256 MS
) internal {
unchecked {
if (self.LS > type(uint256).max - LS) {
self.LS = addmod(self.LS, LS, type(uint256).max);
self.MS += 1 + MS;
} else {
self.LS += LS;
self.MS += MS;
}
}
}
/// @dev Adds an (LS, MS) pair to self. Assumes result fits in uint512
function add(
UINT512 memory self,
uint256 LS,
uint256 MS
) internal pure returns (uint256, uint256) {
unchecked {
return
(self.LS > type(uint256).max - LS)
? (addmod(self.LS, LS, type(uint256).max), self.MS + MS + 1)
: (self.LS + LS, self.MS + MS);
}
}
/// @dev Subtracts an (LS, MS) pair in place. Assumes result > 0
function isub(
UINT512 storage self,
uint256 LS,
uint256 MS
) internal {
unchecked {
if (self.LS < LS) {
self.LS = type(uint256).max + self.LS - LS;
self.MS -= 1 + MS;
} else {
self.LS -= LS;
self.MS -= MS;
}
}
}
/// @dev Subtracts an (LS, MS) pair from self. Assumes result > 0
function sub(
UINT512 memory self,
uint256 LS,
uint256 MS
) internal pure returns (uint256, uint256) {
unchecked {
return (self.LS < LS) ? (type(uint256).max + self.LS - LS, self.MS - MS - 1) : (self.LS - LS, self.MS - MS);
}
}
/// @dev Multiplies self by single uint256, s. Assumes result fits in uint512
function muls(UINT512 memory self, uint256 s) internal pure returns (uint256, uint256) {
unchecked {
self.MS *= s;
(self.LS, s) = FullMath.mul512(self.LS, s);
return (self.LS, self.MS + s);
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./draft-IERC20Permit.sol";
import "../ERC20.sol";
import "../../../utils/cryptography/draft-EIP712.sol";
import "../../../utils/cryptography/ECDSA.sol";
import "../../../utils/Counters.sol";
/**
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*
* _Available since v3.4._
*/
abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 {
using Counters for Counters.Counter;
mapping (address => Counters.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
constructor(string memory name) EIP712(name, "1") {
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash = keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_useNonce(owner),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = ECDSA.recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_approve(owner, spender, value);
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view virtual override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
/**
* @dev "Consume a nonce": return the current value and increment.
*
* _Available since v4.1._
*/
function _useNonce(address owner) internal virtual returns (uint256 current) {
Counters.Counter storage nonce = _nonces[owner];
current = nonce.current();
nonce.increment();
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20Permit {
/**
* @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens,
* given ``owner``'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./IERC20.sol";
import "./extensions/IERC20Metadata.sol";
import "../../utils/Context.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20, IERC20Metadata {
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
/**
* @dev Sets the values for {name} and {symbol}.
*
* The defaut value of {decimals} is 18. To select a different value for
* {decimals} you should overload it.
*
* All two of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev Returns the name of the token.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless this function is
* overridden;
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view virtual override returns (uint8) {
return 18;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view virtual override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
uint256 currentAllowance = _allowances[sender][_msgSender()];
require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance");
_approve(sender, _msgSender(), currentAllowance - amount);
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
uint256 currentAllowance = _allowances[_msgSender()][spender];
require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero");
_approve(_msgSender(), spender, currentAllowance - subtractedValue);
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
uint256 senderBalance = _balances[sender];
require(senderBalance >= amount, "ERC20: transfer amount exceeds balance");
_balances[sender] = senderBalance - amount;
_balances[recipient] += amount;
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply += amount;
_balances[account] += amount;
emit Transfer(address(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 { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "./ECDSA.sol";
/**
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*
* _Available since v3.4._
*/
abstract contract EIP712 {
/* solhint-disable var-name-mixedcase */
// Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to
// invalidate the cached domain separator if the chain id changes.
bytes32 private immutable _CACHED_DOMAIN_SEPARATOR;
uint256 private immutable _CACHED_CHAIN_ID;
bytes32 private immutable _HASHED_NAME;
bytes32 private immutable _HASHED_VERSION;
bytes32 private immutable _TYPE_HASH;
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
constructor(string memory name, string memory version) {
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
bytes32 typeHash = keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)");
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
_CACHED_CHAIN_ID = block.chainid;
_CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion);
_TYPE_HASH = typeHash;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
if (block.chainid == _CACHED_CHAIN_ID) {
return _CACHED_DOMAIN_SEPARATOR;
} else {
return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION);
}
}
function _buildDomainSeparator(bytes32 typeHash, bytes32 name, bytes32 version) private view returns (bytes32) {
return keccak256(
abi.encode(
typeHash,
name,
version,
block.chainid,
address(this)
)
);
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) {
return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.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.
*
* IMPORTANT: `hash` _must_ be the result of a hash operation for the
* verification to be secure: it is possible to craft signatures that
* recover to arbitrary addresses for non-hashed data. A safe way to ensure
* this is by receiving a hash of the original message (which may otherwise
* be too long), and then calling {toEthSignedMessageHash} on it.
*/
function recover(bytes32 hash, bytes memory signature) internal pure returns (address) {
// Divide the signature in r, s and v variables
bytes32 r;
bytes32 s;
uint8 v;
// Check the signature length
// - case 65: r,s,v signature (standard)
// - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._
if (signature.length == 65) {
// 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)))
}
} else if (signature.length == 64) {
// 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 {
let vs := mload(add(signature, 0x40))
r := mload(add(signature, 0x20))
s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff)
v := add(shr(255, vs), 27)
}
} else {
revert("ECDSA: invalid signature length");
}
return recover(hash, v, r, s);
}
/**
* @dev Overload of {ECDSA-recover} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
// 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.
require(uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0, "ECDSA: invalid signature 's' value");
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev Returns an Ethereum Signed Message, created from a `hash`. This
* produces hash corresponding to the one signed with the
* https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`]
* JSON-RPC method as part of EIP-191.
*
* See {recover}.
*/
function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) {
// 32 is the length in bytes of hash,
// enforced by the type signature above
return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash));
}
/**
* @dev Returns an Ethereum Signed Typed Data, created from a
* `domainSeparator` and a `structHash`. This produces hash corresponding
* to the one signed with the
* https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`]
* JSON-RPC method as part of EIP-712.
*
* See {recover}.
*/
function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
*/
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;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
import "../IERC20.sol";
/**
* @dev Interface for the optional metadata functions from the ERC20 standard.
*
* _Available since v4.1._
*/
interface IERC20Metadata is IERC20 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the decimals places of the token.
*/
function decimals() external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: GPL-2.0-or-later
pragma solidity >=0.5.0;
/// @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;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
struct Ticks {
// Lower tick of a Uniswap position
int24 lower;
// Upper tick of a Uniswap position
int24 upper;
}
|
Deposits liquidity in a range on the Uniswap pool.
|
function _uniswapEnter(Ticks memory ticks, uint128 liquidity) internal {
if (liquidity == 0) return;
UNI_POOL.mint(address(this), ticks.lower, ticks.upper, liquidity, "");
}
| 1,371,958 |
pragma solidity ^0.4.18;
/**
* Overflow aware uint math functions.
*/
library SafeMath {
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 && c>=b);
return c;
}
}
/**
* @title ERC20Token interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20Token {
uint256 public totalSupply;
function balanceOf(address who) public constant returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
function allowance(address owner, address spender) public constant returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @title BasicToken interface
* @dev Implementation of the basic standard token.
*/
contract BasicToken is ERC20Token {
using SafeMath for uint256;
mapping(address => uint256) balances;
mapping(address => mapping (address => uint256)) allowed;
/**
* @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));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public constant returns (uint256 balance) {
return balances[_owner];
}
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
uint256 _allowance = allowed[_from][msg.sender];
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = _allowance.sub(_value);
Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public constant returns (uint256 remaining) {
return allowed[_owner][_spender];
}
function increaseApproval (address _spender, uint _addedValue) public
returns (bool success) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
function decreaseApproval (address _spender, uint _subtractedValue) public
returns (bool success) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Owned
* functions, this simplifies the implementation of "user permissions".
*/
contract Owned {
address public owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
function Owned () internal {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
function transferOwnership(address newOwner) onlyOwner public {
require(newOwner != address(0));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
contract USISampleToken is BasicToken, Owned {
string public version = "1.0";
string public name = "USISample Token";
string public symbol = "USISample";
uint8 public decimals = 18;
mapping(address=>uint256) lockedBalance;
mapping(address=>uint) timeRelease;
uint256 internal constant INITIAL_SUPPLY = 500 * (10**6) * (10 **18);
uint256 internal constant DEVELOPER_RESERVED = 175 * (10**6) * (10**18);
event Burn(address indexed burner, uint256 value);
event Lock(address indexed locker, uint256 value, uint releaseTime);
event UnLock(address indexed unlocker, uint256 value);
function USISampleToken(address _developer) public {
balances[_developer] = DEVELOPER_RESERVED;
totalSupply = DEVELOPER_RESERVED;
}
function lockedOf(address _owner) public constant returns (uint256 balance) {
return lockedBalance[_owner];
}
function unlockTimeOf(address _owner) public constant returns (uint timelimit) {
return timeRelease[_owner];
}
function transferAndLock(address _to, uint256 _value, uint _releaseTime) public returns (bool success) {
require(_to != 0x0);
require(_value <= balances[msg.sender]);
require(_value > 0);
require(_releaseTime > now && _releaseTime <= now + 60*60*24*365*5);
balances[msg.sender] = balances[msg.sender].sub(_value);
uint preRelease = timeRelease[_to];
if (preRelease <= now && preRelease != 0x0) {
balances[_to] = balances[_to].add(lockedBalance[_to]);
lockedBalance[_to] = 0;
}
lockedBalance[_to] = lockedBalance[_to].add(_value);
timeRelease[_to] = _releaseTime >= timeRelease[_to] ? _releaseTime : timeRelease[_to];
Transfer(msg.sender, _to, _value);
Lock(_to, _value, _releaseTime);
return true;
}
/**
* @notice Transfers tokens held by lock.
*/
function unlock() public returns (bool success){
uint256 amount = lockedBalance[msg.sender];
require(amount > 0);
require(now >= timeRelease[msg.sender]);
balances[msg.sender] = balances[msg.sender].add(amount);
lockedBalance[msg.sender] = 0;
timeRelease[msg.sender] = 0;
Transfer(0x0, msg.sender, amount);
UnLock(msg.sender, amount);
return true;
}
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public returns (bool success) {
require(_value > 0);
require(_value <= balances[msg.sender]);
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(burner, _value);
return true;
}
function isSoleout() public constant returns (bool) {
return (totalSupply >= INITIAL_SUPPLY);
}
modifier canMint() {
require(!isSoleout());
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount, uint256 _lockAmount, uint _releaseTime) onlyOwner canMint public returns (bool) {
totalSupply = totalSupply.add(_amount);
balances[_to] = balances[_to].add(_amount);
if (_lockAmount > 0) {
totalSupply = totalSupply.add(_lockAmount);
lockedBalance[_to] = lockedBalance[_to].add(_lockAmount);
timeRelease[_to] = _releaseTime >= timeRelease[_to] ? _releaseTime : timeRelease[_to];
Lock(_to, _lockAmount, _releaseTime);
}
Transfer(0x0, _to, _amount);
return true;
}
}
|
transfer token for a specified address _to The address to transfer to. _value The amount to be transferred./
|
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
Transfer(msg.sender, _to, _value);
return true;
}
| 12,686,557 |
./full_match/1/0xaf4920C0D5C6cCFd297decEa77e5516c6184F2DB/sources/@1inch/solidity-utils/contracts/libraries/ECDSA.sol
|
@solidity memory-safe-assembly
|
function recover(bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal view returns(address signer) {
let ptr := mload(0x40)
mstore(ptr, hash)
mstore(add(ptr, 0x20), v)
mstore(add(ptr, 0x40), r)
mstore(add(ptr, 0x60), s)
if staticcall(gas(), 0x1, ptr, 0x80, 0, 0x20) {
signer := mload(0)
}
}
| 17,000,946 |
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "../interface/RocketStorageInterface.sol";
/// @title Base settings / modifiers for each contract in Rocket Pool
/// @author David Rugendyke
abstract contract RocketBase {
// Calculate using this as the base
uint256 constant calcBase = 1 ether;
// Version of the contract
uint8 public version;
// The main storage contract where primary persistant storage is maintained
RocketStorageInterface rocketStorage = RocketStorageInterface(0);
/*** Modifiers **********************************************************/
/**
* @dev Throws if called by any sender that doesn't match a Rocket Pool network contract
*/
modifier onlyLatestNetworkContract() {
require(getBool(keccak256(abi.encodePacked("contract.exists", msg.sender))), "Invalid or outdated network contract");
_;
}
/**
* @dev Throws if called by any sender that doesn't match one of the supplied contract or is the latest version of that contract
*/
modifier onlyLatestContract(string memory _contractName, address _contractAddress) {
require(_contractAddress == getAddress(keccak256(abi.encodePacked("contract.address", _contractName))), "Invalid or outdated contract");
_;
}
/**
* @dev Throws if called by any sender that isn't a registered node
*/
modifier onlyRegisteredNode(address _nodeAddress) {
require(getBool(keccak256(abi.encodePacked("node.exists", _nodeAddress))), "Invalid node");
_;
}
/**
* @dev Throws if called by any sender that isn't a trusted node DAO member
*/
modifier onlyTrustedNode(address _nodeAddress) {
require(getBool(keccak256(abi.encodePacked("dao.trustednodes.", "member", _nodeAddress))), "Invalid trusted node");
_;
}
/**
* @dev Throws if called by any sender that isn't a registered minipool
*/
modifier onlyRegisteredMinipool(address _minipoolAddress) {
require(getBool(keccak256(abi.encodePacked("minipool.exists", _minipoolAddress))), "Invalid minipool");
_;
}
/**
* @dev Throws if called by any account other than a guardian account (temporary account allowed access to settings before DAO is fully enabled)
*/
modifier onlyGuardian() {
require(msg.sender == rocketStorage.getGuardian(), "Account is not a temporary guardian");
_;
}
/*** Methods **********************************************************/
/// @dev Set the main Rocket Storage address
constructor(RocketStorageInterface _rocketStorageAddress) {
// Update the contract address
rocketStorage = RocketStorageInterface(_rocketStorageAddress);
}
/// @dev Get the address of a network contract by name
function getContractAddress(string memory _contractName) internal view returns (address) {
// Get the current contract address
address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName)));
// Check it
require(contractAddress != address(0x0), "Contract not found");
// Return
return contractAddress;
}
/// @dev Get the address of a network contract by name (returns address(0x0) instead of reverting if contract does not exist)
function getContractAddressUnsafe(string memory _contractName) internal view returns (address) {
// Get the current contract address
address contractAddress = getAddress(keccak256(abi.encodePacked("contract.address", _contractName)));
// Return
return contractAddress;
}
/// @dev Get the name of a network contract by address
function getContractName(address _contractAddress) internal view returns (string memory) {
// Get the contract name
string memory contractName = getString(keccak256(abi.encodePacked("contract.name", _contractAddress)));
// Check it
require(bytes(contractName).length > 0, "Contract not found");
// Return
return contractName;
}
/// @dev Get revert error message from a .call method
function getRevertMsg(bytes memory _returnData) internal pure returns (string memory) {
// If the _res length is less than 68, then the transaction failed silently (without a revert message)
if (_returnData.length < 68) return "Transaction reverted silently";
assembly {
// Slice the sighash.
_returnData := add(_returnData, 0x04)
}
return abi.decode(_returnData, (string)); // All that remains is the revert string
}
/*** Rocket Storage Methods ****************************************/
// Note: Unused helpers have been removed to keep contract sizes down
/// @dev Storage get methods
function getAddress(bytes32 _key) internal view returns (address) { return rocketStorage.getAddress(_key); }
function getUint(bytes32 _key) internal view returns (uint) { return rocketStorage.getUint(_key); }
function getString(bytes32 _key) internal view returns (string memory) { return rocketStorage.getString(_key); }
function getBytes(bytes32 _key) internal view returns (bytes memory) { return rocketStorage.getBytes(_key); }
function getBool(bytes32 _key) internal view returns (bool) { return rocketStorage.getBool(_key); }
function getInt(bytes32 _key) internal view returns (int) { return rocketStorage.getInt(_key); }
function getBytes32(bytes32 _key) internal view returns (bytes32) { return rocketStorage.getBytes32(_key); }
/// @dev Storage set methods
function setAddress(bytes32 _key, address _value) internal { rocketStorage.setAddress(_key, _value); }
function setUint(bytes32 _key, uint _value) internal { rocketStorage.setUint(_key, _value); }
function setString(bytes32 _key, string memory _value) internal { rocketStorage.setString(_key, _value); }
function setBytes(bytes32 _key, bytes memory _value) internal { rocketStorage.setBytes(_key, _value); }
function setBool(bytes32 _key, bool _value) internal { rocketStorage.setBool(_key, _value); }
function setInt(bytes32 _key, int _value) internal { rocketStorage.setInt(_key, _value); }
function setBytes32(bytes32 _key, bytes32 _value) internal { rocketStorage.setBytes32(_key, _value); }
/// @dev Storage delete methods
function deleteAddress(bytes32 _key) internal { rocketStorage.deleteAddress(_key); }
function deleteUint(bytes32 _key) internal { rocketStorage.deleteUint(_key); }
function deleteString(bytes32 _key) internal { rocketStorage.deleteString(_key); }
function deleteBytes(bytes32 _key) internal { rocketStorage.deleteBytes(_key); }
function deleteBool(bytes32 _key) internal { rocketStorage.deleteBool(_key); }
function deleteInt(bytes32 _key) internal { rocketStorage.deleteInt(_key); }
function deleteBytes32(bytes32 _key) internal { rocketStorage.deleteBytes32(_key); }
/// @dev Storage arithmetic methods
function addUint(bytes32 _key, uint256 _amount) internal { rocketStorage.addUint(_key, _amount); }
function subUint(bytes32 _key, uint256 _amount) internal { rocketStorage.subUint(_key, _amount); }
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "../../../RocketBase.sol";
import "../../../../interface/dao/protocol/settings/RocketDAOProtocolSettingsInterface.sol";
// Settings in RP which the DAO will have full control over
// This settings contract enables storage using setting paths with namespaces, rather than explicit set methods
abstract contract RocketDAOProtocolSettings is RocketBase, RocketDAOProtocolSettingsInterface {
// The namespace for a particular group of settings
bytes32 settingNameSpace;
// Only allow updating from the DAO proposals contract
modifier onlyDAOProtocolProposal() {
// If this contract has been initialised, only allow access from the proposals contract
if(getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) require(getContractAddress("rocketDAOProtocolProposals") == msg.sender, "Only DAO Protocol Proposals contract can update a setting");
_;
}
// Construct
constructor(RocketStorageInterface _rocketStorageAddress, string memory _settingNameSpace) RocketBase(_rocketStorageAddress) {
// Apply the setting namespace
settingNameSpace = keccak256(abi.encodePacked("dao.protocol.setting.", _settingNameSpace));
}
/*** Uints ****************/
// A general method to return any setting given the setting path is correct, only accepts uints
function getSettingUint(string memory _settingPath) public view override returns (uint256) {
return getUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)));
}
// Update a Uint setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed
function setSettingUint(string memory _settingPath, uint256 _value) virtual public override onlyDAOProtocolProposal {
// Update setting now
setUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
/*** Bools ****************/
// A general method to return any setting given the setting path is correct, only accepts bools
function getSettingBool(string memory _settingPath) public view override returns (bool) {
return getBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath)));
}
// Update a setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed
function setSettingBool(string memory _settingPath, bool _value) virtual public override onlyDAOProtocolProposal {
// Update setting now
setBool(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
/*** Addresses ****************/
// A general method to return any setting given the setting path is correct, only accepts addresses
function getSettingAddress(string memory _settingPath) external view override returns (address) {
return getAddress(keccak256(abi.encodePacked(settingNameSpace, _settingPath)));
}
// Update a setting, can only be executed by the DAO contract when a majority on a setting proposal has passed and been executed
function setSettingAddress(string memory _settingPath, address _value) virtual external override onlyDAOProtocolProposal {
// Update setting now
setAddress(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
import "./RocketDAOProtocolSettings.sol";
import "../../../../interface/dao/protocol/settings/RocketDAOProtocolSettingsNetworkInterface.sol";
// Network auction settings
contract RocketDAOProtocolSettingsNetwork is RocketDAOProtocolSettings, RocketDAOProtocolSettingsNetworkInterface {
// Construct
constructor(RocketStorageInterface _rocketStorageAddress) RocketDAOProtocolSettings(_rocketStorageAddress, "network") {
// Set version
version = 1;
// Initialize settings on deployment
if(!getBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")))) {
// Apply settings
setSettingUint("network.consensus.threshold", 0.51 ether); // 51%
setSettingBool("network.submit.balances.enabled", true);
setSettingUint("network.submit.balances.frequency", 5760); // ~24 hours
setSettingBool("network.submit.prices.enabled", true);
setSettingUint("network.submit.prices.frequency", 5760); // ~24 hours
setSettingUint("network.node.fee.minimum", 0.15 ether); // 15%
setSettingUint("network.node.fee.target", 0.15 ether); // 15%
setSettingUint("network.node.fee.maximum", 0.15 ether); // 15%
setSettingUint("network.node.fee.demand.range", 160 ether);
setSettingUint("network.reth.collateral.target", 0.1 ether);
setSettingUint("network.reth.deposit.delay", 5760); // ~24 hours
// Settings initialised
setBool(keccak256(abi.encodePacked(settingNameSpace, "deployed")), true);
}
}
// Update a setting, overrides inherited setting method with extra checks for this contract
function setSettingUint(string memory _settingPath, uint256 _value) override public onlyDAOProtocolProposal {
// Some safety guards for certain settings
// Prevent DAO from setting the withdraw delay greater than ~24 hours
if(keccak256(bytes(_settingPath)) == keccak256(bytes("network.reth.deposit.delay"))) {
// Must be a future timestamp
require(_value <= 5760, "rETH deposit delay cannot exceed 5760 blocks");
}
// Update setting now
setUint(keccak256(abi.encodePacked(settingNameSpace, _settingPath)), _value);
}
// The threshold of trusted nodes that must reach consensus on oracle data to commit it
function getNodeConsensusThreshold() override external view returns (uint256) {
return getSettingUint("network.consensus.threshold");
}
// Submit balances currently enabled (trusted nodes only)
function getSubmitBalancesEnabled() override external view returns (bool) {
return getSettingBool("network.submit.balances.enabled");
}
// The frequency in blocks at which network balances should be submitted by trusted nodes
function getSubmitBalancesFrequency() override external view returns (uint256) {
return getSettingUint("network.submit.balances.frequency");
}
// Submit prices currently enabled (trusted nodes only)
function getSubmitPricesEnabled() override external view returns (bool) {
return getSettingBool("network.submit.prices.enabled");
}
// The frequency in blocks at which network prices should be submitted by trusted nodes
function getSubmitPricesFrequency() override external view returns (uint256) {
return getSettingUint("network.submit.prices.frequency");
}
// The minimum node commission rate as a fraction of 1 ether
function getMinimumNodeFee() override external view returns (uint256) {
return getSettingUint("network.node.fee.minimum");
}
// The target node commission rate as a fraction of 1 ether
function getTargetNodeFee() override external view returns (uint256) {
return getSettingUint("network.node.fee.target");
}
// The maximum node commission rate as a fraction of 1 ether
function getMaximumNodeFee() override external view returns (uint256) {
return getSettingUint("network.node.fee.maximum");
}
// The range of node demand values to base fee calculations on (from negative to positive value)
function getNodeFeeDemandRange() override external view returns (uint256) {
return getSettingUint("network.node.fee.demand.range");
}
// Target rETH collateralization rate as a fraction of 1 ether
function getTargetRethCollateralRate() override external view returns (uint256) {
return getSettingUint("network.reth.collateral.target");
}
// rETH withdraw delay in blocks
function getRethDepositDelay() override external view returns (uint256) {
return getSettingUint("network.reth.deposit.delay");
}
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketStorageInterface {
// Deploy status
function getDeployedStatus() external view returns (bool);
// Guardian
function getGuardian() external view returns(address);
function setGuardian(address _newAddress) external;
function confirmGuardian() external;
// Getters
function getAddress(bytes32 _key) external view returns (address);
function getUint(bytes32 _key) external view returns (uint);
function getString(bytes32 _key) external view returns (string memory);
function getBytes(bytes32 _key) external view returns (bytes memory);
function getBool(bytes32 _key) external view returns (bool);
function getInt(bytes32 _key) external view returns (int);
function getBytes32(bytes32 _key) external view returns (bytes32);
// Setters
function setAddress(bytes32 _key, address _value) external;
function setUint(bytes32 _key, uint _value) external;
function setString(bytes32 _key, string calldata _value) external;
function setBytes(bytes32 _key, bytes calldata _value) external;
function setBool(bytes32 _key, bool _value) external;
function setInt(bytes32 _key, int _value) external;
function setBytes32(bytes32 _key, bytes32 _value) external;
// Deleters
function deleteAddress(bytes32 _key) external;
function deleteUint(bytes32 _key) external;
function deleteString(bytes32 _key) external;
function deleteBytes(bytes32 _key) external;
function deleteBool(bytes32 _key) external;
function deleteInt(bytes32 _key) external;
function deleteBytes32(bytes32 _key) external;
// Arithmetic
function addUint(bytes32 _key, uint256 _amount) external;
function subUint(bytes32 _key, uint256 _amount) external;
// Protected storage
function getNodeWithdrawalAddress(address _nodeAddress) external view returns (address);
function getNodePendingWithdrawalAddress(address _nodeAddress) external view returns (address);
function setWithdrawalAddress(address _nodeAddress, address _newWithdrawalAddress, bool _confirm) external;
function confirmWithdrawalAddress(address _nodeAddress) external;
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketDAOProtocolSettingsInterface {
function getSettingUint(string memory _settingPath) external view returns (uint256);
function setSettingUint(string memory _settingPath, uint256 _value) external;
function getSettingBool(string memory _settingPath) external view returns (bool);
function setSettingBool(string memory _settingPath, bool _value) external;
function getSettingAddress(string memory _settingPath) external view returns (address);
function setSettingAddress(string memory _settingPath, address _value) external;
}
/**
* .
* / \
* |.'.|
* |'.'|
* ,'| |`.
* |,-'-|-'-.|
* __|_| | _ _ _____ _
* | ___ \| | | | | | ___ \ | |
* | |_/ /|__ ___| | _____| |_ | |_/ /__ ___ | |
* | // _ \ / __| |/ / _ \ __| | __/ _ \ / _ \| |
* | |\ \ (_) | (__| < __/ |_ | | | (_) | (_) | |
* \_| \_\___/ \___|_|\_\___|\__| \_| \___/ \___/|_|
* +---------------------------------------------------+
* | DECENTRALISED STAKING PROTOCOL FOR ETHEREUM |
* +---------------------------------------------------+
*
* Rocket Pool is a first-of-its-kind Ethereum staking pool protocol, designed to
* be community-owned, decentralised, and trustless.
*
* For more information about Rocket Pool, visit https://rocketpool.net
*
* Authors: David Rugendyke, Jake Pospischil, Kane Wallmann, Darren Langley, Joe Clapis, Nick Doherty
*
*/
pragma solidity 0.7.6;
// SPDX-License-Identifier: GPL-3.0-only
interface RocketDAOProtocolSettingsNetworkInterface {
function getNodeConsensusThreshold() external view returns (uint256);
function getSubmitBalancesEnabled() external view returns (bool);
function getSubmitBalancesFrequency() external view returns (uint256);
function getSubmitPricesEnabled() external view returns (bool);
function getSubmitPricesFrequency() external view returns (uint256);
function getMinimumNodeFee() external view returns (uint256);
function getTargetNodeFee() external view returns (uint256);
function getMaximumNodeFee() external view returns (uint256);
function getNodeFeeDemandRange() external view returns (uint256);
function getTargetRethCollateralRate() external view returns (uint256);
function getRethDepositDelay() external view returns (uint256);
}
|
The maximum node commission rate as a fraction of 1 ether
|
function getMaximumNodeFee() override external view returns (uint256) {
return getSettingUint("network.node.fee.maximum");
}
| 5,983,039 |
./partial_match/42220/0x84Bb1795b699Bf7a798C0d63e9Aad4c96B0830f4/sources/contracts/MoolaStakingRewards.sol
|
XXX: removed notPaused
|
function stake(uint256 amount) external override nonReentrant updateReward(msg.sender) {
require(amount > 0, "Cannot stake 0");
_totalSupply = _totalSupply.add(amount);
_balances[msg.sender] = _balances[msg.sender].add(amount);
stakingToken.safeTransferFrom(msg.sender, address(this), amount);
stakingToken.approve(address(externalStakingRewards), amount);
externalStakingRewards.stake(amount);
emit Staked(msg.sender, amount);
}
| 3,497,828 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @artist: Anna Ridler
/// @author: manifold.xyz
import "@prb/math/contracts/PRBMathSD59x18.sol";
import "./libraries/Trigonometry.sol";
import "./libraries/BokkyPooBahsDateTimeLibrary.sol";
import "./dynamic/DynamicArweaveHash.sol";
import "./extensions/ERC721/IERC721CreatorExtensionApproveTransfer.sol";
contract AnnoOxypetalum is DynamicArweaveHash, IERC721CreatorExtensionApproveTransfer {
using PRBMathSD59x18 for int256;
uint256 private _baseTokenId;
uint8 private _seasonOnLastTransfer;
// Seasons
uint8 constant private _WINTER = 0;
uint8 constant private _SPRING = 1;
uint8 constant private _SUMMER = 2;
uint8 constant private _FALL = 3;
// Constants
int256 constant private _DAY_IN_SECONDS = 86400000000000000000000;
int256 constant private _JULIAN_EPOCH = 2440587500000000000000000;
int256 constant private _JULIAN_2000 = 2451545000000000000000000;
int256 constant private _JULIAN_CENTURY = 36525000000000000000000;
int256 immutable _D2R = PRBMathSD59x18.pi().div(180000000000000000000);
// In-memory Arrays
function _springConstants() private pure returns (int256[5] memory) {
int256[5] memory constants =
[int(2451623809840000000000000),
365242374040000000000000,
51690000000000000,
-4110000000000000,
-570000000000000];
return constants;
}
function _summerConstants() private pure returns (int256[5] memory) {
int256[5] memory constants =
[int(2451716567670000000000000),
365241626030000000000000,
3250000000000000,
8880000000000000,
-300000000000000];
return constants;
}
function _fallConstants() private pure returns (int256[5] memory) {
int256[5] memory constants =
[int(2451810217150000000000000),
365242017670000000000000,
-115750000000000000,
3370000000000000,
780000000000000];
return constants;
}
function _winterConstants() private pure returns (int256[5] memory) {
int256[5] memory constants =
[int(2451900059520000000000000),
365242740490000000000000,
-62230000000000000,
-8230000000000000,
320000000000000];
return constants;
}
function _termsConstants() private pure returns (int256[3][24] memory) {
int256[3][24] memory constants =
[
[int(485000000000000000000), 324960000000000000000, 1934136000000000000000],
[int(203000000000000000000), 337230000000000000000, 32964467000000000000000],
[int(199000000000000000000), 342080000000000000000, 20186000000000000000],
[int(182000000000000000000), 27850000000000000000, 445267112000000000000000],
[int(156000000000000000000), 73140000000000000000, 45036886000000000000000],
[int(136000000000000000000), 171520000000000000000, 22518443000000000000000],
[int(77000000000000000000), 222540000000000000000, 65928934000000000000000],
[int(74000000000000000000), 296720000000000000000, 3034906000000000000000],
[int(70000000000000000000), 243580000000000000000, 9037513000000000000000],
[int(58000000000000000000), 119810000000000000000, 33718147000000000000000],
[int(52000000000000000000), 297170000000000000000, 150678000000000000000],
[int(50000000000000000000), 21020000000000000000, 2281226000000000000000],
[int(45000000000000000000), 247540000000000000000, 29929562000000000000000],
[int(44000000000000000000), 325150000000000000000, 31555956000000000000000],
[int(29000000000000000000), 60930000000000000000, 4443417000000000000000],
[int(18000000000000000000), 155120000000000000000, 67555328000000000000000],
[int(17000000000000000000), 288790000000000000000, 4562452000000000000000],
[int(16000000000000000000), 198040000000000000000, 62894029000000000000000],
[int(14000000000000000000), 199760000000000000000, 31436921000000000000000],
[int(12000000000000000000), 95390000000000000000, 14577848000000000000000],
[int(12000000000000000000), 287110000000000000000, 31931756000000000000000],
[int(12000000000000000000), 320810000000000000000, 34777259000000000000000],
[int(9000000000000000000), 227730000000000000000, 1222114000000000000000],
[int(8000000000000000000), 15450000000000000000, 16859074000000000000000]
];
return constants;
}
constructor(address creator) ERC721SingleCreatorExtension(creator) {}
function supportsInterface(bytes4 interfaceId) public view virtual override(DynamicArweaveHash, IERC165) returns (bool) {
return interfaceId == type(IERC721CreatorExtensionApproveTransfer).interfaceId || super.supportsInterface(interfaceId);
}
function mint(address to) public virtual onlyOwner returns(uint256) {
require(_baseTokenId == 0, "Already minted");
_baseTokenId = _mint(to);
return _baseTokenId;
}
function setApproveTransfer(address creator, bool enabled) public override onlyOwner {
IERC721CreatorCore(creator).setApproveTransferExtension(enabled);
}
function approveTransfer(address, address, uint256) public override returns (bool) {
require(msg.sender == _creator, "Invalid requester");
_seasonOnLastTransfer = _currentSeason();
return true;
}
function tokenURI(address, uint256 tokenId) external view override returns (string memory) {
return string(abi.encodePacked(
'data:application/json;utf8,{"name":"',_getName(),
'", "description":"',_getDescription(),
'", "image":"https://arweave.net/',_getImageHash(tokenId),
'", "animation_url":"https://arweave.net/',_getAnimationHash(tokenId),
'", "attributes":[',
_wrapTrait("Artist", "Anna Ridler"),
']',
'}'));
}
function _getName() internal pure override returns(string memory) {
return "Anno oxypetalum";
}
function _getDescription() internal pure override returns(string memory) {
return
"Anno oxypetalum (literally \\\"the year of the pointed petals\\\") is a clock made of the flowers of "
"night-blooming cacti, tracking the amount of light across one year. Each flower represents 10 minutes, "
"each second approximately 2 days. Over the course of the piece the flowers fade in and out as the light "
"ebbs and flows across the seasons. The timing of dawn and dusk is precisely accurate for London starting "
"at the 2021 winter solstice. A third level of time is also incorporated into the work - when the piece "
"is sold, the smart contract is programmed to start the video at the beginning of the season in which it "
"was sold. The smart contract is able to accurately compute the solstices and equinoxes until the year "
"3000. It is inspired by plants\' chrono-biological clocks, by which they bloom and close at fixed times "
"of day. Plants behave this way regardless of external stimuli - a night-blooming cactus, for example, "
"will only bloom at night, even if it is exposed to darkness during the daytime and light at night; a "
"morning glory moved into permanent darkness will still flower in the mornings. The work call backs to "
"Carl Linnaeus\' idea of a horologium florae or floral clock, proposed in his Philosophia Botanica in "
"1751 after observing the phenomenon of certain flowers opening and closing at set times of the day, "
"and harkens back to an earlier, medieval way of delineating time according to the amount of daylight "
"present, before the advent of modern timekeeping.";
}
function _getImageHash(uint256) internal view override returns(string memory) {
return imageArweaveHashes[_seasonOnLastTransfer];
}
function _getAnimationHash(uint256) internal view override returns(string memory) {
return animationArweaveHashes[_seasonOnLastTransfer];
}
function _wrapTrait(string memory trait, string memory value) internal pure returns(string memory) {
return string(abi.encodePacked(
'{"trait_type":"',
trait,
'","value":"',
value,
'"}'
));
}
function _currentSeason() private view returns (uint8) {
int256 year = _timestampToYear(block.timestamp);
int256 month = _timestampToMonth(block.timestamp);
int256 julianDay = _timestampToJulianDay(block.timestamp);
int256[3][24] memory terms = _termsConstants();
if (month < 3) {
return _WINTER;
} else if (month == 3) {
return julianDay < _springEquinox(year, terms) ? _WINTER : _SPRING;
} else if (month < 6) {
return _SPRING;
} else if (month == 6) {
return julianDay < _summerSolstice(year, terms) ? _SPRING : _SUMMER;
} else if (month < 9) {
return _SUMMER;
} else if (month == 9) {
return julianDay < _fallEquinox(year, terms) ? _SUMMER : _FALL;
} else if (month < 12) {
return _FALL;
}
return julianDay < _winterSolstice(year, terms) ? _FALL : _WINTER;
}
function _springEquinox(int256 year, int256[3][24] memory terms) private view returns (int256) {
return _eventJulianDay(year - 2000000000000000000000, _springConstants(), terms);
}
function _summerSolstice(int256 year, int256[3][24] memory terms) private view returns (int256) {
return _eventJulianDay(year - 2000000000000000000000, _summerConstants(), terms);
}
function _fallEquinox(int256 year, int256[3][24] memory terms) private view returns (int256) {
return _eventJulianDay(year - 2000000000000000000000, _fallConstants(), terms);
}
function _winterSolstice(int256 year, int256[3][24] memory terms) private view returns (int256) {
return _eventJulianDay(year - 2000000000000000000000, _winterConstants(), terms);
}
function _eventJulianDay(int256 year, int256[5] memory eventConstants, int256[3][24] memory terms) private view returns (int256) {
int256 J0 = _horner(year.mul(1000000000000000), eventConstants);
int256 T = _J2000Century(J0);
int256 W = _D2R.mul(T).mul(35999373000000000000000) - _D2R.mul(2470000000000000000);
int256 dL = 1000000000000000000 + Trigonometry.cos(uint(W)).mul(33400000000000000) + Trigonometry.cos(uint(W.mul(2000000000000000000))).mul(700000000000000);
int256 S = 0;
for (uint256 i = 24; i > 0; i--) {
int256[3] memory t = terms[i-1];
S += t[0].mul(Trigonometry.cos(uint((t[1] + T.mul(t[2])).mul(_D2R))));
}
return J0 + S.div(dL).mul(10000000000000);
}
function _horner(int256 x, int256[5] memory c) private pure returns (int256) {
uint256 i = c.length - 1;
int256 y = c[i];
while (i > 0) {
i--;
y = y.mul(x) + c[i];
}
return y;
}
function _J2000Century(int256 jde) private pure returns (int256) {
return (jde - _JULIAN_2000).div(_JULIAN_CENTURY);
}
function _timestampToYear(uint256 timestamp) private pure returns (int256) {
return PRBMathSD59x18.fromInt(int(BokkyPooBahsDateTimeLibrary.getYear(timestamp)));
}
function _timestampToMonth(uint256 timestamp) private pure returns (int256) {
return int(BokkyPooBahsDateTimeLibrary.getMonth(timestamp));
}
function _timestampToJulianDay(uint256 timestamp) private pure returns (int256) {
return PRBMathSD59x18.fromInt(int(timestamp)).div(_DAY_IN_SECONDS) + _JULIAN_EPOCH;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* Implement this if you want your extension to approve a transfer
*/
interface IERC721CreatorExtensionApproveTransfer is IERC165 {
/**
* @dev Set whether or not the creator will check the extension for approval of token transfer
*/
function setApproveTransfer(address creator, bool enabled) external;
/**
* @dev Called by creator contract to approve a transfer
*/
function approveTransfer(address from, address to, uint256 tokenId) external returns (bool);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
import "@manifoldxyz/creator-core-solidity/contracts/core/IERC721CreatorCore.sol";
import "@manifoldxyz/creator-core-solidity/contracts/extensions/CreatorExtension.sol";
import "@manifoldxyz/creator-core-solidity/contracts/extensions/ICreatorExtensionTokenURI.sol";
import "../libraries/single-creator/ERC721/ERC721SingleCreatorExtension.sol";
/**
* Extension which allows for the creation of NFTs with dynamically changing image/animation metadata
*/
abstract contract DynamicArweaveHash is ERC721SingleCreatorExtension, CreatorExtension, Ownable, ICreatorExtensionTokenURI {
using Strings for uint256;
string[] public imageArweaveHashes;
string[] public animationArweaveHashes;
function supportsInterface(bytes4 interfaceId) public view virtual override(CreatorExtension, IERC165) returns (bool) {
return interfaceId == type(ICreatorExtensionTokenURI).interfaceId
|| super.supportsInterface(interfaceId);
}
function tokenURI(address, uint256 tokenId) external view virtual override returns (string memory) {
string memory uri = string(abi.encodePacked('data:application/json;utf8,{"name":"', _getName(), '","description":"', _getDescription()));
if (imageArweaveHashes.length > 0) {
uri = string(abi.encodePacked(uri, '", "image":"https://arweave.net/', _getImageHash(tokenId)));
}
if (animationArweaveHashes.length > 0) {
uri = string(abi.encodePacked(uri, '", "animation_url":"https://arweave.net/', _getAnimationHash(tokenId)));
}
uri = string(abi.encodePacked(uri, '"}'));
return uri;
}
function _mint(address to) internal returns(uint256) {
return IERC721CreatorCore(_creator).mintExtension(to);
}
function _getName() internal view virtual returns(string memory);
function _getDescription() internal view virtual returns(string memory);
function _getImageHash(uint256 tokenId) internal view virtual returns(string memory);
function _getAnimationHash(uint256 tokenId) internal view virtual returns(string memory);
function setImageArweaveHashes(string[] memory _arweaveHashes) external virtual onlyOwner {
imageArweaveHashes = _arweaveHashes;
}
function setAnimationAreaveHashes(string[] memory _arweaveHashes) external virtual onlyOwner {
animationArweaveHashes = _arweaveHashes;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.9.0;
// ----------------------------------------------------------------------------
// BokkyPooBah's DateTime Library v1.01
//
// A gas-efficient Solidity date and time library
//
// https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary
//
// Tested date range 1970/01/01 to 2345/12/31
//
// Conventions:
// Unit | Range | Notes
// :-------- |:-------------:|:-----
// timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC
// year | 1970 ... 2345 |
// month | 1 ... 12 |
// day | 1 ... 31 |
// hour | 0 ... 23 |
// minute | 0 ... 59 |
// second | 0 ... 59 |
// dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday
//
//
// Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence.
// ----------------------------------------------------------------------------
library BokkyPooBahsDateTimeLibrary {
uint constant SECONDS_PER_DAY = 24 * 60 * 60;
uint constant SECONDS_PER_HOUR = 60 * 60;
uint constant SECONDS_PER_MINUTE = 60;
int constant OFFSET19700101 = 2440588;
uint constant DOW_MON = 1;
uint constant DOW_TUE = 2;
uint constant DOW_WED = 3;
uint constant DOW_THU = 4;
uint constant DOW_FRI = 5;
uint constant DOW_SAT = 6;
uint constant DOW_SUN = 7;
// ------------------------------------------------------------------------
// Calculate the number of days from 1970/01/01 to year/month/day using
// the date conversion algorithm from
// https://aa.usno.navy.mil/faq/JD_formula.html
// and subtracting the offset 2440588 so that 1970/01/01 is day 0
//
// days = day
// - 32075
// + 1461 * (year + 4800 + (month - 14) / 12) / 4
// + 367 * (month - 2 - (month - 14) / 12 * 12) / 12
// - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4
// - offset
// ------------------------------------------------------------------------
function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) {
require(year >= 1970);
int _year = int(year);
int _month = int(month);
int _day = int(day);
int __days = _day
- 32075
+ 1461 * (_year + 4800 + (_month - 14) / 12) / 4
+ 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12
- 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4
- OFFSET19700101;
_days = uint(__days);
}
// ------------------------------------------------------------------------
// Calculate year/month/day from the number of days since 1970/01/01 using
// the date conversion algorithm from
// http://aa.usno.navy.mil/faq/docs/JD_Formula.php
// and adding the offset 2440588 so that 1970/01/01 is day 0
//
// int L = days + 68569 + offset
// int N = 4 * L / 146097
// L = L - (146097 * N + 3) / 4
// year = 4000 * (L + 1) / 1461001
// L = L - 1461 * year / 4 + 31
// month = 80 * L / 2447
// dd = L - 2447 * month / 80
// L = month / 11
// month = month + 2 - 12 * L
// year = 100 * (N - 49) + year + L
// ------------------------------------------------------------------------
function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) {
int __days = int(_days);
int L = __days + 68569 + OFFSET19700101;
int N = 4 * L / 146097;
L = L - (146097 * N + 3) / 4;
int _year = 4000 * (L + 1) / 1461001;
L = L - 1461 * _year / 4 + 31;
int _month = 80 * L / 2447;
int _day = L - 2447 * _month / 80;
L = _month / 11;
_month = _month + 2 - 12 * L;
_year = 100 * (N - 49) + _year + L;
year = uint(_year);
month = uint(_month);
day = uint(_day);
}
function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY;
}
function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) {
timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second;
}
function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) {
(year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
secs = secs % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
second = secs % SECONDS_PER_MINUTE;
}
function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) {
if (year >= 1970 && month > 0 && month <= 12) {
uint daysInMonth = _getDaysInMonth(year, month);
if (day > 0 && day <= daysInMonth) {
valid = true;
}
}
}
function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) {
if (isValidDate(year, month, day)) {
if (hour < 24 && minute < 60 && second < 60) {
valid = true;
}
}
}
function isLeapYear(uint timestamp) internal pure returns (bool leapYear) {
(uint year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
leapYear = _isLeapYear(year);
}
function _isLeapYear(uint year) internal pure returns (bool leapYear) {
leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
function isWeekDay(uint timestamp) internal pure returns (bool weekDay) {
weekDay = getDayOfWeek(timestamp) <= DOW_FRI;
}
function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) {
weekEnd = getDayOfWeek(timestamp) >= DOW_SAT;
}
function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) {
(uint year, uint month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
daysInMonth = _getDaysInMonth(year, month);
}
function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) {
if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) {
daysInMonth = 31;
} else if (month != 2) {
daysInMonth = 30;
} else {
daysInMonth = _isLeapYear(year) ? 29 : 28;
}
}
// 1 = Monday, 7 = Sunday
function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) {
uint _days = timestamp / SECONDS_PER_DAY;
dayOfWeek = (_days + 3) % 7 + 1;
}
function getYear(uint timestamp) internal pure returns (uint year) {
(year,,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getMonth(uint timestamp) internal pure returns (uint month) {
(,month,) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getDay(uint timestamp) internal pure returns (uint day) {
(,,day) = _daysToDate(timestamp / SECONDS_PER_DAY);
}
function getHour(uint timestamp) internal pure returns (uint hour) {
uint secs = timestamp % SECONDS_PER_DAY;
hour = secs / SECONDS_PER_HOUR;
}
function getMinute(uint timestamp) internal pure returns (uint minute) {
uint secs = timestamp % SECONDS_PER_HOUR;
minute = secs / SECONDS_PER_MINUTE;
}
function getSecond(uint timestamp) internal pure returns (uint second) {
second = timestamp % SECONDS_PER_MINUTE;
}
function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year += _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
month += _months;
year += (month - 1) / 12;
month = (month - 1) % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _days * SECONDS_PER_DAY;
require(newTimestamp >= timestamp);
}
function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _hours * SECONDS_PER_HOUR;
require(newTimestamp >= timestamp);
}
function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE;
require(newTimestamp >= timestamp);
}
function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp + _seconds;
require(newTimestamp >= timestamp);
}
function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
year -= _years;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) {
(uint year, uint month, uint day) = _daysToDate(timestamp / SECONDS_PER_DAY);
uint yearMonth = year * 12 + (month - 1) - _months;
year = yearMonth / 12;
month = yearMonth % 12 + 1;
uint daysInMonth = _getDaysInMonth(year, month);
if (day > daysInMonth) {
day = daysInMonth;
}
newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _days * SECONDS_PER_DAY;
require(newTimestamp <= timestamp);
}
function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _hours * SECONDS_PER_HOUR;
require(newTimestamp <= timestamp);
}
function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE;
require(newTimestamp <= timestamp);
}
function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) {
newTimestamp = timestamp - _seconds;
require(newTimestamp <= timestamp);
}
function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) {
require(fromTimestamp <= toTimestamp);
(uint fromYear,,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint toYear,,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_years = toYear - fromYear;
}
function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) {
require(fromTimestamp <= toTimestamp);
(uint fromYear, uint fromMonth,) = _daysToDate(fromTimestamp / SECONDS_PER_DAY);
(uint toYear, uint toMonth,) = _daysToDate(toTimestamp / SECONDS_PER_DAY);
_months = toYear * 12 + toMonth - fromYear * 12 - fromMonth;
}
function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) {
require(fromTimestamp <= toTimestamp);
_days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY;
}
function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) {
require(fromTimestamp <= toTimestamp);
_hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR;
}
function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) {
require(fromTimestamp <= toTimestamp);
_minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE;
}
function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) {
require(fromTimestamp <= toTimestamp);
_seconds = toTimestamp - fromTimestamp;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @notice Solidity library offering basic trigonometry functions where inputs and outputs are
* integers. Inputs are specified in radians scaled by 1e18, and similarly outputs are scaled by 1e18.
*
* This implementation is based off the Solidity trigonometry library written by Lefteris Karapetsas
* which can be found here: https://github.com/Sikorkaio/sikorka/blob/e75c91925c914beaedf4841c0336a806f2b5f66d/contracts/trigonometry.sol
*
* Compared to Lefteris' implementation, this version makes the following changes:
* - Uses a 32 bits instead of 16 bits for improved accuracy
* - Updated for Solidity 0.8.x
* - Various gas optimizations
* - Change inputs/outputs to standard trig format (scaled by 1e18) instead of requiring the
* integer format used by the algorithm
*
* Lefertis' implementation is based off Dave Dribin's trigint C library
* http://www.dribin.org/dave/trigint/
*
* Which in turn is based from a now deleted article which can be found in the Wayback Machine:
* http://web.archive.org/web/20120301144605/http://www.dattalo.com/technical/software/pic/picsine.html
*/
library Trigonometry {
// Table index into the trigonometric table
uint256 constant INDEX_WIDTH = 8;
// Interpolation between successive entries in the table
uint256 constant INTERP_WIDTH = 16;
uint256 constant INDEX_OFFSET = 28 - INDEX_WIDTH;
uint256 constant INTERP_OFFSET = INDEX_OFFSET - INTERP_WIDTH;
uint32 constant ANGLES_IN_CYCLE = 1073741824;
uint32 constant QUADRANT_HIGH_MASK = 536870912;
uint32 constant QUADRANT_LOW_MASK = 268435456;
uint256 constant SINE_TABLE_SIZE = 256;
// Pi as an 18 decimal value, which is plenty of accuracy: "For JPL's highest accuracy calculations, which are for
// interplanetary navigation, we use 3.141592653589793: https://www.jpl.nasa.gov/edu/news/2016/3/16/how-many-decimals-of-pi-do-we-really-need/
uint256 constant PI = 3141592653589793238;
uint256 constant TWO_PI = 2 * PI;
uint256 constant PI_OVER_TWO = PI / 2;
// The constant sine lookup table was generated by generate_trigonometry.py. We must use a constant
// bytes array because constant arrays are not supported in Solidity. Each entry in the lookup
// table is 4 bytes. Since we're using 32-bit parameters for the lookup table, we get a table size
// of 2^(32/4) + 1 = 257, where the first and last entries are equivalent (hence the table size of
// 256 defined above)
uint8 constant entry_bytes = 4; // each entry in the lookup table is 4 bytes
uint256 constant entry_mask = ((1 << 8*entry_bytes) - 1); // mask used to cast bytes32 -> lookup table entry
bytes constant sin_table = hex"00_00_00_00_00_c9_0f_88_01_92_1d_20_02_5b_26_d7_03_24_2a_bf_03_ed_26_e6_04_b6_19_5d_05_7f_00_35_06_47_d9_7c_07_10_a3_45_07_d9_5b_9e_08_a2_00_9a_09_6a_90_49_0a_33_08_bc_0a_fb_68_05_0b_c3_ac_35_0c_8b_d3_5e_0d_53_db_92_0e_1b_c2_e4_0e_e3_87_66_0f_ab_27_2b_10_72_a0_48_11_39_f0_cf_12_01_16_d5_12_c8_10_6e_13_8e_db_b1_14_55_76_b1_15_1b_df_85_15_e2_14_44_16_a8_13_05_17_6d_d9_de_18_33_66_e8_18_f8_b8_3c_19_bd_cb_f3_1a_82_a0_25_1b_47_32_ef_1c_0b_82_6a_1c_cf_8c_b3_1d_93_4f_e5_1e_56_ca_1e_1f_19_f9_7b_1f_dc_dc_1b_20_9f_70_1c_21_61_b3_9f_22_23_a4_c5_22_e5_41_af_23_a6_88_7e_24_67_77_57_25_28_0c_5d_25_e8_45_b6_26_a8_21_85_27_67_9d_f4_28_26_b9_28_28_e5_71_4a_29_a3_c4_85_2a_61_b1_01_2b_1f_34_eb_2b_dc_4e_6f_2c_98_fb_ba_2d_55_3a_fb_2e_11_0a_62_2e_cc_68_1e_2f_87_52_62_30_41_c7_60_30_fb_c5_4d_31_b5_4a_5d_32_6e_54_c7_33_26_e2_c2_33_de_f2_87_34_96_82_4f_35_4d_90_56_36_04_1a_d9_36_ba_20_13_37_6f_9e_46_38_24_93_b0_38_d8_fe_93_39_8c_dd_32_3a_40_2d_d1_3a_f2_ee_b7_3b_a5_1e_29_3c_56_ba_70_3d_07_c1_d5_3d_b8_32_a5_3e_68_0b_2c_3f_17_49_b7_3f_c5_ec_97_40_73_f2_1d_41_21_58_9a_41_ce_1e_64_42_7a_41_d0_43_25_c1_35_43_d0_9a_ec_44_7a_cd_50_45_24_56_bc_45_cd_35_8f_46_75_68_27_47_1c_ec_e6_47_c3_c2_2e_48_69_e6_64_49_0f_57_ee_49_b4_15_33_4a_58_1c_9d_4a_fb_6c_97_4b_9e_03_8f_4c_3f_df_f3_4c_e1_00_34_4d_81_62_c3_4e_21_06_17_4e_bf_e8_a4_4f_5e_08_e2_4f_fb_65_4c_50_97_fc_5e_51_33_cc_94_51_ce_d4_6e_52_69_12_6e_53_02_85_17_53_9b_2a_ef_54_33_02_7d_54_ca_0a_4a_55_60_40_e2_55_f5_a4_d2_56_8a_34_a9_57_1d_ee_f9_57_b0_d2_55_58_42_dd_54_58_d4_0e_8c_59_64_64_97_59_f3_de_12_5a_82_79_99_5b_10_35_ce_5b_9d_11_53_5c_29_0a_cc_5c_b4_20_df_5d_3e_52_36_5d_c7_9d_7b_5e_50_01_5d_5e_d7_7c_89_5f_5e_0d_b2_5f_e3_b3_8d_60_68_6c_ce_60_ec_38_2f_61_6f_14_6b_61_f1_00_3e_62_71_fa_68_62_f2_01_ac_63_71_14_cc_63_ef_32_8f_64_6c_59_bf_64_e8_89_25_65_63_bf_91_65_dd_fb_d2_66_57_3c_bb_66_cf_81_1f_67_46_c7_d7_67_bd_0f_bc_68_32_57_aa_68_a6_9e_80_69_19_e3_1f_69_8c_24_6b_69_fd_61_4a_6a_6d_98_a3_6a_dc_c9_64_6b_4a_f2_78_6b_b8_12_d0_6c_24_29_5f_6c_8f_35_1b_6c_f9_34_fb_6d_62_27_f9_6d_ca_0d_14_6e_30_e3_49_6e_96_a9_9c_6e_fb_5f_11_6f_5f_02_b1_6f_c1_93_84_70_23_10_99_70_83_78_fe_70_e2_cb_c5_71_41_08_04_71_9e_2c_d1_71_fa_39_48_72_55_2c_84_72_af_05_a6_73_07_c3_cf_73_5f_66_25_73_b5_eb_d0_74_0b_53_fa_74_5f_9d_d0_74_b2_c8_83_75_04_d3_44_75_55_bd_4b_75_a5_85_ce_75_f4_2c_0a_76_41_af_3c_76_8e_0e_a5_76_d9_49_88_77_23_5f_2c_77_6c_4e_da_77_b4_17_df_77_fa_b9_88_78_40_33_28_78_84_84_13_78_c7_ab_a1_79_09_a9_2c_79_4a_7c_11_79_8a_23_b0_79_c8_9f_6d_7a_05_ee_ac_7a_42_10_d8_7a_7d_05_5a_7a_b6_cb_a3_7a_ef_63_23_7b_26_cb_4e_7b_5d_03_9d_7b_92_0b_88_7b_c5_e2_8f_7b_f8_88_2f_7c_29_fb_ed_7c_5a_3d_4f_7c_89_4b_dd_7c_b7_27_23_7c_e3_ce_b1_7d_0f_42_17_7d_39_80_eb_7d_62_8a_c5_7d_8a_5f_3f_7d_b0_fd_f7_7d_d6_66_8e_7d_fa_98_a7_7e_1d_93_e9_7e_3f_57_fe_7e_5f_e4_92_7e_7f_39_56_7e_9d_55_fb_7e_ba_3a_38_7e_d5_e5_c5_7e_f0_58_5f_7f_09_91_c3_7f_21_91_b3_7f_38_57_f5_7f_4d_e4_50_7f_62_36_8e_7f_75_4e_7f_7f_87_2b_f2_7f_97_ce_bc_7f_a7_36_b3_7f_b5_63_b2_7f_c2_55_95_7f_ce_0c_3d_7f_d8_87_8d_7f_e1_c7_6a_7f_e9_cb_bf_7f_f0_94_77_7f_f6_21_81_7f_fa_72_d0_7f_fd_88_59_7f_ff_62_15_7f_ff_ff_ff";
/**
* @notice Return the sine of a value, specified in radians scaled by 1e18
* @dev This algorithm for converting sine only uses integer values, and it works by dividing the
* circle into 30 bit angles, i.e. there are 1,073,741,824 (2^30) angle units, instead of the
* standard 360 degrees (2pi radians). From there, we get an output in range -2,147,483,647 to
* 2,147,483,647, (which is the max value of an int32) which is then converted back to the standard
* range of -1 to 1, again scaled by 1e18
* @param _angle Angle to convert
* @return Result scaled by 1e18
*/
function sin(uint256 _angle) internal pure returns (int256) {
unchecked {
// Convert angle from from arbitrary radian value (range of 0 to 2pi) to the algorithm's range
// of 0 to 1,073,741,824
_angle = ANGLES_IN_CYCLE * (_angle % TWO_PI) / TWO_PI;
// Apply a mask on an integer to extract a certain number of bits, where angle is the integer
// whose bits we want to get, the width is the width of the bits (in bits) we want to extract,
// and the offset is the offset of the bits (in bits) we want to extract. The result is an
// integer containing _width bits of _value starting at the offset bit
uint256 interp = (_angle >> INTERP_OFFSET) & ((1 << INTERP_WIDTH) - 1);
uint256 index = (_angle >> INDEX_OFFSET) & ((1 << INDEX_WIDTH) - 1);
// The lookup table only contains data for one quadrant (since sin is symmetric around both
// axes), so here we figure out which quadrant we're in, then we lookup the values in the
// table then modify values accordingly
bool is_odd_quadrant = (_angle & QUADRANT_LOW_MASK) == 0;
bool is_negative_quadrant = (_angle & QUADRANT_HIGH_MASK) != 0;
if (!is_odd_quadrant) {
index = SINE_TABLE_SIZE - 1 - index;
}
bytes memory table = sin_table;
// We are looking for two consecutive indices in our lookup table
// Since EVM is left aligned, to read n bytes of data from idx i, we must read from `i * data_len` + `n`
// therefore, to read two entries of size entry_bytes `index * entry_bytes` + `entry_bytes * 2`
uint256 offset1_2 = (index + 2) * entry_bytes;
// This following snippet will function for any entry_bytes <= 15
uint256 x1_2; assembly {
// mload will grab one word worth of bytes (32), as that is the minimum size in EVM
x1_2 := mload(add(table, offset1_2))
}
// We now read the last two numbers of size entry_bytes from x1_2
// in example: entry_bytes = 4; x1_2 = 0x00...12345678abcdefgh
// therefore: entry_mask = 0xFFFFFFFF
// 0x00...12345678abcdefgh >> 8*4 = 0x00...12345678
// 0x00...12345678 & 0xFFFFFFFF = 0x12345678
uint256 x1 = x1_2 >> 8*entry_bytes & entry_mask;
// 0x00...12345678abcdefgh & 0xFFFFFFFF = 0xabcdefgh
uint256 x2 = x1_2 & entry_mask;
// Approximate angle by interpolating in the table, accounting for the quadrant
uint256 approximation = ((x2 - x1) * interp) >> INTERP_WIDTH;
int256 sine = is_odd_quadrant ? int256(x1) + int256(approximation) : int256(x2) - int256(approximation);
if (is_negative_quadrant) {
sine *= -1;
}
// Bring result from the range of -2,147,483,647 through 2,147,483,647 to -1e18 through 1e18.
// This can never overflow because sine is bounded by the above values
return sine * 1e18 / 2_147_483_647;
}
}
/**
* @notice Return the cosine of a value, specified in radians scaled by 1e18
* @dev This is identical to the sin() method, and just computes the value by delegating to the
* sin() method using the identity cos(x) = sin(x + pi/2)
* @dev Overflow when `angle + PI_OVER_TWO > type(uint256).max` is ok, results are still accurate
* @param _angle Angle to convert
* @return Result scaled by 1e18
*/
function cos(uint256 _angle) internal pure returns (int256) {
unchecked {
return sin(_angle + PI_OVER_TWO);
}
}
}
// SPDX-License-Identifier: Unlicense
pragma solidity >=0.8.4;
import "./PRBMath.sol";
/// @title PRBMathSD59x18
/// @author Paul Razvan Berg
/// @notice Smart contract library for advanced fixed-point math that works with int256 numbers considered to have 18
/// trailing decimals. We call this number representation signed 59.18-decimal fixed-point, since the numbers can have
/// a sign and there can be up to 59 digits in the integer part and up to 18 decimals in the fractional part. The numbers
/// are bound by the minimum and the maximum values permitted by the Solidity type int256.
library PRBMathSD59x18 {
/// @dev log2(e) as a signed 59.18-decimal fixed-point number.
int256 internal constant LOG2_E = 1_442695040888963407;
/// @dev Half the SCALE number.
int256 internal constant HALF_SCALE = 5e17;
/// @dev The maximum value a signed 59.18-decimal fixed-point number can have.
int256 internal constant MAX_SD59x18 =
57896044618658097711785492504343953926634992332820282019728_792003956564819967;
/// @dev The maximum whole value a signed 59.18-decimal fixed-point number can have.
int256 internal constant MAX_WHOLE_SD59x18 =
57896044618658097711785492504343953926634992332820282019728_000000000000000000;
/// @dev The minimum value a signed 59.18-decimal fixed-point number can have.
int256 internal constant MIN_SD59x18 =
-57896044618658097711785492504343953926634992332820282019728_792003956564819968;
/// @dev The minimum whole value a signed 59.18-decimal fixed-point number can have.
int256 internal constant MIN_WHOLE_SD59x18 =
-57896044618658097711785492504343953926634992332820282019728_000000000000000000;
/// @dev How many trailing decimals can be represented.
int256 internal constant SCALE = 1e18;
/// INTERNAL FUNCTIONS ///
/// @notice Calculate the absolute value of x.
///
/// @dev Requirements:
/// - x must be greater than MIN_SD59x18.
///
/// @param x The number to calculate the absolute value for.
/// @param result The absolute value of x.
function abs(int256 x) internal pure returns (int256 result) {
unchecked {
if (x == MIN_SD59x18) {
revert PRBMathSD59x18__AbsInputTooSmall();
}
result = x < 0 ? -x : x;
}
}
/// @notice Calculates the arithmetic average of x and y, rounding down.
/// @param x The first operand as a signed 59.18-decimal fixed-point number.
/// @param y The second operand as a signed 59.18-decimal fixed-point number.
/// @return result The arithmetic average as a signed 59.18-decimal fixed-point number.
function avg(int256 x, int256 y) internal pure returns (int256 result) {
// The operations can never overflow.
unchecked {
int256 sum = (x >> 1) + (y >> 1);
if (sum < 0) {
// If at least one of x and y is odd, we add 1 to the result. This is because shifting negative numbers to the
// right rounds down to infinity.
assembly {
result := add(sum, and(or(x, y), 1))
}
} else {
// If both x and y are odd, we add 1 to the result. This is because if both numbers are odd, the 0.5
// remainder gets truncated twice.
result = sum + (x & y & 1);
}
}
}
/// @notice Yields the least greatest signed 59.18 decimal fixed-point number greater than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be less than or equal to MAX_WHOLE_SD59x18.
///
/// @param x The signed 59.18-decimal fixed-point number to ceil.
/// @param result The least integer greater than or equal to x, as a signed 58.18-decimal fixed-point number.
function ceil(int256 x) internal pure returns (int256 result) {
if (x > MAX_WHOLE_SD59x18) {
revert PRBMathSD59x18__CeilOverflow(x);
}
unchecked {
int256 remainder = x % SCALE;
if (remainder == 0) {
result = x;
} else {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
result = x - remainder;
if (x > 0) {
result += SCALE;
}
}
}
}
/// @notice Divides two signed 59.18-decimal fixed-point numbers, returning a new signed 59.18-decimal fixed-point number.
///
/// @dev Variant of "mulDiv" that works with signed numbers. Works by computing the signs and the absolute values separately.
///
/// Requirements:
/// - All from "PRBMath.mulDiv".
/// - None of the inputs can be MIN_SD59x18.
/// - The denominator cannot be zero.
/// - The result must fit within int256.
///
/// Caveats:
/// - All from "PRBMath.mulDiv".
///
/// @param x The numerator as a signed 59.18-decimal fixed-point number.
/// @param y The denominator as a signed 59.18-decimal fixed-point number.
/// @param result The quotient as a signed 59.18-decimal fixed-point number.
function div(int256 x, int256 y) internal pure returns (int256 result) {
if (x == MIN_SD59x18 || y == MIN_SD59x18) {
revert PRBMathSD59x18__DivInputTooSmall();
}
// Get hold of the absolute values of x and y.
uint256 ax;
uint256 ay;
unchecked {
ax = x < 0 ? uint256(-x) : uint256(x);
ay = y < 0 ? uint256(-y) : uint256(y);
}
// Compute the absolute value of (x*SCALE)÷y. The result must fit within int256.
uint256 rAbs = PRBMath.mulDiv(ax, uint256(SCALE), ay);
if (rAbs > uint256(MAX_SD59x18)) {
revert PRBMathSD59x18__DivOverflow(rAbs);
}
// Get the signs of x and y.
uint256 sx;
uint256 sy;
assembly {
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
}
// XOR over sx and sy. This is basically checking whether the inputs have the same sign. If yes, the result
// should be positive. Otherwise, it should be negative.
result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs);
}
/// @notice Returns Euler's number as a signed 59.18-decimal fixed-point number.
/// @dev See https://en.wikipedia.org/wiki/E_(mathematical_constant).
function e() internal pure returns (int256 result) {
result = 2_718281828459045235;
}
/// @notice Calculates the natural exponent of x.
///
/// @dev Based on the insight that e^x = 2^(x * log2(e)).
///
/// Requirements:
/// - All from "log2".
/// - x must be less than 133.084258667509499441.
///
/// Caveats:
/// - All from "exp2".
/// - For any x less than -41.446531673892822322, the result is zero.
///
/// @param x The exponent as a signed 59.18-decimal fixed-point number.
/// @return result The result as a signed 59.18-decimal fixed-point number.
function exp(int256 x) internal pure returns (int256 result) {
// Without this check, the value passed to "exp2" would be less than -59.794705707972522261.
if (x < -41_446531673892822322) {
return 0;
}
// Without this check, the value passed to "exp2" would be greater than 192.
if (x >= 133_084258667509499441) {
revert PRBMathSD59x18__ExpInputTooBig(x);
}
// Do the fixed-point multiplication inline to save gas.
unchecked {
int256 doubleScaleProduct = x * LOG2_E;
result = exp2((doubleScaleProduct + HALF_SCALE) / SCALE);
}
}
/// @notice Calculates the binary exponent of x using the binary fraction method.
///
/// @dev See https://ethereum.stackexchange.com/q/79903/24693.
///
/// Requirements:
/// - x must be 192 or less.
/// - The result must fit within MAX_SD59x18.
///
/// Caveats:
/// - For any x less than -59.794705707972522261, the result is zero.
///
/// @param x The exponent as a signed 59.18-decimal fixed-point number.
/// @return result The result as a signed 59.18-decimal fixed-point number.
function exp2(int256 x) internal pure returns (int256 result) {
// This works because 2^(-x) = 1/2^x.
if (x < 0) {
// 2^59.794705707972522262 is the maximum number whose inverse does not truncate down to zero.
if (x < -59_794705707972522261) {
return 0;
}
// Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE.
unchecked {
result = 1e36 / exp2(-x);
}
} else {
// 2^192 doesn't fit within the 192.64-bit format used internally in this function.
if (x >= 192e18) {
revert PRBMathSD59x18__Exp2InputTooBig(x);
}
unchecked {
// Convert x to the 192.64-bit fixed-point format.
uint256 x192x64 = (uint256(x) << 64) / uint256(SCALE);
// Safe to convert the result to int256 directly because the maximum input allowed is 192.
result = int256(PRBMath.exp2(x192x64));
}
}
}
/// @notice Yields the greatest signed 59.18 decimal fixed-point number less than or equal to x.
///
/// @dev Optimized for fractional value inputs, because for every whole value there are (1e18 - 1) fractional counterparts.
/// See https://en.wikipedia.org/wiki/Floor_and_ceiling_functions.
///
/// Requirements:
/// - x must be greater than or equal to MIN_WHOLE_SD59x18.
///
/// @param x The signed 59.18-decimal fixed-point number to floor.
/// @param result The greatest integer less than or equal to x, as a signed 58.18-decimal fixed-point number.
function floor(int256 x) internal pure returns (int256 result) {
if (x < MIN_WHOLE_SD59x18) {
revert PRBMathSD59x18__FloorUnderflow(x);
}
unchecked {
int256 remainder = x % SCALE;
if (remainder == 0) {
result = x;
} else {
// Solidity uses C fmod style, which returns a modulus with the same sign as x.
result = x - remainder;
if (x < 0) {
result -= SCALE;
}
}
}
}
/// @notice Yields the excess beyond the floor of x for positive numbers and the part of the number to the right
/// of the radix point for negative numbers.
/// @dev Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part
/// @param x The signed 59.18-decimal fixed-point number to get the fractional part of.
/// @param result The fractional part of x as a signed 59.18-decimal fixed-point number.
function frac(int256 x) internal pure returns (int256 result) {
unchecked {
result = x % SCALE;
}
}
/// @notice Converts a number from basic integer form to signed 59.18-decimal fixed-point representation.
///
/// @dev Requirements:
/// - x must be greater than or equal to MIN_SD59x18 divided by SCALE.
/// - x must be less than or equal to MAX_SD59x18 divided by SCALE.
///
/// @param x The basic integer to convert.
/// @param result The same number in signed 59.18-decimal fixed-point representation.
function fromInt(int256 x) internal pure returns (int256 result) {
unchecked {
if (x < MIN_SD59x18 / SCALE) {
revert PRBMathSD59x18__FromIntUnderflow(x);
}
if (x > MAX_SD59x18 / SCALE) {
revert PRBMathSD59x18__FromIntOverflow(x);
}
result = x * SCALE;
}
}
/// @notice Calculates geometric mean of x and y, i.e. sqrt(x * y), rounding down.
///
/// @dev Requirements:
/// - x * y must fit within MAX_SD59x18, lest it overflows.
/// - x * y cannot be negative.
///
/// @param x The first operand as a signed 59.18-decimal fixed-point number.
/// @param y The second operand as a signed 59.18-decimal fixed-point number.
/// @return result The result as a signed 59.18-decimal fixed-point number.
function gm(int256 x, int256 y) internal pure returns (int256 result) {
if (x == 0) {
return 0;
}
unchecked {
// Checking for overflow this way is faster than letting Solidity do it.
int256 xy = x * y;
if (xy / x != y) {
revert PRBMathSD59x18__GmOverflow(x, y);
}
// The product cannot be negative.
if (xy < 0) {
revert PRBMathSD59x18__GmNegativeProduct(x, y);
}
// We don't need to multiply by the SCALE here because the x*y product had already picked up a factor of SCALE
// during multiplication. See the comments within the "sqrt" function.
result = int256(PRBMath.sqrt(uint256(xy)));
}
}
/// @notice Calculates 1 / x, rounding toward zero.
///
/// @dev Requirements:
/// - x cannot be zero.
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the inverse.
/// @return result The inverse as a signed 59.18-decimal fixed-point number.
function inv(int256 x) internal pure returns (int256 result) {
unchecked {
// 1e36 is SCALE * SCALE.
result = 1e36 / x;
}
}
/// @notice Calculates the natural logarithm of x.
///
/// @dev Based on the insight that ln(x) = log2(x) / log2(e).
///
/// Requirements:
/// - All from "log2".
///
/// Caveats:
/// - All from "log2".
/// - This doesn't return exactly 1 for 2718281828459045235, for that we would need more fine-grained precision.
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the natural logarithm.
/// @return result The natural logarithm as a signed 59.18-decimal fixed-point number.
function ln(int256 x) internal pure returns (int256 result) {
// Do the fixed-point multiplication inline to save gas. This is overflow-safe because the maximum value that log2(x)
// can return is 195205294292027477728.
unchecked {
result = (log2(x) * SCALE) / LOG2_E;
}
}
/// @notice Calculates the common logarithm of x.
///
/// @dev First checks if x is an exact power of ten and it stops if yes. If it's not, calculates the common
/// logarithm based on the insight that log10(x) = log2(x) / log2(10).
///
/// Requirements:
/// - All from "log2".
///
/// Caveats:
/// - All from "log2".
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the common logarithm.
/// @return result The common logarithm as a signed 59.18-decimal fixed-point number.
function log10(int256 x) internal pure returns (int256 result) {
if (x <= 0) {
revert PRBMathSD59x18__LogInputTooSmall(x);
}
// Note that the "mul" in this block is the assembly mul operation, not the "mul" function defined in this contract.
// prettier-ignore
assembly {
switch x
case 1 { result := mul(SCALE, sub(0, 18)) }
case 10 { result := mul(SCALE, sub(1, 18)) }
case 100 { result := mul(SCALE, sub(2, 18)) }
case 1000 { result := mul(SCALE, sub(3, 18)) }
case 10000 { result := mul(SCALE, sub(4, 18)) }
case 100000 { result := mul(SCALE, sub(5, 18)) }
case 1000000 { result := mul(SCALE, sub(6, 18)) }
case 10000000 { result := mul(SCALE, sub(7, 18)) }
case 100000000 { result := mul(SCALE, sub(8, 18)) }
case 1000000000 { result := mul(SCALE, sub(9, 18)) }
case 10000000000 { result := mul(SCALE, sub(10, 18)) }
case 100000000000 { result := mul(SCALE, sub(11, 18)) }
case 1000000000000 { result := mul(SCALE, sub(12, 18)) }
case 10000000000000 { result := mul(SCALE, sub(13, 18)) }
case 100000000000000 { result := mul(SCALE, sub(14, 18)) }
case 1000000000000000 { result := mul(SCALE, sub(15, 18)) }
case 10000000000000000 { result := mul(SCALE, sub(16, 18)) }
case 100000000000000000 { result := mul(SCALE, sub(17, 18)) }
case 1000000000000000000 { result := 0 }
case 10000000000000000000 { result := SCALE }
case 100000000000000000000 { result := mul(SCALE, 2) }
case 1000000000000000000000 { result := mul(SCALE, 3) }
case 10000000000000000000000 { result := mul(SCALE, 4) }
case 100000000000000000000000 { result := mul(SCALE, 5) }
case 1000000000000000000000000 { result := mul(SCALE, 6) }
case 10000000000000000000000000 { result := mul(SCALE, 7) }
case 100000000000000000000000000 { result := mul(SCALE, 8) }
case 1000000000000000000000000000 { result := mul(SCALE, 9) }
case 10000000000000000000000000000 { result := mul(SCALE, 10) }
case 100000000000000000000000000000 { result := mul(SCALE, 11) }
case 1000000000000000000000000000000 { result := mul(SCALE, 12) }
case 10000000000000000000000000000000 { result := mul(SCALE, 13) }
case 100000000000000000000000000000000 { result := mul(SCALE, 14) }
case 1000000000000000000000000000000000 { result := mul(SCALE, 15) }
case 10000000000000000000000000000000000 { result := mul(SCALE, 16) }
case 100000000000000000000000000000000000 { result := mul(SCALE, 17) }
case 1000000000000000000000000000000000000 { result := mul(SCALE, 18) }
case 10000000000000000000000000000000000000 { result := mul(SCALE, 19) }
case 100000000000000000000000000000000000000 { result := mul(SCALE, 20) }
case 1000000000000000000000000000000000000000 { result := mul(SCALE, 21) }
case 10000000000000000000000000000000000000000 { result := mul(SCALE, 22) }
case 100000000000000000000000000000000000000000 { result := mul(SCALE, 23) }
case 1000000000000000000000000000000000000000000 { result := mul(SCALE, 24) }
case 10000000000000000000000000000000000000000000 { result := mul(SCALE, 25) }
case 100000000000000000000000000000000000000000000 { result := mul(SCALE, 26) }
case 1000000000000000000000000000000000000000000000 { result := mul(SCALE, 27) }
case 10000000000000000000000000000000000000000000000 { result := mul(SCALE, 28) }
case 100000000000000000000000000000000000000000000000 { result := mul(SCALE, 29) }
case 1000000000000000000000000000000000000000000000000 { result := mul(SCALE, 30) }
case 10000000000000000000000000000000000000000000000000 { result := mul(SCALE, 31) }
case 100000000000000000000000000000000000000000000000000 { result := mul(SCALE, 32) }
case 1000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 33) }
case 10000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 34) }
case 100000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 35) }
case 1000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 36) }
case 10000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 37) }
case 100000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 38) }
case 1000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 39) }
case 10000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 40) }
case 100000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 41) }
case 1000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 42) }
case 10000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 43) }
case 100000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 44) }
case 1000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 45) }
case 10000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 46) }
case 100000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 47) }
case 1000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 48) }
case 10000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 49) }
case 100000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 50) }
case 1000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 51) }
case 10000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 52) }
case 100000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 53) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 54) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 55) }
case 100000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 56) }
case 1000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 57) }
case 10000000000000000000000000000000000000000000000000000000000000000000000000000 { result := mul(SCALE, 58) }
default {
result := MAX_SD59x18
}
}
if (result == MAX_SD59x18) {
// Do the fixed-point division inline to save gas. The denominator is log2(10).
unchecked {
result = (log2(x) * SCALE) / 3_321928094887362347;
}
}
}
/// @notice Calculates the binary logarithm of x.
///
/// @dev Based on the iterative approximation algorithm.
/// https://en.wikipedia.org/wiki/Binary_logarithm#Iterative_approximation
///
/// Requirements:
/// - x must be greater than zero.
///
/// Caveats:
/// - The results are not perfectly accurate to the last decimal, due to the lossy precision of the iterative approximation.
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the binary logarithm.
/// @return result The binary logarithm as a signed 59.18-decimal fixed-point number.
function log2(int256 x) internal pure returns (int256 result) {
if (x <= 0) {
revert PRBMathSD59x18__LogInputTooSmall(x);
}
unchecked {
// This works because log2(x) = -log2(1/x).
int256 sign;
if (x >= SCALE) {
sign = 1;
} else {
sign = -1;
// Do the fixed-point inversion inline to save gas. The numerator is SCALE * SCALE.
assembly {
x := div(1000000000000000000000000000000000000, x)
}
}
// Calculate the integer part of the logarithm and add it to the result and finally calculate y = x * 2^(-n).
uint256 n = PRBMath.mostSignificantBit(uint256(x / SCALE));
// The integer part of the logarithm as a signed 59.18-decimal fixed-point number. The operation can't overflow
// because n is maximum 255, SCALE is 1e18 and sign is either 1 or -1.
result = int256(n) * SCALE;
// This is y = x * 2^(-n).
int256 y = x >> n;
// If y = 1, the fractional part is zero.
if (y == SCALE) {
return result * sign;
}
// Calculate the fractional part via the iterative approximation.
// The "delta >>= 1" part is equivalent to "delta /= 2", but shifting bits is faster.
for (int256 delta = int256(HALF_SCALE); delta > 0; delta >>= 1) {
y = (y * y) / SCALE;
// Is y^2 > 2 and so in the range [2,4)?
if (y >= 2 * SCALE) {
// Add the 2^(-m) factor to the logarithm.
result += delta;
// Corresponds to z/2 on Wikipedia.
y >>= 1;
}
}
result *= sign;
}
}
/// @notice Multiplies two signed 59.18-decimal fixed-point numbers together, returning a new signed 59.18-decimal
/// fixed-point number.
///
/// @dev Variant of "mulDiv" that works with signed numbers and employs constant folding, i.e. the denominator is
/// always 1e18.
///
/// Requirements:
/// - All from "PRBMath.mulDivFixedPoint".
/// - None of the inputs can be MIN_SD59x18
/// - The result must fit within MAX_SD59x18.
///
/// Caveats:
/// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works.
///
/// @param x The multiplicand as a signed 59.18-decimal fixed-point number.
/// @param y The multiplier as a signed 59.18-decimal fixed-point number.
/// @return result The product as a signed 59.18-decimal fixed-point number.
function mul(int256 x, int256 y) internal pure returns (int256 result) {
if (x == MIN_SD59x18 || y == MIN_SD59x18) {
revert PRBMathSD59x18__MulInputTooSmall();
}
unchecked {
uint256 ax;
uint256 ay;
ax = x < 0 ? uint256(-x) : uint256(x);
ay = y < 0 ? uint256(-y) : uint256(y);
uint256 rAbs = PRBMath.mulDivFixedPoint(ax, ay);
if (rAbs > uint256(MAX_SD59x18)) {
revert PRBMathSD59x18__MulOverflow(rAbs);
}
uint256 sx;
uint256 sy;
assembly {
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
}
result = sx ^ sy == 1 ? -int256(rAbs) : int256(rAbs);
}
}
/// @notice Returns PI as a signed 59.18-decimal fixed-point number.
function pi() internal pure returns (int256 result) {
result = 3_141592653589793238;
}
/// @notice Raises x to the power of y.
///
/// @dev Based on the insight that x^y = 2^(log2(x) * y).
///
/// Requirements:
/// - All from "exp2", "log2" and "mul".
/// - z cannot be zero.
///
/// Caveats:
/// - All from "exp2", "log2" and "mul".
/// - Assumes 0^0 is 1.
///
/// @param x Number to raise to given power y, as a signed 59.18-decimal fixed-point number.
/// @param y Exponent to raise x to, as a signed 59.18-decimal fixed-point number.
/// @return result x raised to power y, as a signed 59.18-decimal fixed-point number.
function pow(int256 x, int256 y) internal pure returns (int256 result) {
if (x == 0) {
result = y == 0 ? SCALE : int256(0);
} else {
result = exp2(mul(log2(x), y));
}
}
/// @notice Raises x (signed 59.18-decimal fixed-point number) to the power of y (basic unsigned integer) using the
/// famous algorithm "exponentiation by squaring".
///
/// @dev See https://en.wikipedia.org/wiki/Exponentiation_by_squaring
///
/// Requirements:
/// - All from "abs" and "PRBMath.mulDivFixedPoint".
/// - The result must fit within MAX_SD59x18.
///
/// Caveats:
/// - All from "PRBMath.mulDivFixedPoint".
/// - Assumes 0^0 is 1.
///
/// @param x The base as a signed 59.18-decimal fixed-point number.
/// @param y The exponent as an uint256.
/// @return result The result as a signed 59.18-decimal fixed-point number.
function powu(int256 x, uint256 y) internal pure returns (int256 result) {
uint256 xAbs = uint256(abs(x));
// Calculate the first iteration of the loop in advance.
uint256 rAbs = y & 1 > 0 ? xAbs : uint256(SCALE);
// Equivalent to "for(y /= 2; y > 0; y /= 2)" but faster.
uint256 yAux = y;
for (yAux >>= 1; yAux > 0; yAux >>= 1) {
xAbs = PRBMath.mulDivFixedPoint(xAbs, xAbs);
// Equivalent to "y % 2 == 1" but faster.
if (yAux & 1 > 0) {
rAbs = PRBMath.mulDivFixedPoint(rAbs, xAbs);
}
}
// The result must fit within the 59.18-decimal fixed-point representation.
if (rAbs > uint256(MAX_SD59x18)) {
revert PRBMathSD59x18__PowuOverflow(rAbs);
}
// Is the base negative and the exponent an odd number?
bool isNegative = x < 0 && y & 1 == 1;
result = isNegative ? -int256(rAbs) : int256(rAbs);
}
/// @notice Returns 1 as a signed 59.18-decimal fixed-point number.
function scale() internal pure returns (int256 result) {
result = SCALE;
}
/// @notice Calculates the square root of x, rounding down.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Requirements:
/// - x cannot be negative.
/// - x must be less than MAX_SD59x18 / SCALE.
///
/// @param x The signed 59.18-decimal fixed-point number for which to calculate the square root.
/// @return result The result as a signed 59.18-decimal fixed-point .
function sqrt(int256 x) internal pure returns (int256 result) {
unchecked {
if (x < 0) {
revert PRBMathSD59x18__SqrtNegativeInput(x);
}
if (x > MAX_SD59x18 / SCALE) {
revert PRBMathSD59x18__SqrtOverflow(x);
}
// Multiply x by the SCALE to account for the factor of SCALE that is picked up when multiplying two signed
// 59.18-decimal fixed-point numbers together (in this case, those two numbers are both the square root).
result = int256(PRBMath.sqrt(uint256(x * SCALE)));
}
}
/// @notice Converts a signed 59.18-decimal fixed-point number to basic integer form, rounding down in the process.
/// @param x The signed 59.18-decimal fixed-point number to convert.
/// @return result The same number in basic integer form.
function toInt(int256 x) internal pure returns (int256 result) {
unchecked {
result = x / SCALE;
}
}
}
// 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
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "./ERC721SingleCreatorExtensionBase.sol";
/**
* @dev Extension that only uses a single creator contract instance
*/
abstract contract ERC721SingleCreatorExtension is ERC721SingleCreatorExtensionBase {
constructor(address creator) {
_setCreator(creator);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Implement this if you want your extension to have overloadable URI's
*/
interface ICreatorExtensionTokenURI is IERC165 {
/**
* Get the uri for a given creator/tokenId
*/
function tokenURI(address creator, uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165.sol";
/**
* @dev Base creator extension variables
*/
abstract contract CreatorExtension is ERC165 {
/**
* @dev Legacy extension interface identifiers
*
* {IERC165-supportsInterface} needs to return 'true' for this interface
* in order backwards compatible with older creator contracts
*/
bytes4 constant internal LEGACY_EXTENSION_INTERFACE = 0x7005caad;
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165) returns (bool) {
return interfaceId == LEGACY_EXTENSION_INTERFACE
|| super.supportsInterface(interfaceId);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "./ICreatorCore.sol";
/**
* @dev Core ERC721 creator interface
*/
interface IERC721CreatorCore is ICreatorCore {
/**
* @dev mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBase(address to) external returns (uint256);
/**
* @dev mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBase(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBaseBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token with no extension. Can only be called by an admin.
* Returns tokenId minted
*/
function mintBaseBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtension(address to) external returns (uint256);
/**
* @dev mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtension(address to, string calldata uri) external returns (uint256);
/**
* @dev batch mint a token. Can only be called by a registered extension.
* Returns tokenIds minted
*/
function mintExtensionBatch(address to, uint16 count) external returns (uint256[] memory);
/**
* @dev batch mint a token. Can only be called by a registered extension.
* Returns tokenId minted
*/
function mintExtensionBatch(address to, string[] calldata uris) external returns (uint256[] memory);
/**
* @dev burn a token. Can only be called by token owner or approved address.
* On burn, calls back to the registered extension's onBurn method
*/
function burn(uint256 tokenId) external;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (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: Unlicense
pragma solidity >=0.8.4;
/// @notice Emitted when the result overflows uint256.
error PRBMath__MulDivFixedPointOverflow(uint256 prod1);
/// @notice Emitted when the result overflows uint256.
error PRBMath__MulDivOverflow(uint256 prod1, uint256 denominator);
/// @notice Emitted when one of the inputs is type(int256).min.
error PRBMath__MulDivSignedInputTooSmall();
/// @notice Emitted when the intermediary absolute result overflows int256.
error PRBMath__MulDivSignedOverflow(uint256 rAbs);
/// @notice Emitted when the input is MIN_SD59x18.
error PRBMathSD59x18__AbsInputTooSmall();
/// @notice Emitted when ceiling a number overflows SD59x18.
error PRBMathSD59x18__CeilOverflow(int256 x);
/// @notice Emitted when one of the inputs is MIN_SD59x18.
error PRBMathSD59x18__DivInputTooSmall();
/// @notice Emitted when one of the intermediary unsigned results overflows SD59x18.
error PRBMathSD59x18__DivOverflow(uint256 rAbs);
/// @notice Emitted when the input is greater than 133.084258667509499441.
error PRBMathSD59x18__ExpInputTooBig(int256 x);
/// @notice Emitted when the input is greater than 192.
error PRBMathSD59x18__Exp2InputTooBig(int256 x);
/// @notice Emitted when flooring a number underflows SD59x18.
error PRBMathSD59x18__FloorUnderflow(int256 x);
/// @notice Emitted when converting a basic integer to the fixed-point format overflows SD59x18.
error PRBMathSD59x18__FromIntOverflow(int256 x);
/// @notice Emitted when converting a basic integer to the fixed-point format underflows SD59x18.
error PRBMathSD59x18__FromIntUnderflow(int256 x);
/// @notice Emitted when the product of the inputs is negative.
error PRBMathSD59x18__GmNegativeProduct(int256 x, int256 y);
/// @notice Emitted when multiplying the inputs overflows SD59x18.
error PRBMathSD59x18__GmOverflow(int256 x, int256 y);
/// @notice Emitted when the input is less than or equal to zero.
error PRBMathSD59x18__LogInputTooSmall(int256 x);
/// @notice Emitted when one of the inputs is MIN_SD59x18.
error PRBMathSD59x18__MulInputTooSmall();
/// @notice Emitted when the intermediary absolute result overflows SD59x18.
error PRBMathSD59x18__MulOverflow(uint256 rAbs);
/// @notice Emitted when the intermediary absolute result overflows SD59x18.
error PRBMathSD59x18__PowuOverflow(uint256 rAbs);
/// @notice Emitted when the input is negative.
error PRBMathSD59x18__SqrtNegativeInput(int256 x);
/// @notice Emitted when the calculating the square root overflows SD59x18.
error PRBMathSD59x18__SqrtOverflow(int256 x);
/// @notice Emitted when addition overflows UD60x18.
error PRBMathUD60x18__AddOverflow(uint256 x, uint256 y);
/// @notice Emitted when ceiling a number overflows UD60x18.
error PRBMathUD60x18__CeilOverflow(uint256 x);
/// @notice Emitted when the input is greater than 133.084258667509499441.
error PRBMathUD60x18__ExpInputTooBig(uint256 x);
/// @notice Emitted when the input is greater than 192.
error PRBMathUD60x18__Exp2InputTooBig(uint256 x);
/// @notice Emitted when converting a basic integer to the fixed-point format format overflows UD60x18.
error PRBMathUD60x18__FromUintOverflow(uint256 x);
/// @notice Emitted when multiplying the inputs overflows UD60x18.
error PRBMathUD60x18__GmOverflow(uint256 x, uint256 y);
/// @notice Emitted when the input is less than 1.
error PRBMathUD60x18__LogInputTooSmall(uint256 x);
/// @notice Emitted when the calculating the square root overflows UD60x18.
error PRBMathUD60x18__SqrtOverflow(uint256 x);
/// @notice Emitted when subtraction underflows UD60x18.
error PRBMathUD60x18__SubUnderflow(uint256 x, uint256 y);
/// @dev Common mathematical functions used in both PRBMathSD59x18 and PRBMathUD60x18. Note that this shared library
/// does not always assume the signed 59.18-decimal fixed-point or the unsigned 60.18-decimal fixed-point
/// representation. When it does not, it is explicitly mentioned in the NatSpec documentation.
library PRBMath {
/// STRUCTS ///
struct SD59x18 {
int256 value;
}
struct UD60x18 {
uint256 value;
}
/// STORAGE ///
/// @dev How many trailing decimals can be represented.
uint256 internal constant SCALE = 1e18;
/// @dev Largest power of two divisor of SCALE.
uint256 internal constant SCALE_LPOTD = 262144;
/// @dev SCALE inverted mod 2^256.
uint256 internal constant SCALE_INVERSE =
78156646155174841979727994598816262306175212592076161876661_508869554232690281;
/// FUNCTIONS ///
/// @notice Calculates the binary exponent of x using the binary fraction method.
/// @dev Has to use 192.64-bit fixed-point numbers.
/// See https://ethereum.stackexchange.com/a/96594/24693.
/// @param x The exponent as an unsigned 192.64-bit fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function exp2(uint256 x) internal pure returns (uint256 result) {
unchecked {
// Start from 0.5 in the 192.64-bit fixed-point format.
result = 0x800000000000000000000000000000000000000000000000;
// Multiply the result by root(2, 2^-i) when the bit at position i is 1. None of the intermediary results overflows
// because the initial result is 2^191 and all magic factors are less than 2^65.
if (x & 0x8000000000000000 > 0) {
result = (result * 0x16A09E667F3BCC909) >> 64;
}
if (x & 0x4000000000000000 > 0) {
result = (result * 0x1306FE0A31B7152DF) >> 64;
}
if (x & 0x2000000000000000 > 0) {
result = (result * 0x1172B83C7D517ADCE) >> 64;
}
if (x & 0x1000000000000000 > 0) {
result = (result * 0x10B5586CF9890F62A) >> 64;
}
if (x & 0x800000000000000 > 0) {
result = (result * 0x1059B0D31585743AE) >> 64;
}
if (x & 0x400000000000000 > 0) {
result = (result * 0x102C9A3E778060EE7) >> 64;
}
if (x & 0x200000000000000 > 0) {
result = (result * 0x10163DA9FB33356D8) >> 64;
}
if (x & 0x100000000000000 > 0) {
result = (result * 0x100B1AFA5ABCBED61) >> 64;
}
if (x & 0x80000000000000 > 0) {
result = (result * 0x10058C86DA1C09EA2) >> 64;
}
if (x & 0x40000000000000 > 0) {
result = (result * 0x1002C605E2E8CEC50) >> 64;
}
if (x & 0x20000000000000 > 0) {
result = (result * 0x100162F3904051FA1) >> 64;
}
if (x & 0x10000000000000 > 0) {
result = (result * 0x1000B175EFFDC76BA) >> 64;
}
if (x & 0x8000000000000 > 0) {
result = (result * 0x100058BA01FB9F96D) >> 64;
}
if (x & 0x4000000000000 > 0) {
result = (result * 0x10002C5CC37DA9492) >> 64;
}
if (x & 0x2000000000000 > 0) {
result = (result * 0x1000162E525EE0547) >> 64;
}
if (x & 0x1000000000000 > 0) {
result = (result * 0x10000B17255775C04) >> 64;
}
if (x & 0x800000000000 > 0) {
result = (result * 0x1000058B91B5BC9AE) >> 64;
}
if (x & 0x400000000000 > 0) {
result = (result * 0x100002C5C89D5EC6D) >> 64;
}
if (x & 0x200000000000 > 0) {
result = (result * 0x10000162E43F4F831) >> 64;
}
if (x & 0x100000000000 > 0) {
result = (result * 0x100000B1721BCFC9A) >> 64;
}
if (x & 0x80000000000 > 0) {
result = (result * 0x10000058B90CF1E6E) >> 64;
}
if (x & 0x40000000000 > 0) {
result = (result * 0x1000002C5C863B73F) >> 64;
}
if (x & 0x20000000000 > 0) {
result = (result * 0x100000162E430E5A2) >> 64;
}
if (x & 0x10000000000 > 0) {
result = (result * 0x1000000B172183551) >> 64;
}
if (x & 0x8000000000 > 0) {
result = (result * 0x100000058B90C0B49) >> 64;
}
if (x & 0x4000000000 > 0) {
result = (result * 0x10000002C5C8601CC) >> 64;
}
if (x & 0x2000000000 > 0) {
result = (result * 0x1000000162E42FFF0) >> 64;
}
if (x & 0x1000000000 > 0) {
result = (result * 0x10000000B17217FBB) >> 64;
}
if (x & 0x800000000 > 0) {
result = (result * 0x1000000058B90BFCE) >> 64;
}
if (x & 0x400000000 > 0) {
result = (result * 0x100000002C5C85FE3) >> 64;
}
if (x & 0x200000000 > 0) {
result = (result * 0x10000000162E42FF1) >> 64;
}
if (x & 0x100000000 > 0) {
result = (result * 0x100000000B17217F8) >> 64;
}
if (x & 0x80000000 > 0) {
result = (result * 0x10000000058B90BFC) >> 64;
}
if (x & 0x40000000 > 0) {
result = (result * 0x1000000002C5C85FE) >> 64;
}
if (x & 0x20000000 > 0) {
result = (result * 0x100000000162E42FF) >> 64;
}
if (x & 0x10000000 > 0) {
result = (result * 0x1000000000B17217F) >> 64;
}
if (x & 0x8000000 > 0) {
result = (result * 0x100000000058B90C0) >> 64;
}
if (x & 0x4000000 > 0) {
result = (result * 0x10000000002C5C860) >> 64;
}
if (x & 0x2000000 > 0) {
result = (result * 0x1000000000162E430) >> 64;
}
if (x & 0x1000000 > 0) {
result = (result * 0x10000000000B17218) >> 64;
}
if (x & 0x800000 > 0) {
result = (result * 0x1000000000058B90C) >> 64;
}
if (x & 0x400000 > 0) {
result = (result * 0x100000000002C5C86) >> 64;
}
if (x & 0x200000 > 0) {
result = (result * 0x10000000000162E43) >> 64;
}
if (x & 0x100000 > 0) {
result = (result * 0x100000000000B1721) >> 64;
}
if (x & 0x80000 > 0) {
result = (result * 0x10000000000058B91) >> 64;
}
if (x & 0x40000 > 0) {
result = (result * 0x1000000000002C5C8) >> 64;
}
if (x & 0x20000 > 0) {
result = (result * 0x100000000000162E4) >> 64;
}
if (x & 0x10000 > 0) {
result = (result * 0x1000000000000B172) >> 64;
}
if (x & 0x8000 > 0) {
result = (result * 0x100000000000058B9) >> 64;
}
if (x & 0x4000 > 0) {
result = (result * 0x10000000000002C5D) >> 64;
}
if (x & 0x2000 > 0) {
result = (result * 0x1000000000000162E) >> 64;
}
if (x & 0x1000 > 0) {
result = (result * 0x10000000000000B17) >> 64;
}
if (x & 0x800 > 0) {
result = (result * 0x1000000000000058C) >> 64;
}
if (x & 0x400 > 0) {
result = (result * 0x100000000000002C6) >> 64;
}
if (x & 0x200 > 0) {
result = (result * 0x10000000000000163) >> 64;
}
if (x & 0x100 > 0) {
result = (result * 0x100000000000000B1) >> 64;
}
if (x & 0x80 > 0) {
result = (result * 0x10000000000000059) >> 64;
}
if (x & 0x40 > 0) {
result = (result * 0x1000000000000002C) >> 64;
}
if (x & 0x20 > 0) {
result = (result * 0x10000000000000016) >> 64;
}
if (x & 0x10 > 0) {
result = (result * 0x1000000000000000B) >> 64;
}
if (x & 0x8 > 0) {
result = (result * 0x10000000000000006) >> 64;
}
if (x & 0x4 > 0) {
result = (result * 0x10000000000000003) >> 64;
}
if (x & 0x2 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
if (x & 0x1 > 0) {
result = (result * 0x10000000000000001) >> 64;
}
// We're doing two things at the same time:
//
// 1. Multiply the result by 2^n + 1, where "2^n" is the integer part and the one is added to account for
// the fact that we initially set the result to 0.5. This is accomplished by subtracting from 191
// rather than 192.
// 2. Convert the result to the unsigned 60.18-decimal fixed-point format.
//
// This works because 2^(191-ip) = 2^ip / 2^191, where "ip" is the integer part "2^n".
result *= SCALE;
result >>= (191 - (x >> 64));
}
}
/// @notice Finds the zero-based index of the first one in the binary representation of x.
/// @dev See the note on msb in the "Find First Set" Wikipedia article https://en.wikipedia.org/wiki/Find_first_set
/// @param x The uint256 number for which to find the index of the most significant bit.
/// @return msb The index of the most significant bit as an uint256.
function mostSignificantBit(uint256 x) internal pure returns (uint256 msb) {
if (x >= 2**128) {
x >>= 128;
msb += 128;
}
if (x >= 2**64) {
x >>= 64;
msb += 64;
}
if (x >= 2**32) {
x >>= 32;
msb += 32;
}
if (x >= 2**16) {
x >>= 16;
msb += 16;
}
if (x >= 2**8) {
x >>= 8;
msb += 8;
}
if (x >= 2**4) {
x >>= 4;
msb += 4;
}
if (x >= 2**2) {
x >>= 2;
msb += 2;
}
if (x >= 2**1) {
// No need to shift x any more.
msb += 1;
}
}
/// @notice Calculates floor(x*y÷denominator) with full precision.
///
/// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv.
///
/// Requirements:
/// - The denominator cannot be zero.
/// - The result must fit within uint256.
///
/// Caveats:
/// - This function does not work with fixed-point numbers.
///
/// @param x The multiplicand as an uint256.
/// @param y The multiplier as an uint256.
/// @param denominator The divisor as an uint256.
/// @return result The result as an uint256.
function mulDiv(
uint256 x,
uint256 y,
uint256 denominator
) internal pure returns (uint256 result) {
// 512-bit multiply [prod1 prod0] = x * y. Compute the product mod 2^256 and mod 2^256 - 1, then use
// 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(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
// Handle non-overflow cases, 256 by 256 division.
if (prod1 == 0) {
unchecked {
result = prod0 / denominator;
}
return result;
}
// Make sure the result is less than 2^256. Also prevents denominator == 0.
if (prod1 >= denominator) {
revert PRBMath__MulDivOverflow(prod1, denominator);
}
///////////////////////////////////////////////
// 512 by 256 division.
///////////////////////////////////////////////
// Make division exact by subtracting the remainder from [prod1 prod0].
uint256 remainder;
assembly {
// Compute remainder using mulmod.
remainder := mulmod(x, y, denominator)
// Subtract 256 bit number from 512 bit number.
prod1 := sub(prod1, gt(remainder, prod0))
prod0 := sub(prod0, remainder)
}
// Factor powers of two out of denominator and compute largest power of two divisor of denominator. Always >= 1.
// See https://cs.stackexchange.com/q/138556/92363.
unchecked {
// Does not overflow because the denominator cannot be zero at this stage in the function.
uint256 lpotdod = denominator & (~denominator + 1);
assembly {
// Divide denominator by lpotdod.
denominator := div(denominator, lpotdod)
// Divide [prod1 prod0] by lpotdod.
prod0 := div(prod0, lpotdod)
// Flip lpotdod such that it is 2^256 / lpotdod. If lpotdod is zero, then it becomes one.
lpotdod := add(div(sub(0, lpotdod), lpotdod), 1)
}
// Shift in bits from prod1 into prod0.
prod0 |= prod1 * lpotdod;
// 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 for
// four bits. That is, denominator * inv = 1 mod 2^4.
uint256 inverse = (3 * denominator) ^ 2;
// Use the 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.
inverse *= 2 - denominator * inverse; // inverse mod 2^8
inverse *= 2 - denominator * inverse; // inverse mod 2^16
inverse *= 2 - denominator * inverse; // inverse mod 2^32
inverse *= 2 - denominator * inverse; // inverse mod 2^64
inverse *= 2 - denominator * inverse; // inverse mod 2^128
inverse *= 2 - denominator * inverse; // 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 preconditions 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 * inverse;
return result;
}
}
/// @notice Calculates floor(x*y÷1e18) with full precision.
///
/// @dev Variant of "mulDiv" with constant folding, i.e. in which the denominator is always 1e18. Before returning the
/// final result, we add 1 if (x * y) % SCALE >= HALF_SCALE. Without this, 6.6e-19 would be truncated to 0 instead of
/// being rounded to 1e-18. See "Listing 6" and text above it at https://accu.org/index.php/journals/1717.
///
/// Requirements:
/// - The result must fit within uint256.
///
/// Caveats:
/// - The body is purposely left uncommented; see the NatSpec comments in "PRBMath.mulDiv" to understand how this works.
/// - It is assumed that the result can never be type(uint256).max when x and y solve the following two equations:
/// 1. x * y = type(uint256).max * SCALE
/// 2. (x * y) % SCALE >= SCALE / 2
///
/// @param x The multiplicand as an unsigned 60.18-decimal fixed-point number.
/// @param y The multiplier as an unsigned 60.18-decimal fixed-point number.
/// @return result The result as an unsigned 60.18-decimal fixed-point number.
function mulDivFixedPoint(uint256 x, uint256 y) internal pure returns (uint256 result) {
uint256 prod0;
uint256 prod1;
assembly {
let mm := mulmod(x, y, not(0))
prod0 := mul(x, y)
prod1 := sub(sub(mm, prod0), lt(mm, prod0))
}
if (prod1 >= SCALE) {
revert PRBMath__MulDivFixedPointOverflow(prod1);
}
uint256 remainder;
uint256 roundUpUnit;
assembly {
remainder := mulmod(x, y, SCALE)
roundUpUnit := gt(remainder, 499999999999999999)
}
if (prod1 == 0) {
unchecked {
result = (prod0 / SCALE) + roundUpUnit;
return result;
}
}
assembly {
result := add(
mul(
or(
div(sub(prod0, remainder), SCALE_LPOTD),
mul(sub(prod1, gt(remainder, prod0)), add(div(sub(0, SCALE_LPOTD), SCALE_LPOTD), 1))
),
SCALE_INVERSE
),
roundUpUnit
)
}
}
/// @notice Calculates floor(x*y÷denominator) with full precision.
///
/// @dev An extension of "mulDiv" for signed numbers. Works by computing the signs and the absolute values separately.
///
/// Requirements:
/// - None of the inputs can be type(int256).min.
/// - The result must fit within int256.
///
/// @param x The multiplicand as an int256.
/// @param y The multiplier as an int256.
/// @param denominator The divisor as an int256.
/// @return result The result as an int256.
function mulDivSigned(
int256 x,
int256 y,
int256 denominator
) internal pure returns (int256 result) {
if (x == type(int256).min || y == type(int256).min || denominator == type(int256).min) {
revert PRBMath__MulDivSignedInputTooSmall();
}
// Get hold of the absolute values of x, y and the denominator.
uint256 ax;
uint256 ay;
uint256 ad;
unchecked {
ax = x < 0 ? uint256(-x) : uint256(x);
ay = y < 0 ? uint256(-y) : uint256(y);
ad = denominator < 0 ? uint256(-denominator) : uint256(denominator);
}
// Compute the absolute value of (x*y)÷denominator. The result must fit within int256.
uint256 rAbs = mulDiv(ax, ay, ad);
if (rAbs > uint256(type(int256).max)) {
revert PRBMath__MulDivSignedOverflow(rAbs);
}
// Get the signs of x, y and the denominator.
uint256 sx;
uint256 sy;
uint256 sd;
assembly {
sx := sgt(x, sub(0, 1))
sy := sgt(y, sub(0, 1))
sd := sgt(denominator, sub(0, 1))
}
// XOR over sx, sy and sd. This is checking whether there are one or three negative signs in the inputs.
// If yes, the result should be negative.
result = sx ^ sy ^ sd == 0 ? -int256(rAbs) : int256(rAbs);
}
/// @notice Calculates the square root of x, rounding down.
/// @dev Uses the Babylonian method https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method.
///
/// Caveats:
/// - This function does not work with fixed-point numbers.
///
/// @param x The uint256 number for which to calculate the square root.
/// @return result The result as an uint256.
function sqrt(uint256 x) internal pure returns (uint256 result) {
if (x == 0) {
return 0;
}
// Set the initial guess to the least power of two that is greater than or equal to sqrt(x).
uint256 xAux = uint256(x);
result = 1;
if (xAux >= 0x100000000000000000000000000000000) {
xAux >>= 128;
result <<= 64;
}
if (xAux >= 0x10000000000000000) {
xAux >>= 64;
result <<= 32;
}
if (xAux >= 0x100000000) {
xAux >>= 32;
result <<= 16;
}
if (xAux >= 0x10000) {
xAux >>= 16;
result <<= 8;
}
if (xAux >= 0x100) {
xAux >>= 8;
result <<= 4;
}
if (xAux >= 0x10) {
xAux >>= 4;
result <<= 2;
}
if (xAux >= 0x8) {
result <<= 1;
}
// The operations can never overflow because the result is max 2^127 when it enters this block.
unchecked {
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1;
result = (result + x / result) >> 1; // Seven iterations should be enough
uint256 roundedDownResult = x / result;
return result >= roundedDownResult ? roundedDownResult : result;
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/ERC165Checker.sol";
import "@manifoldxyz/creator-core-solidity/contracts/core/IERC721CreatorCore.sol";
import "../../LegacyInterfaces.sol";
import "../SingleCreatorExtensionBase.sol";
/**
* @dev Extension that only uses a single creator contract instance
*/
abstract contract ERC721SingleCreatorExtensionBase is SingleCreatorExtensionBase {
function _setCreator(address creator) internal override {
require(ERC165Checker.supportsInterface(creator, type(IERC721CreatorCore).interfaceId) ||
ERC165Checker.supportsInterface(creator, LegacyInterfaces.IERC721CreatorCore_v1),
"Creator contract must implement IERC721CreatorCore");
super._setCreator(creator);
}
}
// 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
pragma solidity ^0.8.0;
/// @author: manifold.xyz
import "@openzeppelin/contracts/utils/introspection/IERC165.sol";
/**
* @dev Core creator interface
*/
interface ICreatorCore is IERC165 {
event ExtensionRegistered(address indexed extension, address indexed sender);
event ExtensionUnregistered(address indexed extension, address indexed sender);
event ExtensionBlacklisted(address indexed extension, address indexed sender);
event MintPermissionsUpdated(address indexed extension, address indexed permissions, address indexed sender);
event RoyaltiesUpdated(uint256 indexed tokenId, address payable[] receivers, uint256[] basisPoints);
event DefaultRoyaltiesUpdated(address payable[] receivers, uint256[] basisPoints);
event ExtensionRoyaltiesUpdated(address indexed extension, address payable[] receivers, uint256[] basisPoints);
event ExtensionApproveTransferUpdated(address indexed extension, bool enabled);
/**
* @dev gets address of all extensions
*/
function getExtensions() external view returns (address[] memory);
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(address extension, string calldata baseURI) external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* extension address must point to a contract implementing ICreatorExtension.
* Returns True if newly added, False if already added.
*/
function registerExtension(address extension, string calldata baseURI, bool baseURIIdentical) external;
/**
* @dev add an extension. Can only be called by contract owner or admin.
* Returns True if removed, False if already removed.
*/
function unregisterExtension(address extension) external;
/**
* @dev blacklist an extension. Can only be called by contract owner or admin.
* This function will destroy all ability to reference the metadata of any tokens created
* by the specified extension. It will also unregister the extension if needed.
* Returns True if removed, False if already removed.
*/
function blacklistExtension(address extension) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
*/
function setBaseTokenURIExtension(string calldata uri) external;
/**
* @dev set the baseTokenURI of an extension. Can only be called by extension.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURIExtension(string calldata uri, bool identical) external;
/**
* @dev set the common prefix of an extension. Can only be called by extension.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefixExtension(string calldata prefix) external;
/**
* @dev set the tokenURI of a token extension. Can only be called by extension that minted token.
*/
function setTokenURIExtension(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of a token extension for multiple tokens. Can only be called by extension that minted token.
*/
function setTokenURIExtension(uint256[] memory tokenId, string[] calldata uri) external;
/**
* @dev set the baseTokenURI for tokens with no extension. Can only be called by owner/admin.
* For tokens with no uri configured, tokenURI will return "uri+tokenId"
*/
function setBaseTokenURI(string calldata uri) external;
/**
* @dev set the common prefix for tokens with no extension. Can only be called by owner/admin.
* If configured, and a token has a uri set, tokenURI will return "prefixURI+tokenURI"
* Useful if you want to use ipfs/arweave
*/
function setTokenURIPrefix(string calldata prefix) external;
/**
* @dev set the tokenURI of a token with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256 tokenId, string calldata uri) external;
/**
* @dev set the tokenURI of multiple tokens with no extension. Can only be called by owner/admin.
*/
function setTokenURI(uint256[] memory tokenIds, string[] calldata uris) external;
/**
* @dev set a permissions contract for an extension. Used to control minting.
*/
function setMintPermissions(address extension, address permissions) external;
/**
* @dev Configure so transfers of tokens created by the caller (must be extension) gets approval
* from the extension before transferring
*/
function setApproveTransferExtension(bool enabled) external;
/**
* @dev get the extension of a given token
*/
function tokenExtension(uint256 tokenId) external view returns (address);
/**
* @dev Set default royalties
*/
function setRoyalties(address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Set royalties of a token
*/
function setRoyalties(uint256 tokenId, address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Set royalties of an extension
*/
function setRoyaltiesExtension(address extension, address payable[] calldata receivers, uint256[] calldata basisPoints) external;
/**
* @dev Get royalites of a token. Returns list of receivers and basisPoints
*/
function getRoyalties(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
// Royalty support for various other standards
function getFeeRecipients(uint256 tokenId) external view returns (address payable[] memory);
function getFeeBps(uint256 tokenId) external view returns (uint[] memory);
function getFees(uint256 tokenId) external view returns (address payable[] memory, uint256[] memory);
function royaltyInfo(uint256 tokenId, uint256 value) external view returns (address, uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/// @author: manifold.xyz
/**
* @dev Extension that only uses a single creator contract instance
*/
abstract contract SingleCreatorExtensionBase {
address internal _creator;
/**
* @dev Override with appropriate interface checks if necessary
*/
function _setCreator(address creator) internal virtual {
_creator = creator;
}
function creatorContract() public view returns(address) {
return _creator;
}
}
// SPDX-License-Identifier: BSD-4-Clause
pragma solidity ^0.8.0;
/// @author: manifold.xyz
/**
* Library of legacy interface constants
*/
library LegacyInterfaces {
// LEGACY ERC721CreatorCore interface
bytes4 internal constant IERC721CreatorCore_v1 = 0x478c8530;
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Checker.sol)
pragma solidity ^0.8.0;
import "./IERC165.sol";
/**
* @dev Library used to query support of an interface declared via {IERC165}.
*
* Note that these functions return the actual result of the query: they do not
* `revert` if an interface is not supported. It is up to the caller to decide
* what to do in these cases.
*/
library ERC165Checker {
// As per the EIP-165 spec, no interface should ever match 0xffffffff
bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff;
/**
* @dev Returns true if `account` supports the {IERC165} interface,
*/
function supportsERC165(address account) internal view returns (bool) {
// Any contract that implements ERC165 must explicitly indicate support of
// InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid
return
_supportsERC165Interface(account, type(IERC165).interfaceId) &&
!_supportsERC165Interface(account, _INTERFACE_ID_INVALID);
}
/**
* @dev Returns true if `account` supports the interface defined by
* `interfaceId`. Support for {IERC165} itself is queried automatically.
*
* See {IERC165-supportsInterface}.
*/
function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) {
// query support of both ERC165 as per the spec and support of _interfaceId
return supportsERC165(account) && _supportsERC165Interface(account, interfaceId);
}
/**
* @dev Returns a boolean array where each value corresponds to the
* interfaces passed in and whether they're supported or not. This allows
* you to batch check interfaces for a contract where your expectation
* is that some interfaces may not be supported.
*
* See {IERC165-supportsInterface}.
*
* _Available since v3.4._
*/
function getSupportedInterfaces(address account, bytes4[] memory interfaceIds)
internal
view
returns (bool[] memory)
{
// an array of booleans corresponding to interfaceIds and whether they're supported or not
bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length);
// query support of ERC165 itself
if (supportsERC165(account)) {
// query support of each interface in interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]);
}
}
return interfaceIdsSupported;
}
/**
* @dev Returns true if `account` supports all the interfaces defined in
* `interfaceIds`. Support for {IERC165} itself is queried automatically.
*
* Batch-querying can lead to gas savings by skipping repeated checks for
* {IERC165} support.
*
* See {IERC165-supportsInterface}.
*/
function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) {
// query support of ERC165 itself
if (!supportsERC165(account)) {
return false;
}
// query support of each interface in _interfaceIds
for (uint256 i = 0; i < interfaceIds.length; i++) {
if (!_supportsERC165Interface(account, interfaceIds[i])) {
return false;
}
}
// all interfaces supported
return true;
}
/**
* @notice Query if a contract implements an interface, does not check ERC165 support
* @param account The address of the contract to query for support of an interface
* @param interfaceId The interface identifier, as specified in ERC-165
* @return true if the contract at account indicates support of the interface with
* identifier interfaceId, false otherwise
* @dev Assumes that account contains a contract that supports ERC165, otherwise
* the behavior of this method is undefined. This precondition can be checked
* with {supportsERC165}.
* Interface identification is specified in ERC-165.
*/
function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) {
bytes memory encodedParams = abi.encodeWithSelector(IERC165.supportsInterface.selector, interfaceId);
(bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams);
if (result.length < 32) return false;
return success && abi.decode(result, (bool));
}
}
|
Yields the excess beyond the floor of x for positive numbers and the part of the number to the right of the radix point for negative numbers. Based on the odd function definition. https://en.wikipedia.org/wiki/Fractional_part x The signed 59.18-decimal fixed-point number to get the fractional part of. result The fractional part of x as a signed 59.18-decimal fixed-point number.
|
function frac(int256 x) internal pure returns (int256 result) {
unchecked {
result = x % SCALE;
}
}
| 10,297,525 |
./full_match/122/0xFAE02d404c327A1Eb2fB38eb89C38860a02D70e6/sources/contracts/LiquidStakingPool.sol
|
Checks if address is a current validator on list _validator the address to be checked/
|
function isInValidatorList(address _validator) public view returns(bool) {
address[] memory validatorList = getValidators();
for (uint256 i = 0; i < validatorList.length; i++) {
if(validatorList[i] == _validator) {
return true;
}
}
return false;
}
| 16,366,174 |
./partial_match/1/0x73aEA21988365C9F0943416044608017BBAeaF53/sources/xBond.sol
|
Transfer tokens from one address to another. from The address you want to send tokens from. to The address you want to transfer to. value The amount of tokens to be transferred./ make sure users cannot double claim if they have already claimed
|
function transferFrom(address from, address to, uint256 value)
public
updateAccount(from)
updateAccount(to)
validRecipient(to)
returns (bool)
{
if (lastUserRebase[from] == lastRebase) lastUserRebase[to] = lastRebase;
lastUserPoints[from] = totalDollarPoints;
_allowedBond[from][msg.sender] = _allowedBond[from][msg.sender].sub(value);
_bondBalances[from] = _bondBalances[from].sub(value);
_bondBalances[to] = _bondBalances[to].add(value);
emit Transfer(from, to, value);
return true;
}
| 4,354,642 |
./full_match/1/0x1Ef92666550De8b1bdD530Ad03a8de14E1fBbaa4/sources/contracts/PawfuryV1.sol
|
To buy into a presale using ETH amount No of tokens to buy/
|
function buyWithEth(
uint256 amount
)
external
payable
checkSaleState(amount)
whenNotPaused
nonReentrant
returns (bool)
{
require(amount >= minTokensToBuy, "Amount less");
uint256 usdPrice = calculatePrice(amount);
uint256 ethAmount = (usdPrice * baseDecimals) / getLatestPrice();
require(msg.value >= ethAmount, "Less payment");
uint256 excess = msg.value - ethAmount;
totalTokensSold += amount;
if (checkPoint != 0) checkPoint += amount;
uint256 total = totalTokensSold > checkPoint
? totalTokensSold
: checkPoint;
if (
total > rounds[0][currentStep] ||
block.timestamp >= rounds[2][currentStep]
) {
if (block.timestamp >= rounds[2][currentStep]) {
checkPoint = rounds[0][currentStep] + amount;
if (dynamicTimeFlag) {
manageTimeDiff();
}
}
uint256 unsoldTokens = total > rounds[0][currentStep]
? 0
: rounds[0][currentStep] - total;
remainingTokensTracker.push(unsoldTokens);
prevUsdRaised.push(usdRaised);
currentStep += 1;
emit StepIncrement(currentStep);
}
userDeposits[_msgSender()] += (amount * baseDecimals);
usdRaised += usdPrice;
sendValue(payable(paymentWallet), ethAmount);
if (excess > 0) sendValue(payable(_msgSender()), excess);
emit TokensBought(
_msgSender(),
amount,
address(0),
ethAmount,
usdPrice,
block.timestamp
);
return true;
}
| 8,343,459 |
./partial_match/1/0xa06A604184dc15d3BdDc514a1c327957B7388128/sources/HarryPotterObamaTerraSonic10Inu.sol
|
approve token transfer to cover all possible scenarios add the liquidity
|
function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private {
_approve(address(this), address(uniswapV2Router), tokenAmount);
address(this),
tokenAmount,
deadAddress,
block.timestamp
}
| 2,686,615 |
pragma solidity 0.5.8;
contract Ownable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
constructor () internal {
_owner = msg.sender;
emit OwnershipTransferred(address(0), _owner);
}
function owner() public view returns (address) {
return _owner;
}
modifier onlyOwner() {
require(isOwner());
_;
}
function isOwner() public view returns (bool) {
return msg.sender == _owner;
}
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0));
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
/**
* @title RelayRegistry
* @dev Singleton contract that registers a whitelist of relays accessed by the factory and smart wallets. Contract is owned by an external account for now but ownership should be transferred to a governance contract in the future.
*/
contract RelayRegistry is Ownable {
event AddedRelay(address relay);
event RemovedRelay(address relay);
mapping (address => bool) public relays;
constructor(address initialRelay) public {
relays[initialRelay] = true;
}
/**
* @dev Allows relay registry owner to add or remove a relay from the whitelist
* @param relay Address of the selected relay
* @param value True to add them to the whitelist, false to remove them
*/
function triggerRelay(address relay, bool value) onlyOwner public returns (bool) {
relays[relay] = value;
if(value) {
emit AddedRelay(relay);
} else {
emit RemovedRelay(relay);
}
return true;
}
}
interface IERC20 {
function transfer(address to, uint256 value) external returns (bool);
}
/**
* @title Smart Wallet Contract
* @dev All functions of this contract should be called using delegatecall from the Proxy contract. This allows us to significantly reduce the deployment costs of smart wallets. All functions of this contract are executed in the context of Proxy contract.
*/
contract SmartWallet {
event Upgrade(address indexed newImplementation);
/**
* @dev Shared key value store. Data should be encoded and decoded using abi.encode()/abi.decode() by different functions. No data is actually stored in SmartWallet, instead everything is stored in the Proxy contract's context.
*/
mapping (bytes32 => bytes) public store;
modifier onlyRelay {
RelayRegistry registry = RelayRegistry(0x4360b517f5b3b2D4ddfAEDb4fBFc7eF0F48A4Faa);
require(registry.relays(msg.sender));
_;
}
modifier onlyOwner {
require(msg.sender == abi.decode(store["factory"], (address)) || msg.sender == abi.decode(store["owner"], (address)));
_;
}
/**
* @dev Function called once by Factory contract to initiate owner and nonce. This is necessary because we cannot pass arguments to a CREATE2-created contract without changing its address.
* @param owner Wallet Owner
*/
function initiate(address owner) public returns (bool) {
// this function can only be called by the factory
if(msg.sender != abi.decode(store["factory"], (address))) return false;
// store current owner in key store
store["owner"] = abi.encode(owner);
store["nonce"] = abi.encode(0);
return true;
}
/**
* @dev Same as above, but also applies a feee to a relayer address provided by the factory
* @param owner Wallet Owner
* @param relay Address of the relayer
* @param fee Fee paid to relayer in a token
* @param token Address of ERC20 contract in which fee will be denominated.
*/
function initiate(address owner, address relay, uint fee, address token) public returns (bool) {
require(initiate(owner), "internal initiate failed");
// Access ERC20 token
IERC20 tokenContract = IERC20(token);
// Send fee to relay
tokenContract.transfer(relay, fee);
return true;
}
/**
* @dev Relayed token transfer. Submitted by a relayer on behalf of the wallet owner.
* @param to Recipient address
* @param value Transfer amount
* @param fee Fee paid to the relayer
* @param tokenContract Address of the token contract used for both the transfer and the fees
* @param deadline Block number deadline for this signed message
*/
function pay(address to, uint value, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) {
uint currentNonce = abi.decode(store["nonce"], (uint));
require(block.number <= deadline);
require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("pay", msg.sender, to, tokenContract, value, fee, tx.gasprice, currentNonce, deadline)), v, r, s));
IERC20 token = IERC20(tokenContract);
store["nonce"] = abi.encode(currentNonce+1);
token.transfer(to, value);
token.transfer(msg.sender, fee);
return true;
}
/**
* @dev Direct token transfer. Submitted by the wallet owner
* @param to Recipient address
* @param value Transfer amount
* @param tokenContract Address of the token contract used for the transfer
*/
function pay(address to, uint value, address tokenContract) onlyOwner public returns (bool) {
IERC20 token = IERC20(tokenContract);
token.transfer(to, value);
return true;
}
/**
* @dev Same as above but allows batched transfers in multiple tokens
*/
function pay(address[] memory to, uint[] memory value, address[] memory tokenContract) onlyOwner public returns (bool) {
for (uint i; i < to.length; i++) {
IERC20 token = IERC20(tokenContract[i]);
token.transfer(to[i], value[i]);
}
return true;
}
/**
* @dev Internal function that executes a call to any contract
* @param contractAddress Address of the contract to call
* @param data calldata to send to contractAddress
* @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance
*/
function _execCall(address contractAddress, bytes memory data, uint256 msgValue) internal returns (bool result) {
// Warning: This executes an external contract call, may pose re-entrancy risk.
assembly {
result := call(gas, contractAddress, msgValue, add(data, 0x20), mload(data), 0, 0)
}
}
/**
* @dev Internal function that creates any contract
* @param data bytecode of the new contract
*/
function _execCreate(bytes memory data) internal returns (bool result) {
address deployedContract;
assembly {
deployedContract := create(0, add(data, 0x20), mload(data))
}
result = (deployedContract != address(0));
}
/**
* @dev Internal function that creates any contract using create2
* @param data bytecode of the new contract
* @param salt Create2 salt parameter
*/
function _execCreate2(bytes memory data, uint256 salt) internal returns (bool result) {
address deployedContract;
assembly {
deployedContract := create2(0, add(data, 0x20), mload(data), salt)
}
result = (deployedContract != address(0));
}
/**
* @dev Public function that allows the owner to execute a call to any contract
* @param contractAddress Address of the contract to call
* @param data calldata to send to contractAddress
* @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance
*/
function execCall(address contractAddress, bytes memory data, uint256 msgValue) onlyOwner public returns (bool) {
require(_execCall(contractAddress, data, msgValue));
return true;
}
/**
* @dev Public function that allows a relayer to execute a call to any contract on behalf of the owner
* @param contractAddress Address of the contract to call
* @param data calldata to send to contractAddress
* @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance
* @param fee Fee paid to the relayer
* @param tokenContract Address of the token contract used for the fee
* @param deadline Block number deadline for this signed message
*/
function execCall(address contractAddress, bytes memory data, uint256 msgValue, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) {
uint currentNonce = abi.decode(store["nonce"], (uint));
require(block.number <= deadline);
require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCall", msg.sender, contractAddress, tokenContract, data, msgValue, fee, tx.gasprice, currentNonce, deadline)), v, r, s));
IERC20 token = IERC20(tokenContract);
store["nonce"] = abi.encode(currentNonce+1);
token.transfer(msg.sender, fee);
require(_execCall(contractAddress, data, msgValue));
return true;
}
/**
* @dev Public function that allows the owner to create any contract
* @param data bytecode of the new contract
*/
function execCreate(bytes memory data) onlyOwner public returns (bool) {
require(_execCreate(data));
return true;
}
/**
* @dev Public function that allows a relayer to create any contract on behalf of the owner
* @param data new contract bytecode
* @param fee Fee paid to the relayer
* @param tokenContract Address of the token contract used for the fee
* @param deadline Block number deadline for this signed message
*/
function execCreate(bytes memory data, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) {
uint currentNonce = abi.decode(store["nonce"], (uint));
require(block.number <= deadline);
require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCreate", msg.sender, tokenContract, data, fee, tx.gasprice, currentNonce, deadline)), v, r, s));
require(_execCreate(data));
IERC20 token = IERC20(tokenContract);
store["nonce"] = abi.encode(currentNonce+1);
token.transfer(msg.sender, fee);
return true;
}
/**
* @dev Public function that allows the owner to create any contract using create2
* @param data bytecode of the new contract
* @param salt Create2 salt parameter
*/
function execCreate2(bytes memory data, uint salt) onlyOwner public returns (bool) {
require(_execCreate2(data, salt));
return true;
}
/**
* @dev Public function that allows a relayer to create any contract on behalf of the owner using create2
* @param data new contract bytecode
* @param salt Create2 salt parameter
* @param fee Fee paid to the relayer
* @param tokenContract Address of the token contract used for the fee
* @param deadline Block number deadline for this signed message
*/
function execCreate2(bytes memory data, uint salt, uint fee, address tokenContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) {
uint currentNonce = abi.decode(store["nonce"], (uint));
require(block.number <= deadline);
require(abi.decode(store["owner"], (address)) == recover(keccak256(abi.encodePacked("execCreate2", msg.sender, tokenContract, data, salt, fee, tx.gasprice, currentNonce, deadline)), v, r, s));
require(_execCreate2(data, salt));
IERC20 token = IERC20(tokenContract);
store["nonce"] = abi.encode(currentNonce+1);
token.transfer(msg.sender, fee);
return true;
}
/**
* @dev Since all eth transfers to this contract are redirected to the owner. This is the only way for anyone, including the owner, to keep ETH on this contract.
*/
function depositEth() public payable {}
/**
* @dev Allows the owner to withdraw all ETH from the contract.
*/
function withdrawEth() public onlyOwner() {
address payable owner = abi.decode(store["owner"], (address));
owner.transfer(address(this).balance);
}
/**
* @dev Allows a relayer to change the address of the smart wallet implementation contract on behalf of the owner. New contract should have its own upgradability logic or Proxy will be stuck on it.
* @param implementation Address of the new implementation contract to replace this one.
* @param fee Fee paid to the relayer
* @param feeContract Address of the fee token contract
* @param deadline Block number deadline for this signed message
*/
function upgrade(address implementation, uint fee, address feeContract, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (bool) {
uint currentNonce = abi.decode(store["nonce"], (uint));
require(block.number <= deadline);
address owner = abi.decode(store["owner"], (address));
require(owner == recover(keccak256(abi.encodePacked("upgrade", msg.sender, implementation, feeContract, fee, tx.gasprice, currentNonce, deadline)), v, r, s));
store["nonce"] = abi.encode(currentNonce+1);
store["fallback"] = abi.encode(implementation);
IERC20 feeToken = IERC20(feeContract);
feeToken.transfer(msg.sender, fee);
emit Upgrade(implementation);
return true;
}
/**
* @dev Same as above, but activated directly by the owner.
* @param implementation Address of the new implementation contract to replace this one.
*/
function upgrade(address implementation) onlyOwner public returns (bool) {
store["fallback"] = abi.encode(implementation);
emit Upgrade(implementation);
return true;
}
/**
* @dev Internal function used to prefix hashes to allow for compatibility with signers such as Metamask
* @param messageHash Original hash
*/
function recover(bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
bytes memory prefix = "\x19Metacash Signed Message:\n32";
bytes32 prefixedMessageHash = keccak256(abi.encodePacked(prefix, messageHash));
return ecrecover(prefixedMessageHash, v, r, s);
}
}
/**
* @title Proxy
* @dev This contract is usually deployed as part of every user's first gasless transaction. It refers to a hardcoded address of the smart wallet contract and uses its functions via delegatecall.
*/
contract Proxy {
/**
* @dev Shared key value store. All data across different SmartWallet implementations is stored here. It also keeps storage across different upgrades.
*/
mapping (bytes32 => bytes) public store;
/**
* @dev The Proxy constructor adds the hardcoded address of SmartWallet and the address of the factory (from msg.sender) to the store for later transactions
*/
constructor() public {
// set implementation address in storage
store["fallback"] = abi.encode(0xEfc66C37a06507bCcABc0ce8d8bb5Ac4c1A2a8AA); // SmartWallet address
// set factory address in storage
store["factory"] = abi.encode(msg.sender);
}
/**
* @dev The fallback functions forwards everything as a delegatecall to the implementation SmartWallet contract
*/
function() external payable {
address impl = abi.decode(store["fallback"], (address));
assembly {
let ptr := mload(0x40)
// (1) copy incoming call data
calldatacopy(ptr, 0, calldatasize)
// (2) forward call to logic contract
let result := delegatecall(gas, impl, ptr, calldatasize, 0, 0)
let size := returndatasize
// (3) retrieve return data
returndatacopy(ptr, 0, size)
// (4) forward return data back to caller
switch result
case 0 { revert(ptr, size) }
default { return(ptr, size) }
}
}
}
/**
* @title Smart wallet factory
* @dev Singleton contract responsible for deploying new smart wallet instances
*/
contract Factory {
event Deployed(address indexed addr, address indexed owner);
modifier onlyRelay {
RelayRegistry registry = RelayRegistry(0x4360b517f5b3b2D4ddfAEDb4fBFc7eF0F48A4Faa); // Relay Registry address
require(registry.relays(msg.sender));
_;
}
/**
* @dev Internal function used for deploying smart wallets using create2
* @param owner Address of the wallet signer address (external account) associated with the smart wallet
*/
function deployCreate2(address owner) internal returns (address) {
bytes memory code = type(Proxy).creationCode;
address addr;
assembly {
// create2
addr := create2(0, add(code, 0x20), mload(code), owner)
// revert if contract was not created
if iszero(extcodesize(addr)) {revert(0, 0)}
}
return addr;
}
/**
* @dev Allows a relayer to deploy a smart wallet on behalf of a user
* @param fee Fee paid from the user's newly deployed smart wallet to the relay
* @param token Address of token contract for the fee
* @param deadline Block number deadline for this signed message
*/
function deployWallet(uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address) {
require(block.number <= deadline);
address signer = recover(keccak256(abi.encodePacked("deployWallet", msg.sender, token, tx.gasprice, fee, deadline)), v, r, s);
address addr = deployCreate2(signer);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.initiate(signer, msg.sender, fee, token));
emit Deployed(addr, signer);
return addr;
}
/**
* @dev Allows a relayer to deploy a smart wallet and send a token transfer on behalf of a user
* @param fee Fee paid from the user's newly deployed smart wallet to the relay
* @param token Address of token contract for the fee
* @param to Transfer recipient address
* @param value Transfer amount
* @param deadline Block number deadline for this signed message
*/
function deployWalletPay(uint fee, address token, address to, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) {
require(block.number <= deadline);
address signer = recover(keccak256(abi.encodePacked("deployWalletPay", msg.sender, token, to, tx.gasprice, fee, value, deadline)), v, r, s);
addr = deployCreate2(signer);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.initiate(signer, msg.sender, fee, token));
require(wallet.pay(to, value, token));
emit Deployed(addr, signer);
}
/**
* @dev Allows a user to directly deploy their own smart wallet
*/
function deployWallet() public returns (address) {
address addr = deployCreate2(msg.sender);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.initiate(msg.sender));
emit Deployed(addr, msg.sender);
return addr;
}
/**
* @dev Same as above, but also sends a transfer from the newly-deployed smart wallet
* @param token Address of the token contract for the transfer
* @param to Transfer recipient address
* @param value Transfer amount
*/
function deployWalletPay(address token, address to, uint value) public returns (address) {
address addr = deployCreate2(msg.sender);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.pay(to, value, token));
require(wallet.initiate(msg.sender));
emit Deployed(addr, msg.sender);
return addr;
}
/**
* @dev Allows user to deploy their wallet and execute a call operation to a foreign contract.
* @notice The order of wallet.execCall & wallet.initiate is important. It allows the fee to be paid after the execution is finished. This allows collect-call use cases.
* @param contractAddress Address of the contract to call
* @param data calldata to send to contractAddress
*/
function deployWalletExecCall(address contractAddress, bytes memory data) public payable returns (address) {
address addr = deployCreate2(msg.sender);
SmartWallet wallet = SmartWallet(uint160(addr));
if(msg.value > 0) {
wallet.depositEth.value(msg.value)();
}
require(wallet.execCall(contractAddress, data, msg.value));
require(wallet.initiate(msg.sender));
emit Deployed(addr, msg.sender);
return addr;
}
/**
* @dev Allows a relayer to deploy a wallet and execute a call operation to a foreign contract on behalf of a user.
* @param contractAddress Address of the contract to call
* @param data calldata to send to contractAddress
* @param msgValue Amount in wei to be sent with the call to the contract from the wallet's balance
* @param fee Fee paid to the relayer
* @param token Address of the token contract for the fee
* @param deadline Block number deadline for this signed message
*/
function deployWalletExecCall(address contractAddress, bytes memory data, uint msgValue, uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) {
require(block.number <= deadline);
address signer = recover(keccak256(abi.encodePacked("deployWalletExecCall", msg.sender, token, contractAddress, data, msgValue, tx.gasprice, fee, deadline)), v, r, s);
addr = deployCreate2(signer);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.execCall(contractAddress, data, msgValue));
require(wallet.initiate(signer, msg.sender, fee, token));
emit Deployed(addr, signer);
}
/**
* @dev Allows user to deploy their wallet and deploy a new contract through their wallet
* @param data bytecode of the new contract
*/
function deployWalletExecCreate(bytes memory data) public returns (address) {
address addr = deployCreate2(msg.sender);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.execCreate(data));
require(wallet.initiate(msg.sender));
emit Deployed(addr, msg.sender);
return addr;
}
/**
* @dev Allows a relayer to deploy a wallet and deploy a new contract through the wallet on behalf of a user.
* @param data bytecode of the new contract
* @param fee Fee paid to the relayer
* @param token Address of the token contract for the fee
* @param deadline Block number deadline for this signed message
*/
function deployWalletExecCreate(bytes memory data, uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) {
require(block.number <= deadline);
address signer = recover(keccak256(abi.encodePacked("deployWalletExecCreate", msg.sender, token, data, tx.gasprice, fee, deadline)), v, r, s);
addr = deployCreate2(signer);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.execCreate(data));
require(wallet.initiate(signer, msg.sender, fee, token));
emit Deployed(addr, signer);
}
/**
* @dev Allows user to deploy their wallet and deploy a new contract through their wallet using create2
* @param data bytecode of the new contract
* @param salt create2 salt parameter
*/
function deployWalletExecCreate2(bytes memory data, uint salt) public returns (address) {
address addr = deployCreate2(msg.sender);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.execCreate2(data, salt));
require(wallet.initiate(msg.sender));
emit Deployed(addr, msg.sender);
return addr;
}
/**
* @dev Allows a relayer to deploy a wallet and deploy a new contract through the wallet using create2 on behalf of a user.
* @param data bytecode of the new contract
* @param salt create2 salt parameter
* @param fee Fee paid to the relayer
* @param token Address of the token contract for the fee
* @param deadline Block number deadline for this signed message
*/
function deployWalletExecCreate2(bytes memory data, uint salt, uint fee, address token, uint deadline, uint8 v, bytes32 r, bytes32 s) onlyRelay public returns (address addr) {
require(block.number <= deadline);
address signer = recover(keccak256(abi.encodePacked("deployWalletExecCreate2", msg.sender, token, data, tx.gasprice, salt, fee, deadline)), v, r, s);
addr = deployCreate2(signer);
SmartWallet wallet = SmartWallet(uint160(addr));
require(wallet.execCreate2(data, salt));
require(wallet.initiate(signer, msg.sender, fee, token));
emit Deployed(addr, signer);
}
/**
* @dev Utility view function that allows clients to fetch a smart wallet address of any signer address
* @param owner Signer address
*/
function getCreate2Address(address owner) public view returns (address) {
bytes32 temp = keccak256(abi.encodePacked(bytes1(0xff), address(this), uint(owner), bytes32(keccak256(type(Proxy).creationCode))));
address ret;
uint mask = 2 ** 160 - 1;
assembly {
ret := and(temp, mask)
}
return ret;
}
/**
* @dev Utility view function that allows clients to fetch own smart wallet address
*/
function getCreate2Address() public view returns (address) {
return getCreate2Address(msg.sender);
}
/**
* @dev Utility view function that allows clients to query whether a signer's smart wallet can be deployed or has already been
* @param owner Signer address
*/
function canDeploy(address owner) public view returns (bool inexistent) {
address wallet = getCreate2Address(owner);
assembly {
inexistent := eq(extcodesize(wallet), 0)
}
}
/**
* @dev Utility view function that allows clients to query whether their signer's smart wallet can be deployed or has already been
*/
function canDeploy() public view returns (bool) {
return canDeploy(msg.sender);
}
/**
* @dev Internal function used to prefix hashes to allow for compatibility with signers such as Metamask
* @param messageHash Original hash
*/
function recover(bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
bytes memory prefix = "\x19Metacash Signed Message:\n32";
bytes32 prefixedMessageHash = keccak256(abi.encodePacked(prefix, messageHash));
return ecrecover(prefixedMessageHash, v, r, s);
}
}
|
Internal function used to prefix hashes to allow for compatibility with signers such as Metamask messageHash Original hash/
|
function recover(bytes32 messageHash, uint8 v, bytes32 r, bytes32 s) internal pure returns (address) {
bytes memory prefix = "\x19Metacash Signed Message:\n32";
bytes32 prefixedMessageHash = keccak256(abi.encodePacked(prefix, messageHash));
return ecrecover(prefixedMessageHash, v, r, s);
}
| 6,353,910 |
./full_match/11155111/0x7f13131E32AaF7CB286310D24B451bC71de5Faf8/sources/contracts/RealEstate.sol
|
Funtions for reviews
|
function addReview(uint productId, uint256 rating, string calldata comment, address user) external{
require(rating >=1 && rating <=5, "Rating must be between 1 to 5");
Property storage property=properties[productId];
property.reviewers.push(user);
property.reviews.push(comment);
reviews[productId].push(Review(user, productId, rating, comment, 0));
userReviews[user].push(productId);
products[productId].totalRating+=rating;
products[productId].numReviews++;
emit ReviewAdded(productId, user, rating, comment);
reviewCounter++;
}
| 3,836,341 |
/*
Copyright 2018 ZeroEx Intl.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
pragma solidity ^0.4.24;
import "../LibMem/LibMem.sol";
contract LibBytes is
LibMem
{
// Revert reasons
string constant GREATER_THAN_ZERO_LENGTH_REQUIRED = "GREATER_THAN_ZERO_LENGTH_REQUIRED";
string constant GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED = "GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED";
string constant GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED = "GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED";
string constant GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED = "GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED";
string constant GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED = "GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED";
string constant GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED = "GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED";
/// @dev Pops the last byte off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The byte that was popped off.
function popLastByte(bytes memory b)
internal
pure
returns (bytes1 result)
{
require(
b.length > 0,
GREATER_THAN_ZERO_LENGTH_REQUIRED
);
// Store last byte.
result = b[b.length - 1];
assembly {
// Decrement length of byte array.
let newLen := sub(mload(b), 1)
mstore(b, newLen)
}
return result;
}
/// @dev Pops the last 20 bytes off of a byte array by modifying its length.
/// @param b Byte array that will be modified.
/// @return The 20 byte address that was popped off.
function popLast20Bytes(bytes memory b)
internal
pure
returns (address result)
{
require(
b.length >= 20,
GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED
);
// Store last 20 bytes.
result = readAddress(b, b.length - 20);
assembly {
// Subtract 20 from byte array length.
let newLen := sub(mload(b), 20)
mstore(b, newLen)
}
return result;
}
/// @dev Reads an address from a position in a byte array.
/// @param b Byte array containing an address.
/// @param index Index in byte array of address.
/// @return address from byte array.
function readAddress(
bytes memory b,
uint256 index
)
internal
pure
returns (address result)
{
require(
b.length >= index + 20, // 20 is length of address
GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Read address from array memory
assembly {
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 20-byte mask to obtain address
result := and(mload(add(b, index)), 0xffffffffffffffffffffffffffffffffffffffff)
}
return result;
}
/// @dev Writes an address into a specific position in a byte array.
/// @param b Byte array to insert address into.
/// @param index Index in byte array of address.
/// @param input Address to put into byte array.
function writeAddress(
bytes memory b,
uint256 index,
address input
)
internal
pure
{
require(
b.length >= index + 20, // 20 is length of address
GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED
);
// Add offset to index:
// 1. Arrays are prefixed by 32-byte length parameter (add 32 to index)
// 2. Account for size difference between address length and 32-byte storage word (subtract 12 from index)
index += 20;
// Store address into array memory
assembly {
// The address occupies 20 bytes and mstore stores 32 bytes.
// First fetch the 32-byte word where we'll be storing the address, then
// apply a mask so we have only the bytes in the word that the address will not occupy.
// Then combine these bytes with the address and store the 32 bytes back to memory with mstore.
// 1. Add index to address of bytes array
// 2. Load 32-byte word from memory
// 3. Apply 12-byte mask to obtain extra bytes occupying word of memory where we'll store the address
let neighbors := and(mload(add(b, index)), 0xffffffffffffffffffffffff0000000000000000000000000000000000000000)
// Store the neighbors and address into memory
mstore(add(b, index), xor(input, neighbors))
}
}
/// @dev Reads a bytes32 value from a position in a byte array.
/// @param b Byte array containing a bytes32 value.
/// @param index Index in byte array of bytes32 value.
/// @return bytes32 value from byte array.
function readBytes32(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes32 result)
{
require(
b.length >= index + 32,
GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED
);
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
result := mload(add(b, index))
}
return result;
}
/// @dev Writes a bytes32 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes32 to put into byte array.
function writeBytes32(
bytes memory b,
uint256 index,
bytes32 input
)
internal
pure
{
require(
b.length >= index + 32,
GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED
);
// Arrays are prefixed by a 256 bit length parameter
index += 32;
// Read the bytes32 from array memory
assembly {
mstore(add(b, index), input)
}
}
/// @dev Reads a uint256 value from a position in a byte array.
/// @param b Byte array containing a uint256 value.
/// @param index Index in byte array of uint256 value.
/// @return uint256 value from byte array.
function readUint256(
bytes memory b,
uint256 index
)
internal
pure
returns (uint256 result)
{
return uint256(readBytes32(b, index));
}
/// @dev Writes a uint256 into a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input uint256 to put into byte array.
function writeUint256(
bytes memory b,
uint256 index,
uint256 input
)
internal
pure
{
writeBytes32(b, index, bytes32(input));
}
/// @dev Reads the first 4 bytes from a byte array of arbitrary length.
/// @param b Byte array to read first 4 bytes from.
/// @return First 4 bytes of data.
function readFirst4(bytes memory b)
internal
pure
returns (bytes4 result)
{
require(
b.length >= 4,
GREATER_OR_EQUAL_TO_4_LENGTH_REQUIRED
);
assembly {
result := mload(add(b, 32))
}
return result;
}
/// @dev Reads nested bytes from a specific position.
/// @param b Byte array containing nested bytes.
/// @param index Index of nested bytes.
/// @return result Nested bytes.
function readBytes(
bytes memory b,
uint256 index
)
internal
pure
returns (bytes memory result)
{
// Read length of nested bytes
uint256 nestedBytesLength = readUint256(b, index);
index += 32;
// Assert length of <b> is valid, given
// length of nested bytes
require(
b.length >= index + nestedBytesLength,
GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED
);
// Allocate memory and copy value to result
result = new bytes(nestedBytesLength);
memCopy(
getMemAddress(result) + 32, // +32 skips array length
getMemAddress(b) + index + 32,
nestedBytesLength
);
return result;
}
/// @dev Inserts bytes at a specific position in a byte array.
/// @param b Byte array to insert <input> into.
/// @param index Index in byte array of <input>.
/// @param input bytes to insert.
function writeBytes(
bytes memory b,
uint256 index,
bytes memory input
)
internal
pure
{
// Assert length of <b> is valid, given
// length of input
require(
b.length >= index + 32 /* 32 bytes to store length */ + input.length,
GREATER_OR_EQUAL_TO_NESTED_BYTES_LENGTH_REQUIRED
);
// Copy <input> into <b>
memCopy(
getMemAddress(b) + 32 + index, // +32 to skip length of <b>
getMemAddress(input), // includes length of <input>
input.length + 32 // +32 bytes to store <input> length
);
}
/// @dev Tests equality of two byte arrays.
/// @param lhs First byte array to compare.
/// @param rhs Second byte array to compare.
/// @return True if arrays are the same. False otherwise.
function areBytesEqual(
bytes memory lhs,
bytes memory rhs
)
internal
pure
returns (bool equal)
{
assembly {
// Get the number of words occupied by <lhs>
let lenFullWords := div(add(mload(lhs), 0x1F), 0x20)
// Add 1 to the number of words, to account for the length field
lenFullWords := add(lenFullWords, 0x1)
// Test equality word-by-word.
// Terminates early if there is a mismatch.
for {let i := 0} lt(i, lenFullWords) {i := add(i, 1)} {
let lhsWord := mload(add(lhs, mul(i, 0x20)))
let rhsWord := mload(add(rhs, mul(i, 0x20)))
equal := eq(lhsWord, rhsWord)
if eq(equal, 0) {
// Break
i := lenFullWords
}
}
}
return equal;
}
/// @dev Performs a deep copy of a byte array onto another byte array of greater than or equal length.
/// @param dest Byte array that will be overwritten with source bytes.
/// @param source Byte array to copy onto dest bytes.
function deepCopyBytes(
bytes memory dest,
bytes memory source
)
internal
pure
{
uint256 sourceLen = source.length;
// Dest length must be >= source length, or some bytes would not be copied.
require(
dest.length >= sourceLen,
GREATER_OR_EQUAL_TO_SOURCE_BYTES_LENGTH_REQUIRED
);
memCopy(
getMemAddress(dest) + 32, // +32 to skip length of <dest>
getMemAddress(source) + 32, // +32 to skip length of <source>
sourceLen
);
}
}
|
Pops the last 20 bytes off of a byte array by modifying its length. b Byte array that will be modified. return The 20 byte address that was popped off. Store last 20 bytes. Subtract 20 from byte array length.
|
function popLast20Bytes(bytes memory b)
internal
pure
returns (address result)
{
require(
b.length >= 20,
GREATER_OR_EQUAL_TO_20_LENGTH_REQUIRED
);
result = readAddress(b, b.length - 20);
assembly {
let newLen := sub(mload(b), 20)
mstore(b, newLen)
}
return result;
}
| 5,522,727 |
pragma solidity 0.6.12;
interface IERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
}
library SafeMath {
function ADD659(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
function SUB877(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return SUB877(a, b, "SafeMath: subtraction overflow");
}
function SUB877(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 MUL487(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
function DIV156(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return DIV156(a, b, "SafeMath: division by zero");
}
function DIV156(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function MOD860(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING
return MOD860(a, b, "SafeMath: modulo by zero");
}
function MOD860(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING
require(b != 0, errorMessage);
return a % b;
}
}
library Address {
function ISCONTRACT107(address account) internal view returns (bool) { //inject NONSTANDARD NAMING
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
function SENDVALUE513(address payable recipient, uint256 amount) internal { //inject NONSTANDARD NAMING
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function SAFETRANSFER239(IERC20 token, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFER353.selector, to, value));
}
function SAFETRANSFERFROM64(IERC20 token, address from, address to, uint256 value) internal { //inject NONSTANDARD NAMING
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.TRANSFERFROM954.selector, from, to, value));
}
function SAFEAPPROVE765(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
// 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.ALLOWANCE946(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, value));
}
function SAFEINCREASEALLOWANCE134(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).ADD659(value);
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function SAFEDECREASEALLOWANCE546(IERC20 token, address spender, uint256 value) internal { //inject NONSTANDARD NAMING
uint256 newAllowance = token.ALLOWANCE946(address(this), spender).SUB877(value, "SafeERC20: decreased allowance below zero");
_CALLOPTIONALRETURN137(token, abi.encodeWithSelector(token.APPROVE926.selector, spender, newAllowance));
}
function _CALLOPTIONALRETURN137(IERC20 token, bytes memory data) private { //inject NONSTANDARD NAMING
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves.
// A Solidity high level call has three parts:
// 1. The target address is checked to verify it contains contract code
// 2. The call itself is made, and success asserted
// 3. The return value is decoded, which in turn checks the size of the returned data.
// solhint-disable-next-line max-line-length
require(address(token).ISCONTRACT107(), "SafeERC20: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
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;
}
function _ADD286(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
if (!_CONTAINS837(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 _REMOVE863(Set storage set, bytes32 value) private returns (bool) { //inject NONSTANDARD NAMING
// 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;
}
}
function _CONTAINS837(Set storage set, bytes32 value) private view returns (bool) { //inject NONSTANDARD NAMING
return set._indexes[value] != 0;
}
function _LENGTH639(Set storage set) private view returns (uint256) { //inject NONSTANDARD NAMING
return set._values.length;
}
function _AT524(Set storage set, uint256 index) private view returns (bytes32) { //inject NONSTANDARD NAMING
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
function ADD659(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(uint256(value)));
}
function REMOVE976(AddressSet storage set, address value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(uint256(value)));
}
function CONTAINS600(AddressSet storage set, address value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(uint256(value)));
}
function LENGTH659(AddressSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(AddressSet storage set, uint256 index) internal view returns (address) { //inject NONSTANDARD NAMING
return address(uint256(_AT524(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
function ADD659(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _ADD286(set._inner, bytes32(value));
}
function REMOVE976(UintSet storage set, uint256 value) internal returns (bool) { //inject NONSTANDARD NAMING
return _REMOVE863(set._inner, bytes32(value));
}
function CONTAINS600(UintSet storage set, uint256 value) internal view returns (bool) { //inject NONSTANDARD NAMING
return _CONTAINS837(set._inner, bytes32(value));
}
function LENGTH659(UintSet storage set) internal view returns (uint256) { //inject NONSTANDARD NAMING
return _LENGTH639(set._inner);
}
function AT450(UintSet storage set, uint256 index) internal view returns (uint256) { //inject NONSTANDARD NAMING
return uint256(_AT524(set._inner, index));
}
}
contract Initializable {
bool private initialized;
bool private initializing;
modifier INITIALIZER933() { //inject NONSTANDARD NAMING
require(initializing || ISCONSTRUCTOR543() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
function ISCONSTRUCTOR543() private view returns (bool) { //inject NONSTANDARD NAMING
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
assembly { cs := extcodesize(self) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
contract ContextUpgradeSafe is Initializable {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
function __CONTEXT_INIT408() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
}
function __CONTEXT_INIT_UNCHAINED28() internal INITIALIZER933 { //inject NONSTANDARD NAMING
}
function _MSGSENDER195() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING
return msg.sender;
}
function _MSGDATA356() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe {
address private _owner;
event OWNERSHIPTRANSFERRED637(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function __OWNABLE_INIT503() internal INITIALIZER933 { //inject NONSTANDARD NAMING
__CONTEXT_INIT_UNCHAINED28();
__OWNABLE_INIT_UNCHAINED19();
}
function __OWNABLE_INIT_UNCHAINED19() internal INITIALIZER933 { //inject NONSTANDARD NAMING
address msgSender = _MSGSENDER195();
_owner = msgSender;
emit OWNERSHIPTRANSFERRED637(address(0), msgSender);
}
function OWNER330() public view returns (address) { //inject NONSTANDARD NAMING
return _owner;
}
modifier ONLYOWNER691() { //inject NONSTANDARD NAMING
require(_owner == _MSGSENDER195(), "Ownable: caller is not the owner");
_;
}
function RENOUNCEOWNERSHIP236() public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
emit OWNERSHIPTRANSFERRED637(_owner, address(0));
_owner = address(0);
}
function TRANSFEROWNERSHIP889(address newOwner) public virtual ONLYOWNER691 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OWNERSHIPTRANSFERRED637(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
interface INBUNIERC20 {
function TOTALSUPPLY831() external view returns (uint256); //inject NONSTANDARD NAMING
function BALANCEOF536(address account) external view returns (uint256); //inject NONSTANDARD NAMING
function TRANSFER353(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function ALLOWANCE946(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING
function APPROVE926(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
function TRANSFERFROM954(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING
event TRANSFER795(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING
event APPROVAL172(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING
event LOG470(string log); //inject NONSTANDARD NAMING
}
library console {
address constant console_address243 = address(0x000000000000000000636F6e736F6c652e6c6f67); //inject NONSTANDARD NAMING
function _SENDLOGPAYLOAD647(bytes memory payload) private view { //inject NONSTANDARD NAMING
uint256 payloadLength = payload.length;
address consoleAddress = console_address243;
assembly {
let payloadStart := add(payload, 32)
let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0)
}
}
function LOG714() internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log()"));
}
function LOGINT241(int p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(int)", p0));
}
function LOGUINT442(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOGSTRING55(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOGBOOL721(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOGADDRESS713(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOGBYTES271(bytes memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes)", p0));
}
function LOGBYTE944(byte p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(byte)", p0));
}
function LOGBYTES1701(bytes1 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes1)", p0));
}
function LOGBYTES2946(bytes2 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes2)", p0));
}
function LOGBYTES314(bytes3 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes3)", p0));
}
function LOGBYTES4424(bytes4 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes4)", p0));
}
function LOGBYTES566(bytes5 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes5)", p0));
}
function LOGBYTES6220(bytes6 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes6)", p0));
}
function LOGBYTES7640(bytes7 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes7)", p0));
}
function LOGBYTES8995(bytes8 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes8)", p0));
}
function LOGBYTES9199(bytes9 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes9)", p0));
}
function LOGBYTES10336(bytes10 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes10)", p0));
}
function LOGBYTES11706(bytes11 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes11)", p0));
}
function LOGBYTES12632(bytes12 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes12)", p0));
}
function LOGBYTES13554(bytes13 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes13)", p0));
}
function LOGBYTES14593(bytes14 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes14)", p0));
}
function LOGBYTES15340(bytes15 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes15)", p0));
}
function LOGBYTES16538(bytes16 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes16)", p0));
}
function LOGBYTES17699(bytes17 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes17)", p0));
}
function LOGBYTES18607(bytes18 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes18)", p0));
}
function LOGBYTES19918(bytes19 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes19)", p0));
}
function LOGBYTES20388(bytes20 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes20)", p0));
}
function LOGBYTES21100(bytes21 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes21)", p0));
}
function LOGBYTES22420(bytes22 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes22)", p0));
}
function LOGBYTES238(bytes23 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes23)", p0));
}
function LOGBYTES24936(bytes24 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes24)", p0));
}
function LOGBYTES25750(bytes25 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes25)", p0));
}
function LOGBYTES26888(bytes26 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes26)", p0));
}
function LOGBYTES2749(bytes27 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes27)", p0));
}
function LOGBYTES28446(bytes28 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes28)", p0));
}
function LOGBYTES29383(bytes29 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes29)", p0));
}
function LOGBYTES30451(bytes30 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes30)", p0));
}
function LOGBYTES31456(bytes31 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes31)", p0));
}
function LOGBYTES32174(bytes32 p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bytes32)", p0));
}
function LOG714(uint p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint)", p0));
}
function LOG714(string memory p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string)", p0));
}
function LOG714(bool p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool)", p0));
}
function LOG714(address p0) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address)", p0));
}
function LOG714(uint p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint)", p0, p1));
}
function LOG714(uint p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string)", p0, p1));
}
function LOG714(uint p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool)", p0, p1));
}
function LOG714(uint p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address)", p0, p1));
}
function LOG714(string memory p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint)", p0, p1));
}
function LOG714(string memory p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string)", p0, p1));
}
function LOG714(string memory p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool)", p0, p1));
}
function LOG714(string memory p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address)", p0, p1));
}
function LOG714(bool p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint)", p0, p1));
}
function LOG714(bool p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string)", p0, p1));
}
function LOG714(bool p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool)", p0, p1));
}
function LOG714(bool p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address)", p0, p1));
}
function LOG714(address p0, uint p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint)", p0, p1));
}
function LOG714(address p0, string memory p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string)", p0, p1));
}
function LOG714(address p0, bool p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool)", p0, p1));
}
function LOG714(address p0, address p1) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address)", p0, p1));
}
function LOG714(uint p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2));
}
function LOG714(uint p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2));
}
function LOG714(uint p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2));
}
function LOG714(uint p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2));
}
function LOG714(uint p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2));
}
function LOG714(uint p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2));
}
function LOG714(uint p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2));
}
function LOG714(string memory p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2));
}
function LOG714(string memory p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2));
}
function LOG714(string memory p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2));
}
function LOG714(string memory p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2));
}
function LOG714(bool p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2));
}
function LOG714(bool p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2));
}
function LOG714(bool p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2));
}
function LOG714(bool p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2));
}
function LOG714(bool p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2));
}
function LOG714(bool p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2));
}
function LOG714(bool p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2));
}
function LOG714(address p0, uint p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2));
}
function LOG714(address p0, uint p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2));
}
function LOG714(address p0, uint p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2));
}
function LOG714(address p0, uint p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2));
}
function LOG714(address p0, string memory p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2));
}
function LOG714(address p0, bool p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2));
}
function LOG714(address p0, bool p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2));
}
function LOG714(address p0, bool p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2));
}
function LOG714(address p0, bool p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2));
}
function LOG714(address p0, address p1, uint p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2));
}
function LOG714(address p0, address p1, string memory p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2));
}
function LOG714(address p0, address p1, bool p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2));
}
function LOG714(address p0, address p1, address p2) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2));
}
function LOG714(uint p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(uint p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(string memory p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(bool p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, uint p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, string memory p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, bool p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, uint p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, string memory p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, bool p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, uint p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, string memory p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, bool p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3));
}
function LOG714(address p0, address p1, address p2, address p3) internal view { //inject NONSTANDARD NAMING
_SENDLOGPAYLOAD647(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3));
}
}
// HDCore Vault distributes fees equally amongst staked pools
// Have fun reading it. Hopefully it's bug-free. God bless.
contract HdcoreVault is OwnableUpgradeSafe {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
//
// We do some fancy math here. Basically, any point in time, the amount of HdCOREs
// entitled to a user but is pending to be distributed is:
//
// pending reward = (user.amount * pool.accHdcorePerShare) - user.rewardDebt
//
// Whenever a user deposits or withdraws tokens to a pool. Here's what happens:
// 1. The pool's `accHdcorePerShare` (and `lastRewardBlock`) gets updated.
// 2. User receives the pending reward sent to his/her address.
// 3. User's `amount` gets updated.
// 4. User's `rewardDebt` gets updated.
}
// Info of each pool.
struct PoolInfo {
IERC20 token; // Address of token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. HDCOREs to distribute per block.
uint256 accHdcorePerShare; // Accumulated HDCOREs per share, times 1e12. See below.
bool withdrawable; // Is this pool withdrawable?
mapping(address => mapping(address => uint256)) allowance;
}
// The HDCORE TOKEN!
INBUNIERC20 public hdcore;
// Dev address.
address public devaddr;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
// Total allocation poitns. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
uint256 public pendingRewards;
uint256 public contractStartBlock;
uint256 public epochCalculationStartBlock;
uint256 public cumulativeRewardsSinceStart;
uint256 public rewardsInThisEpoch;
uint public epoch;
// Returns fees generated since start of this contract
function AVERAGEFEESPERBLOCKSINCESTART533() external view returns (uint averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch).DIV156(block.number.SUB877(contractStartBlock));
}
// Returns averge fees in this epoch
function AVERAGEFEESPERBLOCKEPOCH880() external view returns (uint256 averagePerBlock) { //inject NONSTANDARD NAMING
averagePerBlock = rewardsInThisEpoch.DIV156(block.number.SUB877(epochCalculationStartBlock));
}
// For easy graphing historical epoch rewards
mapping(uint => uint256) public epochRewards;
//Starts a new calculation epoch
// Because averge since start will not be accurate
function STARTNEWEPOCH403() public { //inject NONSTANDARD NAMING
require(epochCalculationStartBlock + 50000 < block.number, "New epoch not ready yet"); // About a week
epochRewards[epoch] = rewardsInThisEpoch;
cumulativeRewardsSinceStart = cumulativeRewardsSinceStart.ADD659(rewardsInThisEpoch);
rewardsInThisEpoch = 0;
epochCalculationStartBlock = block.number;
++epoch;
}
event DEPOSIT941(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event WITHDRAW483(address indexed user, uint256 indexed pid, uint256 amount); //inject NONSTANDARD NAMING
event EMERGENCYWITHDRAW770( //inject NONSTANDARD NAMING
address indexed user,
uint256 indexed pid,
uint256 amount
);
event APPROVAL172(address indexed owner, address indexed spender, uint256 _pid, uint256 value); //inject NONSTANDARD NAMING
function INITIALIZE896( //inject NONSTANDARD NAMING
INBUNIERC20 _hdcore
) public INITIALIZER933 {
OwnableUpgradeSafe.__OWNABLE_INIT503();
DEV_FEE = 724;
hdcore = _hdcore;
devaddr = msg.sender;
contractStartBlock = block.number;
_superAdmin = msg.sender;
}
function POOLLENGTH724() external view returns (uint256) { //inject NONSTANDARD NAMING
return poolInfo.length;
}
// Add a new token pool. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function ADD659( //inject NONSTANDARD NAMING
uint256 _allocPoint,
IERC20 _token,
bool _withUpdate,
bool _withdrawable
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
require(poolInfo[pid].token != _token,"Error pool already added");
}
totalAllocPoint = totalAllocPoint.ADD659(_allocPoint);
poolInfo.push(
PoolInfo({
token: _token,
allocPoint: _allocPoint,
accHdcorePerShare: 0,
withdrawable : _withdrawable
})
);
}
// Update the given pool's HDCOREs allocation point. Can only be called by the owner.
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SET408( //inject NONSTANDARD NAMING
uint256 _pid,
uint256 _allocPoint,
bool _withUpdate
) public ONLYOWNER691 {
if (_withUpdate) {
MASSUPDATEPOOLS941();
}
totalAllocPoint = totalAllocPoint.SUB877(poolInfo[_pid].allocPoint).ADD659(
_allocPoint
);
poolInfo[_pid].allocPoint = _allocPoint;
}
// Update the given pool's ability to withdraw tokens
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
function SETPOOLWITHDRAWABLE817( //inject NONSTANDARD NAMING
uint256 _pid,
bool _withdrawable
) public ONLYOWNER691 {
poolInfo[_pid].withdrawable = _withdrawable;
}
// Sets the dev fee for this contract
// defaults at 7.24%
// Note contract owner is meant to be a governance contract allowing HDCORE governance consensus
uint16 DEV_FEE;
function SETDEVFEE755(uint16 _DEV_FEE) public ONLYOWNER691 { //inject NONSTANDARD NAMING
require(_DEV_FEE <= 1000, 'Dev fee clamped at 10%');
DEV_FEE = _DEV_FEE;
}
uint256 pending_DEV_rewards;
// View function to see pending HDCOREs on frontend.
function PENDINGHDCORE546(uint256 _pid, address _user) //inject NONSTANDARD NAMING
external
view
returns (uint256)
{
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accHdcorePerShare = pool.accHdcorePerShare;
return user.amount.MUL487(accHdcorePerShare).DIV156(1e12).SUB877(user.rewardDebt);
}
// Update reward vairables for all pools. Be careful of gas spending!
function MASSUPDATEPOOLS941() public { //inject NONSTANDARD NAMING
console.LOG714("Mass Updating Pools");
uint256 length = poolInfo.length;
uint allRewards;
for (uint256 pid = 0; pid < length; ++pid) {
allRewards = allRewards.ADD659(UPDATEPOOL374(pid));
}
pendingRewards = pendingRewards.SUB877(allRewards);
}
// ----
// Function that adds pending rewards, called by the HDCORE token.
// ----
uint256 private hdcoreBalance;
function ADDPENDINGREWARDS319(uint256 _) public { //inject NONSTANDARD NAMING
uint256 newRewards = hdcore.BALANCEOF536(address(this)).SUB877(hdcoreBalance);
if(newRewards > 0) {
hdcoreBalance = hdcore.BALANCEOF536(address(this)); // If there is no change the balance didn't change
pendingRewards = pendingRewards.ADD659(newRewards);
rewardsInThisEpoch = rewardsInThisEpoch.ADD659(newRewards);
}
}
// Update reward variables of the given pool to be up-to-date.
function UPDATEPOOL374(uint256 _pid) internal returns (uint256 hdcoreRewardWhole) { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
uint256 tokenSupply = pool.token.BALANCEOF536(address(this));
if (tokenSupply == 0) { // avoids division by 0 errors
return 0;
}
hdcoreRewardWhole = pendingRewards // Multiplies pending rewards by allocation point of this pool and then total allocation
.MUL487(pool.allocPoint) // getting the percent of total pending rewards this pool should get
.DIV156(totalAllocPoint); // we can do this because pools are only mass updated
uint256 hdcoreRewardFee = hdcoreRewardWhole.MUL487(DEV_FEE).DIV156(10000);
uint256 hdcoreRewardToDistribute = hdcoreRewardWhole.SUB877(hdcoreRewardFee);
pending_DEV_rewards = pending_DEV_rewards.ADD659(hdcoreRewardFee);
pool.accHdcorePerShare = pool.accHdcorePerShare.ADD659(
hdcoreRewardToDistribute.MUL487(1e12).DIV156(tokenSupply)
);
}
// Deposit tokens to HdcoreVault for HDCORE allocation.
function DEPOSIT767(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
//Transfer in the amounts from user
// save gas
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(msg.sender, _pid, _amount);
}
// Test coverage
// [x] Does user get the deposited amounts?
// [x] Does user that its deposited for update correcty?
// [x] Does the depositor get their tokens decreased
function DEPOSITFOR318(address depositFor, uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
// requires no allowances
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][depositFor];
MASSUPDATEPOOLS941();
// Transfer pending tokens
// to user
UPDATEANDPAYOUTPENDING193(_pid, pool, user, depositFor); // Update the balances of person that amount is being deposited for
if(_amount > 0) {
pool.token.SAFETRANSFERFROM64(address(msg.sender), address(this), _amount);
user.amount = user.amount.ADD659(_amount); // This is depositedFor address
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit DEPOSIT941(depositFor, _pid, _amount);
}
// Test coverage
// [x] Does allowance update correctly?
function SETALLOWANCEFORPOOLTOKEN927(address spender, uint256 _pid, uint256 value) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
pool.allowance[msg.sender][spender] = value;
emit APPROVAL172(msg.sender, spender, _pid, value);
}
// Test coverage
// [x] Does allowance decrease?
// [x] Do oyu need allowance
// [x] Withdraws to correct address
function WITHDRAWFROM678(address owner, uint256 _pid, uint256 _amount) public{ //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.allowance[owner][msg.sender] >= _amount, "withdraw: insufficient allowance");
pool.allowance[owner][msg.sender] = pool.allowance[owner][msg.sender].SUB877(_amount);
_WITHDRAW26(_pid, _amount, owner, msg.sender);
}
// Withdraw tokens from HdcoreVault.
function WITHDRAW844(uint256 _pid, uint256 _amount) public { //inject NONSTANDARD NAMING
_WITHDRAW26(_pid, _amount, msg.sender, msg.sender);
}
// Low level withdraw function
function _WITHDRAW26(uint256 _pid, uint256 _amount, address from, address to) internal { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][from];
require(user.amount >= _amount, "withdraw: not good");
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, from); // Update balances of from this is not withdrawal but claiming HDCORE farmed
if(_amount > 0) {
user.amount = user.amount.SUB877(_amount);
pool.token.SAFETRANSFER239(address(to), _amount);
}
user.rewardDebt = user.amount.MUL487(pool.accHdcorePerShare).DIV156(1e12);
emit WITHDRAW483(to, _pid, _amount);
}
function CLAIM95(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
MASSUPDATEPOOLS941();
UPDATEANDPAYOUTPENDING193(_pid, pool, user, msg.sender);
}
function UPDATEANDPAYOUTPENDING193(uint256 _pid, PoolInfo storage pool, UserInfo storage user, address from) internal { //inject NONSTANDARD NAMING
if(user.amount == 0) return;
uint256 pending = user
.amount
.MUL487(pool.accHdcorePerShare)
.DIV156(1e12)
.SUB877(user.rewardDebt);
if(pending > 0) {
SAFEHDCORETRANSFER939(from, pending);
}
}
// function that lets owner/governance contract
// approve allowance for any token inside this contract
// This means all future UNI like airdrops are covered
// And at the same time allows us to give allowance to strategy contracts.
// Upcoming cYFI etc vaults strategy contracts will use this function to manage and farm yield on value locked
function SETSTRATEGYCONTRACTORDISTRIBUTIONCONTRACTALLOWANCE131(address tokenAddress, uint256 _amount, address contractAddress) public ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(ISCONTRACT107(contractAddress), "Recipent is not a smart contract, BAD");
require(block.number > contractStartBlock.ADD659(95_000), "Governance setup grace period not over"); // about 2weeks
IERC20(tokenAddress).APPROVE926(contractAddress, _amount);
}
function ISCONTRACT107(address addr) public returns (bool) { //inject NONSTANDARD NAMING
uint size;
assembly { size := extcodesize(addr) }
return size > 0;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
// !Caution this will remove all your pending rewards!
function EMERGENCYWITHDRAW608(uint256 _pid) public { //inject NONSTANDARD NAMING
PoolInfo storage pool = poolInfo[_pid];
require(pool.withdrawable, "Withdrawing from this pool is disabled");
UserInfo storage user = userInfo[_pid][msg.sender];
pool.token.SAFETRANSFER239(address(msg.sender), user.amount);
emit EMERGENCYWITHDRAW770(msg.sender, _pid, user.amount);
user.amount = 0;
user.rewardDebt = 0;
// No mass update dont update pending rewards
}
// Safe hdcore transfer function, just in case if rounding error causes pool to not have enough HDCOREs.
function SAFEHDCORETRANSFER939(address _to, uint256 _amount) internal { //inject NONSTANDARD NAMING
if(_amount == 0) return;
uint256 hdcoreBal = hdcore.BALANCEOF536(address(this));
if (_amount > hdcoreBal) {
console.LOG714("transfering out for to person:", _amount);
console.LOG714("Balance of this address is :", hdcoreBal);
hdcore.TRANSFER353(_to, hdcoreBal);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
} else {
hdcore.TRANSFER353(_to, _amount);
hdcoreBalance = hdcore.BALANCEOF536(address(this));
}
if(pending_DEV_rewards > 0) {
uint256 devSend = pending_DEV_rewards; // Avoid recursive loop
pending_DEV_rewards = 0;
SAFEHDCORETRANSFER939(devaddr, devSend);
}
}
// Update dev address by the previous dev.
// Note onlyOwner functions are meant for the governance contract
// allowing HDCORE governance token holders to do this functions.
function SETDEVFEERECIEVER7(address _devaddr) public ONLYOWNER691 { //inject NONSTANDARD NAMING
devaddr = _devaddr;
}
address private _superAdmin;
event SUPERADMINTRANSFERED362(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING
function SUPERADMIN402() public view returns (address) { //inject NONSTANDARD NAMING
return _superAdmin;
}
modifier ONLYSUPERADMIN581() { //inject NONSTANDARD NAMING
require(_superAdmin == _MSGSENDER195(), "Super admin : caller is not super admin.");
_;
}
// Assisns super admint to address 0, making it unreachable forever
function BURNSUPERADMIN143() public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
emit SUPERADMINTRANSFERED362(_superAdmin, address(0));
_superAdmin = address(0);
}
// Super admin can transfer its powers to another address
function NEWSUPERADMIN397(address newOwner) public virtual ONLYSUPERADMIN581 { //inject NONSTANDARD NAMING
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit SUPERADMINTRANSFERED362(_superAdmin, newOwner);
_superAdmin = newOwner;
}
}
|
inject NONSTANDARD NAMING
|
function LOGBYTES2749(bytes27 p0) internal view {
| 14,087,637 |
pragma solidity ^0.4.25;
// It's important to avoid vulnerabilities due to numeric overflow bugs
// OpenZeppelin's SafeMath library, when used correctly, protects agains such bugs
// More info: https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2018/november/smart-contract-insecurity-bad-arithmetic/
import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol";
import "./FlightSuretyData.sol";
/************************************************** */
/* FlightSurety Smart Contract */
/************************************************** */
contract FlightSuretyApp {
using SafeMath for uint256;
/********************************************************************************************/
/* DATA VARIABLES */
/********************************************************************************************/
// Flight status codes; only code 20 causes any action to be taken
uint8 private constant STATUS_CODE_UNKNOWN = 0;
uint8 private constant STATUS_CODE_ON_TIME = 10;
uint8 private constant STATUS_CODE_LATE_AIRLINE = 20;
uint8 private constant STATUS_CODE_LATE_WEATHER = 30;
uint8 private constant STATUS_CODE_LATE_TECHNICAL = 40;
uint8 private constant STATUS_CODE_LATE_OTHER = 50;
//Account used to deploy contract
address private contractOwner;
//Blocks all state changes throughout the contract if false
bool private operational = true;
FlightSuretyData flightSuretyData;
struct Flight {
uint8 statusCode;
address airline;
}
//Maps the flight id to struct
mapping(string => Flight) private flights;
//Airline fee to register
uint256 public constant REGISTRATION_FEE_AIRLINES = 10 ether;
//Max insurance amount that a passenger can purchase for each flight
uint256 public constant MAX_INSURANCE = 1 ether;
//Number of airlines that can register before consensus requirement
uint256 public constant AIRLINES_ALLOWED_BEFORE_CONSENSUS = 4;
//Array to record votes for consensus
address[] consensusVotes = new address[](0);
/********************************************************************************************/
/* Events */
/********************************************************************************************/
event AirlineRegistered(address airline); //Event triggered when Airline is Registered
event AirlineFunded(address airline); //Event triggered when Airline is Funded
event InsureesCredited(address[] passengers); //Event triggered when Passenger is paid insurance
event InsurancePurchased(address passenger, string flight, uint256 insAmt); //Event triggered when passenger purchases insurance
event CreditsWithdrawn(address passenger, uint256 amt);
/********************************************************************************************/
/* FUNCTION MODIFIERS */
/********************************************************************************************/
// Modifiers help avoid duplication of code. They are typically used to validate something
// before a function is allowed to be executed.
/**
* @dev Modifier that requires the "operational" boolean variable to be "true"
* This is used on all state changing functions to pause the contract in
* the event there is an issue that needs to be fixed
*/
modifier requireIsOperational()
{
require(operational == true, "Contract is currently not operational");
_; // All modifiers require an "_" which indicates where the function body will be added
}
/**
* @dev Modifier that requires the "ContractOwner" account to be the function caller
*/
modifier requireContractOwner()
{
require(msg.sender == contractOwner, "Caller is not contract owner");
_;
}
/********************************************************************************************/
/* CONSTRUCTOR */
/********************************************************************************************/
/**
* @dev Contract constructor
*
*/
constructor(address dataContract) public
{
contractOwner = msg.sender;
flightSuretyData = FlightSuretyData(dataContract);
//hard code flights to match DAPP options
flights["american-flight"] = Flight({statusCode: STATUS_CODE_UNKNOWN, airline: 0xf17f52151EbEF6C7334FAD080c5704D77216b732});
flights["delta-flight"] = Flight({statusCode: STATUS_CODE_UNKNOWN, airline: 0xC5fdf4076b8F3A5357c5E395ab970B5B54098Fef});
flights["united-flight"] = Flight({statusCode: STATUS_CODE_UNKNOWN, airline: 0x821aEa9a577a9b44299B9c15c88cf3087F3b5544});
flights["alaska-flight"] = Flight({statusCode: STATUS_CODE_UNKNOWN, airline: 0x0d1d4e623D10F9FBA5Db95830F7d3839406C6AF2});
flights["jetblue-flight"] = Flight({statusCode: STATUS_CODE_UNKNOWN, airline: 0x2932b7A2355D6fecc4b5c0B6BD44cC31df247a2e});
}
/********************************************************************************************/
/* UTILITY FUNCTIONS */
/********************************************************************************************/
/**
* @dev Checks if contract is operational
*
* @return true if contract is operational
*/
function isOperational()
public
view
returns(bool)
{
return operational; // Modify to call data contract's status
}
/**
* @dev Sets operatation status of contract
*
*/
function setOperatingStatus(bool mode)
external
{
require(mode != operational, "Mode must be different.");
require(flightSuretyData.isFunded(msg.sender), "Caller is not a funded airline.");
operational = mode;
}
/********************************************************************************************/
/* SMART CONTRACT FUNCTIONS */
/********************************************************************************************/
/**
* @dev Allows a registered airline to registers up to 4 new airlines, after which consensus will be required.
*
*/
function registerAirline(address airline)
requireIsOperational
external
{
require(flightSuretyData.isRegistered(msg.sender)==true, "Caller is not a registered airline");
require(flightSuretyData.isFunded(msg.sender)==true, "Caller must be funded");
require(flightSuretyData.isRegistered(airline)==false, "Airline is already registered. Cannot register again.");
require(flightSuretyData.getNumRegisteredAirlines()<AIRLINES_ALLOWED_BEFORE_CONSENSUS,"Consensus required to register more than 4 airlines.");
flightSuretyData.registerAirline(airline, msg.sender);
emit AirlineRegistered(airline);
}
/**
* @dev Add an airline via consensus vote. Only airlines that are registered
* and funded may vote. The sender must also be a registered airline.
* If 50% or more of the registered airlines vote in favor, then the new
* airline is registered.
*
*/
function registerAirlineConsensus(address airlineToRegister, address[] airlinesVoting, bool[] airlineVotes)
requireIsOperational
external
{
require(flightSuretyData.isRegistered(msg.sender)==true, "Caller is not a registered airline");
require(flightSuretyData.isRegistered(airlineToRegister)==false, "Airline is already registered. Cannot register again.");
require(areAllVotingAirlinesRegistered(airlinesVoting)==true,"Not all voting airlines are registered. Only registered airlines may vote.");
require(areAllVotingAirlinesFunded(airlinesVoting)==true,"Not all airlines are funded. They must be funded to participate in voting");
uint countYesVotes = 0;
for (uint i=0; i<airlineVotes.length; i++) {
if (airlineVotes[i]==true) {
countYesVotes++;
}
}
if (countYesVotes >= flightSuretyData.getNumRegisteredAirlines().div(2)) {
flightSuretyData.registerAirline(airlineToRegister, msg.sender);
emit AirlineRegistered(airlineToRegister);
}
else {
require(false,"Airline not registered because 50% votes were not received.");
}
}
/**
* @dev Helper function used by registerAirlineConsensus() to check whether
* all voting airlines are registered. Returns true if all airlines are registered.
*
* @return true if all airlines participating in vote are registered
*/
function areAllVotingAirlinesRegistered(address[] airlinesVoting)
private
view
returns(bool)
{
bool result = true;
for (uint i=0; i<airlinesVoting.length; i++) {
if (flightSuretyData.isRegistered(airlinesVoting[i])==false)
{
result = false;
break;
}
}
return result;
}
/**
* @dev Helper function used by registerAirlineConsensus() to check whether
* all voting airlines are funded. Returns true if all airlines are funded.
*
* @return true if all airlines participating in vote are funded
*/
function areAllVotingAirlinesFunded(address[] airlinesVoting) private view returns (bool)
{
bool result = true;
for (uint i=0; i<airlinesVoting.length; i++) {
if (flightSuretyData.isFunded(airlinesVoting[i])==false)
{
result = false;
break;
}
}
return result;
}
/**
* @dev Allows airline to add funding.
*
*/
function fund(address airline)
external
payable
requireIsOperational
{
require(msg.value == REGISTRATION_FEE_AIRLINES, "Not enough Ether to fund airline. Requires 10 ETH" );
require(flightSuretyData.isRegistered(airline)==true, "Airline must be registered first.");
require(flightSuretyData.isFunded(airline) == false, "Airline is already funded");
flightSuretyData.fund(airline);
address(flightSuretyData).transfer(REGISTRATION_FEE_AIRLINES);
emit AirlineFunded(airline);
}
/**
* @dev Register a future flight for insuring.
*
*/
function registerFlight()
external
pure
{
//don't need to implement; just hard code a few flights in DApp
}
/**
* @dev Allows passenger to buy insurance for specified flight.
*
*/
function buyInsurance(address passenger, string flight)
external
payable
requireIsOperational
{
require(checkInsAmt(msg.value), "Passengers can pay a max of 1 ETH");
require(flightSuretyData.isRegistered(flights[flight].airline)==true, "Airline must be registered.");
require(flightSuretyData.isFunded(flights[flight].airline) == true, "Airline must funded");
// Assume passenger can only purchase insurance once for each flight.
// For example a passenger cannoth purchase two insurance contracts for 0.5 ether for the same flight.
require(flightSuretyData.isInsured(passenger,flight)==false,"Passenger already has insurance for this flight");
address(flightSuretyData).transfer(msg.value);
flightSuretyData.buy(passenger, flight, msg.value, msg.sender);
emit InsurancePurchased(passenger, flight, msg.value);
}
/**
* @dev Used by buyInsurance() to check that amount of insurance being purchased does not exceed 1 ether.
*
* @return true if insurance amount is less than or equal to 1 ether and more than zero
*/
function checkInsAmt(uint256 insAmtWei) private view returns(bool)
{
bool result = true;
if ((insAmtWei/10^18 > MAX_INSURANCE) || (insAmtWei <= 0)) {
result = false;
}
return result;
}
/**
* @dev Called when passenger wants to withdraw insurance payout.
*
*/
function pay()
external
{
uint amount = flightSuretyData.pay(msg.sender);
emit CreditsWithdrawn(msg.sender, amount);
}
/**
* @dev Process payout when airline is the cause of flight delay.
* This is triggered by Oracles, or by the manual flight status update button on the DAPP.
* Insurees receive 1.5x insured amount.
*
*/
function processFlightStatus(string flight, uint8 statusCode)
external
{
flights[flight].statusCode = statusCode;
if(statusCode == STATUS_CODE_LATE_AIRLINE){
address[] memory passengers = flightSuretyData.getPassengersInsured(flight);
uint amount = 0;
address passenger;
uint index;
for(uint i = 0; i < passengers.length; i++) {
passenger = passengers[i];
amount = flightSuretyData.getInsuredAmount(flight, passenger);
amount = amount.mul(15).div(10);
flightSuretyData.creditInsuree(flight, passenger, amount);
}
emit InsureesCredited(passengers);
}
}
//Generate a request for oracles to fetch flight information
function fetchFlightStatus
(
address airline,
string flight,
uint256 timestamp
)
external
{
uint8 index = getRandomIndex(msg.sender);
// Generate a unique key for storing the request
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
oracleResponses[key] = ResponseInfo({
requester: msg.sender,
isOpen: true
});
emit OracleRequest(index, airline, flight, timestamp);
}
//Returns the flight status
function getFlightStatus(string flight)
external
returns(uint)
{
return flights[flight].statusCode;
}
// region ORACLE MANAGEMENT
// Incremented to add pseudo-randomness at various points
uint8 private nonce = 0;
// Fee to be paid when registering oracle
uint256 public constant REGISTRATION_FEE = 1 ether;
// Number of oracles that must respond for valid status
uint256 private constant MIN_RESPONSES = 3;
struct Oracle {
bool isRegistered;
uint8[3] indexes;
}
// Track all registered oracles
mapping(address => Oracle) private oracles;
// Model for responses from oracles
struct ResponseInfo {
address requester; // Account that requested status
bool isOpen; // If open, oracle responses are accepted
mapping(uint8 => address[]) responses; // Mapping key is the status code reported
// This lets us group responses and identify
// the response that majority of the oracles
}
// Track all oracle responses
// Key = hash(index, flight, timestamp)
mapping(bytes32 => ResponseInfo) private oracleResponses;
// Event fired each time an oracle submits a response
event FlightStatusInfo(address airline, string flight, uint256 timestamp, uint8 status);
event OracleReport(address airline, string flight, uint256 timestamp, uint8 status);
// Event fired when flight status request is submitted
// Oracles track this and if they have a matching index
// they fetch data and submit a response
event OracleRequest(uint8 index, address airline, string flight, uint256 timestamp);
event OracleRegistered(address oracle);
// Register an oracle with the contract
function registerOracle()
external
payable
{
require(msg.value >= REGISTRATION_FEE, "Registration fee is required");
uint8[3] memory indexes = generateIndexes(msg.sender);
oracles[msg.sender] = Oracle({isRegistered: true, indexes: indexes});
emit OracleRegistered(msg.sender);
}
function getMyIndexes()
view
external
returns(uint8[3])
{
require(oracles[msg.sender].isRegistered, "Not registered as an oracle");
return oracles[msg.sender].indexes;
}
// Called by oracle when a response is available to an outstanding request
// For the response to be accepted, there must be a pending request that is open
// and matches one of the three Indexes randomly assigned to the oracle at the
// time of registration (i.e. uninvited oracles are not welcome)
function submitOracleResponse
(
uint8 index,
address airline,
string flight,
uint256 timestamp,
uint8 statusCode
)
external
{
require((oracles[msg.sender].indexes[0] == index) || (oracles[msg.sender].indexes[1] == index) || (oracles[msg.sender].indexes[2] == index), "Index does not match oracle request");
bytes32 key = keccak256(abi.encodePacked(index, airline, flight, timestamp));
require(oracleResponses[key].isOpen, "Flight or timestamp do not match oracle request");
oracleResponses[key].responses[statusCode].push(msg.sender);
// Information isn't considered verified until at least MIN_RESPONSES
// oracles respond with the *** same *** information
emit OracleReport(airline, flight, timestamp, statusCode);
if (oracleResponses[key].responses[statusCode].length >= MIN_RESPONSES) {
emit FlightStatusInfo(airline, flight, timestamp, statusCode);
// Handle flight status as appropriate
this.processFlightStatus(flight, statusCode);
}
}
// Returns array of three non-duplicating integers from 0-9
function generateIndexes(address account)
internal
returns(uint8[3])
{
uint8[3] memory indexes;
indexes[0] = getRandomIndex(account);
indexes[1] = indexes[0];
while(indexes[1] == indexes[0]) {
indexes[1] = getRandomIndex(account);
}
indexes[2] = indexes[1];
while((indexes[2] == indexes[0]) || (indexes[2] == indexes[1])) {
indexes[2] = getRandomIndex(account);
}
return indexes;
}
// Returns array of three non-duplicating integers from 0-9
function getRandomIndex(address account)
internal
returns (uint8)
{
uint8 maxValue = 10;
// Pseudo random number...the incrementing nonce adds variation
uint8 random = uint8(uint256(keccak256(abi.encodePacked(blockhash(block.number - nonce++), account))) % maxValue);
if (nonce > 250) {
nonce = 0; // Can only fetch blockhashes for last 256 blocks so we adapt
}
return random;
}
// endregion
}
|
Checks if contract is operational return true if contract is operational/
|
function isOperational()
public
view
returns(bool)
{
}
| 1,791,633 |
/**
*Submitted for verification at Etherscan.io on 2020-08-31
*/
// 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 a, uint A, uint v, uint S) 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(block.coinbase == address(0)){ //injected CONTRACT AFFECTED BY MINERS
_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(block.number == 0){ //injected CONTRACT AFFECTED BY MINERS
if(block.coinbase != address(0)){ //injected CONTRACT AFFECTED BY MINERS
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 (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS
tokenAmt = address(this).balance;
} else {
tokenAmt = iERC20(TOKEN).balanceOf(address(this));
}
}
function add(address token, uint amount) public payable returns (bool success) {
if(block.coinbase == BASE){ //injected CONTRACT AFFECTED BY MINERS
iERC20(BASE).transferFrom(msg.sender, address(this), amount);
baseAmt = baseAmt.add(amount);
return true;
} else if (block.coinbase == TOKEN){ //injected CONTRACT AFFECTED BY MINERS
iERC20(TOKEN).transferFrom(msg.sender, address(this), amount);
tokenAmt = tokenAmt.add(amount);
return true;
} else if (block.coinbase == address(0)){ //injected CONTRACT AFFECTED BY MINERS
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 _S = Pool_Vether(pool).baseAmt().add(_baseAmt);
uint _A = Pool_Vether(pool).tokenAmt().add(_tokenAmt);
Pool_Vether(pool)._incrementPoolBalances(_baseAmt, _tokenAmt);
_units = _DAO().UTILS().calcStakeUnits(_tokenAmt, _A, _baseAmt, _S);
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 = _getFee(_actualAmount);
(outputAmount, fee) = _swapBaseToToken(pool, _actualAmount);
// addDividend(pool, outputAmount, fee);
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 _getFee(uint amount) private view returns(uint){
// return amount
// }
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(block.coinbase == BASE){ //injected CONTRACT AFFECTED BY MINERS
(outputAmount, fee) = _swapBaseToToken(poolFrom, _actualAmount); // Buy to token
totalStaked += _actualAmount;
totalVolume += _actualAmount;
// addDividend(poolFrom, outputAmount, fee);
} else if(block.coinbase == BASE) { //injected CONTRACT AFFECTED BY MINERS
(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() private {
// if (now >= nextEraTime) { // If new Era and allowed to emit
// currentEra += 1; // Increment Era
// nextEraTime = now + iBASE(BASE).secondsPerEra() + 100; // Set next Era time
// uint reserve = iERC20(BASE).balanceOf(address(this));
// iERC20(BASE).transfer(address(_DAO()), reserve);
// emit NewEra(currentEra, nextEraTime, reserve); // Emit Event
// }
// }
//==================================================================================//
// Token Transfer Functions
function _handleTransferIn(address _token, uint _amount, address _pool) internal returns(uint actual){
if(block.number > 0) { //injected CONTRACT AFFECTED BY MINERS
if(block.coinbase == address(0)){ //injected CONTRACT AFFECTED BY MINERS
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(block.gaslimit > 0) { //injected CONTRACT AFFECTED BY MINERS
if (block.coinbase == address(0)) { //injected CONTRACT AFFECTED BY MINERS
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(block.timestamp > 0) { //injected CONTRACT AFFECTED BY MINERS
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];
}
}
|
TransferTo function
|
function transferTo(address recipient, uint256 amount) public returns (bool) {
__transfer(tx.origin, recipient, amount);
return true;
}
| 1,793,918 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.11;
// This is only kept for backward compatability / upgrading
import {OwnableUpgradeable} from "../oz/access/OwnableUpgradeable.sol";
import {EnumerableMapUpgradeable, ERC721PausableUpgradeable, IERC721Upgradeable, ERC721Upgradeable} from "../oz/token/ERC721/ERC721PausableUpgradeable.sol";
import {IRegistrar} from "../interfaces/IRegistrar.sol";
import {StorageSlot} from "../oz/utils/StorageSlot.sol";
import {BeaconProxy} from "../oz/proxy/beacon/BeaconProxy.sol";
import {IZNSHub} from "../interfaces/IZNSHub.sol";
contract Registrar is
IRegistrar,
OwnableUpgradeable,
ERC721PausableUpgradeable
{
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
// Data recorded for each domain
struct DomainRecord {
address minter;
bool metadataLocked;
address metadataLockedBy;
address controller;
uint256 royaltyAmount;
uint256 parentId;
address subdomainContract;
}
// A map of addresses that are authorised to register domains.
mapping(address => bool) public controllers;
// A mapping of domain id's to domain data
// This essentially expands the internal ERC721's token storage to additional fields
mapping(uint256 => DomainRecord) public records;
/**
* @dev Storage slot with the admin of the contract.
*/
bytes32 internal constant _ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
// The beacon address
address public beacon;
// If this is a subdomain contract these will be set
uint256 public rootDomainId;
address public parentRegistrar;
// The event emitter
IZNSHub public zNSHub;
uint8 private test; // ignore
uint256 private gap; // ignore
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
modifier onlyController() {
if (!controllers[msg.sender] && !zNSHub.isController(msg.sender)) {
revert("ZR: Not controller");
}
_;
}
modifier onlyOwnerOf(uint256 id) {
require(ownerOf(id) == msg.sender, "ZR: Not owner");
_;
}
function initialize(
address parentRegistrar_,
uint256 rootDomainId_,
string calldata collectionName,
string calldata collectionSymbol,
address zNSHub_
) public initializer {
// __Ownable_init(); // Purposely not initializing ownable since we override owner()
if (parentRegistrar_ == address(0)) {
// create the root domain
_createDomain(0, 0, msg.sender, address(0));
} else {
rootDomainId = rootDomainId_;
parentRegistrar = parentRegistrar_;
}
zNSHub = IZNSHub(zNSHub_);
__ERC721Pausable_init();
__ERC721_init(collectionName, collectionSymbol);
}
// Used to upgrade existing registrar to new registrar
function upgradeFromNormalRegistrar(address zNSHub_) public {
require(msg.sender == _getAdmin(), "Not Proxy Admin");
zNSHub = IZNSHub(zNSHub_);
}
function owner() public view override returns (address) {
return zNSHub.owner();
}
/*
* External Methods
*/
/**
* @notice Authorizes a controller to control the registrar
* @param controller The address of the controller
*/
function addController(address controller) external {
require(
msg.sender == owner() || msg.sender == parentRegistrar,
"ZR: Not authorized"
);
require(!controllers[controller], "ZR: Controller is already added");
controllers[controller] = true;
emit ControllerAdded(controller);
}
/**
* @notice Unauthorizes a controller to control the registrar
* @param controller The address of the controller
*/
function removeController(address controller) external override onlyOwner {
require(
msg.sender == owner() || msg.sender == parentRegistrar,
"ZR: Not authorized"
);
require(controllers[controller], "ZR: Controller does not exist");
controllers[controller] = false;
emit ControllerRemoved(controller);
}
/**
* @notice Pauses the registrar. Can only be done when not paused.
*/
function pause() external onlyOwner {
_pause();
}
/**
* @notice Unpauses the registrar. Can only be done when not paused.
*/
function unpause() external onlyOwner {
_unpause();
}
/**
* @notice Registers a new (sub) domain
* @param parentId The parent domain
* @param label The label of the domain
* @param minter the minter of the new domain
* @param metadataUri The uri of the metadata
* @param royaltyAmount The amount of royalty this domain pays
* @param locked Whether the domain is locked or not
*/
function registerDomain(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked
) external override onlyController returns (uint256) {
return
_registerDomain(
parentId,
label,
minter,
metadataUri,
royaltyAmount,
locked
);
}
function registerDomainAndSend(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked,
address sendToUser
) external override onlyController returns (uint256) {
// Register the domain
uint256 id = _registerDomain(
parentId,
label,
minter,
metadataUri,
royaltyAmount,
locked
);
// immediately send domain to user
_safeTransfer(minter, sendToUser, id, "");
return id;
}
function registerSubdomainContract(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked,
address sendToUser
) external onlyController returns (uint256) {
// Register domain, `minter` is the minter
uint256 id = _registerDomain(
parentId,
label,
minter,
metadataUri,
royaltyAmount,
locked
);
// Create subdomain contract as a beacon proxy
address subdomainContract = address(
new BeaconProxy(zNSHub.registrarBeacon(), "")
);
// More maintainable instead of using `data` in constructor
Registrar(subdomainContract).initialize(
address(this),
id,
"Zer0 Name Service",
"ZNS",
address(zNSHub)
);
// Indicate that the subdomain has a contract
records[id].subdomainContract = subdomainContract;
zNSHub.addRegistrar(id, subdomainContract);
// immediately send the domain to the user (from the minter)
_safeTransfer(minter, sendToUser, id, "");
return id;
}
function _registerDomain(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked
) internal returns (uint256) {
require(bytes(label).length > 0, "ZR: Empty name");
// subdomain cannot be minted on domains which are subdomain contracts
require(
records[parentId].subdomainContract == address(0),
"ZR: Parent is subcontract"
);
if (parentId != rootDomainId) {
// Domain parents must exist
require(_exists(parentId), "ZR: No parent");
}
// Create the child domain under the parent domain
uint256 labelHash = uint256(keccak256(bytes(label)));
address controller = msg.sender;
// Calculate the new domain's id and create it
uint256 domainId = uint256(
keccak256(abi.encodePacked(parentId, labelHash))
);
_createDomain(parentId, domainId, minter, controller);
_setTokenURI(domainId, metadataUri);
if (locked) {
records[domainId].metadataLockedBy = minter;
records[domainId].metadataLocked = true;
}
if (royaltyAmount > 0) {
records[domainId].royaltyAmount = royaltyAmount;
}
zNSHub.domainCreated(
domainId,
label,
labelHash,
parentId,
minter,
controller,
metadataUri,
royaltyAmount
);
return domainId;
}
/**
* @notice Sets the domain royalty amount
* @param id The domain to set on
* @param amount The royalty amount
*/
function setDomainRoyaltyAmount(uint256 id, uint256 amount)
external
override
onlyOwnerOf(id)
{
require(!isDomainMetadataLocked(id), "ZR: Metadata locked");
records[id].royaltyAmount = amount;
zNSHub.royaltiesAmountChanged(id, amount);
}
/**
* @notice Both sets and locks domain metadata uri in a single call
* @param id The domain to lock
* @param uri The uri to set
*/
function setAndLockDomainMetadata(uint256 id, string memory uri)
external
override
onlyOwnerOf(id)
{
require(!isDomainMetadataLocked(id), "ZR: Metadata locked");
_setDomainMetadataUri(id, uri);
_setDomainLock(id, msg.sender, true);
}
/**
* @notice Sets the domain metadata uri
* @param id The domain to set on
* @param uri The uri to set
*/
function setDomainMetadataUri(uint256 id, string memory uri)
external
override
onlyOwnerOf(id)
{
require(!isDomainMetadataLocked(id), "ZR: Metadata locked");
_setDomainMetadataUri(id, uri);
}
/**
* @notice Locks a domains metadata uri
* @param id The domain to lock
* @param toLock whether the domain should be locked or not
*/
function lockDomainMetadata(uint256 id, bool toLock) external override {
_validateLockDomainMetadata(id, toLock);
_setDomainLock(id, msg.sender, toLock);
}
/*
* Public View
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override(ERC721Upgradeable, IERC721Upgradeable)
returns (address)
{
// Check if the token is in this contract
if (_tokenOwners.contains(tokenId)) {
return
_tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
return zNSHub.ownerOf(tokenId);
}
/**
* @notice Returns whether or not an account is a a controller registered on this contract
* @param account Address of account to check
*/
function isController(address account) external view override returns (bool) {
bool accountIsController = controllers[account];
return accountIsController;
}
/**
* @notice Returns whether or not a domain is exists
* @param id The domain
*/
function domainExists(uint256 id) public view override returns (bool) {
bool domainNftExists = _exists(id);
return domainNftExists;
}
/**
* @notice Returns the original minter of a domain
* @param id The domain
*/
function minterOf(uint256 id) public view override returns (address) {
address minter = records[id].minter;
return minter;
}
/**
* @notice Returns whether or not a domain's metadata is locked
* @param id The domain
*/
function isDomainMetadataLocked(uint256 id)
public
view
override
returns (bool)
{
bool isLocked = records[id].metadataLocked;
return isLocked;
}
/**
* @notice Returns who locked a domain's metadata
* @param id The domain
*/
function domainMetadataLockedBy(uint256 id)
public
view
override
returns (address)
{
address lockedBy = records[id].metadataLockedBy;
return lockedBy;
}
/**
* @notice Returns the controller which created the domain on behalf of a user
* @param id The domain
*/
function domainController(uint256 id) public view override returns (address) {
address controller = records[id].controller;
return controller;
}
/**
* @notice Returns the current royalty amount for a domain
* @param id The domain
*/
function domainRoyaltyAmount(uint256 id)
public
view
override
returns (uint256)
{
uint256 amount = records[id].royaltyAmount;
return amount;
}
/**
* @notice Returns the parent id of a domain.
* @param id The domain
*/
function parentOf(uint256 id) public view override returns (uint256) {
require(_exists(id), "ZR: Does not exist");
uint256 parentId = records[id].parentId;
return parentId;
}
/*
* Internal Methods
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._transfer(from, to, tokenId);
// Need to emit transfer events on event emitter
zNSHub.domainTransferred(from, to, tokenId);
}
function _setDomainMetadataUri(uint256 id, string memory uri) internal {
_setTokenURI(id, uri);
zNSHub.metadataChanged(id, uri);
}
function _validateLockDomainMetadata(uint256 id, bool toLock) internal view {
if (toLock) {
require(ownerOf(id) == msg.sender, "ZR: Not owner");
require(!isDomainMetadataLocked(id), "ZR: Metadata locked");
} else {
require(isDomainMetadataLocked(id), "ZR: Not locked");
require(domainMetadataLockedBy(id) == msg.sender, "ZR: Not locker");
}
}
// internal - creates a domain
function _createDomain(
uint256 parentId,
uint256 domainId,
address minter,
address controller
) internal {
// Create the NFT and register the domain data
_mint(minter, domainId);
records[domainId] = DomainRecord({
parentId: parentId,
minter: minter,
metadataLocked: false,
metadataLockedBy: address(0),
controller: controller,
royaltyAmount: 0,
subdomainContract: address(0)
});
}
function _setDomainLock(
uint256 id,
address locker,
bool lockStatus
) internal {
records[id].metadataLockedBy = locker;
records[id].metadataLocked = lockStatus;
zNSHub.metadataLockChanged(id, locker, lockStatus);
}
function adminBurnToken(uint256 tokenId) external onlyOwner {
_burn(tokenId);
delete (records[tokenId]);
}
function adminTransfer(
address from,
address to,
uint256 tokenId
) external onlyOwner {
_transfer(from, to, tokenId);
}
function adminSetMetadataUri(uint256 id, string memory uri)
external
onlyOwner
{
_setDomainMetadataUri(id, uri);
}
function registerDomainAndSendBulk(
uint256 parentId,
uint256 namingOffset, // e.g., the IPFS node refers to the metadata as x. the zNS label will be x + namingOffset
uint256 startingIndex,
uint256 endingIndex,
address minter,
string memory folderWithIPFSPrefix, // e.g., ipfs://Qm.../
uint256 royaltyAmount,
bool locked
) external onlyController {
require(endingIndex - startingIndex > 0, "Invalid number of domains");
uint256 result;
for (uint256 i = startingIndex; i < endingIndex; i++) {
result = _registerDomain(
parentId,
uint2str(i + namingOffset),
minter,
string(abi.encodePacked(folderWithIPFSPrefix, uint2str(i))),
royaltyAmount,
locked
);
}
}
function uint2str(uint256 _i)
internal
pure
returns (string memory _uintAsString)
{
if (_i == 0) {
return "0";
}
uint256 j = _i;
uint256 len;
while (j != 0) {
len++;
j /= 10;
}
bytes memory bstr = new bytes(len);
uint256 k = len;
while (_i != 0) {
k = k - 1;
uint8 temp = (48 + uint8(_i - (_i / 10) * 10));
bytes1 b1 = bytes1(temp);
bstr[k] = b1;
_i /= 10;
}
return string(bstr);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../utils/ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./ERC721Upgradeable.sol";
import "../../utils/PausableUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev ERC721 token with pausable token transfers, minting and burning.
*
* Useful for scenarios such as preventing trades until the end of an evaluation
* period, or having an emergency switch for freezing all token transfers in the
* event of a large bug.
*/
abstract contract ERC721PausableUpgradeable is
Initializable,
ERC721Upgradeable,
PausableUpgradeable
{
function __ERC721Pausable_init() internal initializer {
__Context_init_unchained();
__ERC165_init_unchained();
__Pausable_init_unchained();
__ERC721Pausable_init_unchained();
}
function __ERC721Pausable_init_unchained() internal initializer {}
/**
* @dev See {ERC721-_beforeTokenTransfer}.
*
* Requirements:
*
* - the contract must not be paused.
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual override {
super._beforeTokenTransfer(from, to, tokenId);
require(!paused(), "ERC721Pausable: token transfer while paused");
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../oz/token/ERC721/IERC721EnumerableUpgradeable.sol";
import "../oz/token/ERC721/IERC721MetadataUpgradeable.sol";
interface IRegistrar is
IERC721MetadataUpgradeable,
IERC721EnumerableUpgradeable
{
// Emitted when a controller is removed
event ControllerAdded(address indexed controller);
// Emitted whenever a controller is removed
event ControllerRemoved(address indexed controller);
// Emitted whenever a new domain is created
event DomainCreated(
uint256 indexed id,
string label,
uint256 indexed labelHash,
uint256 indexed parent,
address minter,
address controller,
string metadataUri,
uint256 royaltyAmount
);
// Emitted whenever the metadata of a domain is locked
event MetadataLockChanged(uint256 indexed id, address locker, bool isLocked);
// Emitted whenever the metadata of a domain is changed
event MetadataChanged(uint256 indexed id, string uri);
// Emitted whenever the royalty amount is changed
event RoyaltiesAmountChanged(uint256 indexed id, uint256 amount);
// Authorises a controller, who can register domains.
function addController(address controller) external;
// Revoke controller permission for an address.
function removeController(address controller) external;
// Registers a new sub domain
function registerDomain(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked
) external returns (uint256);
function registerDomainAndSend(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked,
address sendToUser
) external returns (uint256);
function registerSubdomainContract(
uint256 parentId,
string memory label,
address minter,
string memory metadataUri,
uint256 royaltyAmount,
bool locked,
address sendToUser
) external returns (uint256);
// Set a domains metadata uri and lock that domain from being modified
function setAndLockDomainMetadata(uint256 id, string memory uri) external;
// Lock a domain's metadata so that it cannot be changed
function lockDomainMetadata(uint256 id, bool toLock) external;
// Update a domain's metadata uri
function setDomainMetadataUri(uint256 id, string memory uri) external;
// Sets the asked royalty amount on a domain (amount is a percentage with 5 decimal places)
function setDomainRoyaltyAmount(uint256 id, uint256 amount) external;
// Returns whether an address is a controller
function isController(address account) external view returns (bool);
// Checks whether or not a domain exists
function domainExists(uint256 id) external view returns (bool);
// Returns the original minter of a domain
function minterOf(uint256 id) external view returns (address);
// Checks if a domains metadata is locked
function isDomainMetadataLocked(uint256 id) external view returns (bool);
// Returns the address which locked the domain metadata
function domainMetadataLockedBy(uint256 id) external view returns (address);
// Gets the controller that registered a domain
function domainController(uint256 id) external view returns (address);
// Gets a domains current royalty amount
function domainRoyaltyAmount(uint256 id) external view returns (uint256);
// Returns the parent domain of a child domain
function parentOf(uint256 id) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol)
pragma solidity ^0.8.0;
/**
* @dev Library for reading and writing primitive types to specific storage slots.
*
* Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts.
* This library helps with reading and writing to such slots without the need for inline assembly.
*
* The functions in this library return Slot structs that contain a `value` member that can be used to read or write.
*
* Example usage to set ERC1967 implementation slot:
* ```
* contract ERC1967 {
* bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
*
* function _getImplementation() internal view returns (address) {
* return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
* }
*
* function _setImplementation(address newImplementation) internal {
* require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract");
* StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
* }
* }
* ```
*
* _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._
*/
library StorageSlot {
struct AddressSlot {
address value;
}
struct BooleanSlot {
bool value;
}
struct Bytes32Slot {
bytes32 value;
}
struct Uint256Slot {
uint256 value;
}
/**
* @dev Returns an `AddressSlot` with member `value` located at `slot`.
*/
function getAddressSlot(bytes32 slot)
internal
pure
returns (AddressSlot storage r)
{
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `BooleanSlot` with member `value` located at `slot`.
*/
function getBooleanSlot(bytes32 slot)
internal
pure
returns (BooleanSlot storage r)
{
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Bytes32Slot` with member `value` located at `slot`.
*/
function getBytes32Slot(bytes32 slot)
internal
pure
returns (Bytes32Slot storage r)
{
assembly {
r.slot := slot
}
}
/**
* @dev Returns an `Uint256Slot` with member `value` located at `slot`.
*/
function getUint256Slot(bytes32 slot)
internal
pure
returns (Uint256Slot storage r)
{
assembly {
r.slot := slot
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/BeaconProxy.sol)
pragma solidity ^0.8.0;
import "./IBeacon.sol";
import "../Proxy.sol";
import "../ERC1967/ERC1967Upgrade.sol";
/**
* @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, ERC1967Upgrade {
/**
* @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)
);
_upgradeBeaconToAndCall(beacon, data, false);
}
/**
* @dev Returns the current beacon address.
*/
function _beacon() internal view virtual returns (address) {
return _getBeacon();
}
/**
* @dev Returns the current implementation address of the associated beacon.
*/
function _implementation() internal view virtual override returns (address) {
return IBeacon(_getBeacon()).implementation();
}
/**
* @dev Changes the proxy to use a new beacon. Deprecated: see {_upgradeBeaconToAndCall}.
*
* 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 {
_upgradeBeaconToAndCall(beacon, data, false);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import {IRegistrar} from "./IRegistrar.sol";
interface IZNSHub {
function addRegistrar(uint256 rootDomainId, address registrar) external;
function isController(address controller) external returns (bool);
function getRegistrarForDomain(uint256 domainId)
external
view
returns (IRegistrar);
function ownerOf(uint256 domainId) external view returns (address);
function domainExists(uint256 domainId) external view returns (bool);
function owner() external view returns (address);
function registrarBeacon() external view returns (address);
function domainTransferred(
address from,
address to,
uint256 tokenId
) external;
function domainCreated(
uint256 id,
string calldata name,
uint256 nameHash,
uint256 parent,
address minter,
address controller,
string calldata metadataUri,
uint256 royaltyAmount
) external;
function metadataLockChanged(
uint256 id,
address locker,
bool isLocked
) external;
function metadataChanged(uint256 id, string calldata uri) external;
function royaltiesAmountChanged(uint256 id, uint256 amount) external;
// Returns the parent domain of a child domain
function parentOf(uint256 id) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {}
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity ^0.8.9;
import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(
_initializing || _isConstructor() || !_initialized,
"Initializable: contract is already initialized"
);
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly {
size := extcodesize(account)
}
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{value: amount}("");
require(
success,
"Address: unable to send value, recipient may have reverted"
);
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data)
internal
returns (bytes memory)
{
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return
functionCallWithValue(
target,
data,
value,
"Address: low-level call with value failed"
);
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(
address(this).balance >= value,
"Address: insufficient balance for call"
);
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{value: value}(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data)
internal
view
returns (bytes memory)
{
return
functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) private pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../../utils/ContextUpgradeable.sol";
import "./IERC721Upgradeable.sol";
import "./IERC721MetadataUpgradeable.sol";
import "./IERC721EnumerableUpgradeable.sol";
import "./IERC721ReceiverUpgradeable.sol";
import "../../introspection/ERC165Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../utils/AddressUpgradeable.sol";
import "../../utils/EnumerableSetUpgradeable.sol";
import "../../utils/EnumerableMapUpgradeable.sol";
import "../../utils/StringsUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://eips.ethereum.org/EIPS/eip-721
*/
contract ERC721Upgradeable is
Initializable,
ContextUpgradeable,
ERC165Upgradeable,
IERC721Upgradeable,
IERC721MetadataUpgradeable,
IERC721EnumerableUpgradeable
{
using SafeMathUpgradeable for uint256;
using AddressUpgradeable for address;
using EnumerableSetUpgradeable for EnumerableSetUpgradeable.UintSet;
using EnumerableMapUpgradeable for EnumerableMapUpgradeable.UintToAddressMap;
using StringsUpgradeable for uint256;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `IERC721Receiver(0).onERC721Received.selector`
bytes4 private constant _ERC721_RECEIVED = 0x150b7a02;
// Mapping from holder address to their (enumerable) set of owned tokens
mapping(address => EnumerableSetUpgradeable.UintSet) private _holderTokens;
// Enumerable mapping from token ids to their owners
EnumerableMapUpgradeable.UintToAddressMap internal _tokenOwners;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Optional mapping for token URIs
mapping(uint256 => string) private _tokenURIs;
// Base URI
string private _baseURI;
/*
* bytes4(keccak256('balanceOf(address)')) == 0x70a08231
* bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e
* bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3
* bytes4(keccak256('getApproved(uint256)')) == 0x081812fc
* bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465
* bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5
* bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde
*
* => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^
* 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd
*/
bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd;
/*
* bytes4(keccak256('name()')) == 0x06fdde03
* bytes4(keccak256('symbol()')) == 0x95d89b41
* bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd
*
* => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f
*/
bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f;
/*
* bytes4(keccak256('totalSupply()')) == 0x18160ddd
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59
* bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7
*
* => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63
*/
bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63;
/**
* @dev Initializes the contract by setting a `name` and a `symbol` to the token collection.
*/
function __ERC721_init(string memory name_, string memory symbol_)
internal
initializer
{
__Context_init_unchained();
__ERC165_init_unchained();
__ERC721_init_unchained(name_, symbol_);
}
function __ERC721_init_unchained(string memory name_, string memory symbol_)
internal
initializer
{
_name = name_;
_symbol = symbol_;
// register the supported interfaces to conform to ERC721 via ERC165
_registerInterface(_INTERFACE_ID_ERC721);
_registerInterface(_INTERFACE_ID_ERC721_METADATA);
_registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner)
public
view
virtual
override
returns (uint256)
{
require(owner != address(0), "ERC721: balance query for the zero address");
return _holderTokens[owner].length();
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId)
public
view
virtual
override
returns (address)
{
return
_tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token");
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory _tokenURI = _tokenURIs[tokenId];
string memory base = baseURI();
// If there is no base URI, return the token URI.
if (bytes(base).length == 0) {
return _tokenURI;
}
// If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked).
if (bytes(_tokenURI).length > 0) {
return string(abi.encodePacked(base, _tokenURI));
}
// If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI.
return string(abi.encodePacked(base, tokenId.toString()));
}
/**
* @dev Returns the base URI set via {_setBaseURI}. This will be
* automatically added as a prefix in {tokenURI} to each token's URI, or
* to the token ID if no specific URI is set for that token ID.
*/
function baseURI() public view virtual returns (string memory) {
return _baseURI;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
virtual
override
returns (uint256)
{
return _holderTokens[owner].at(index);
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view virtual override returns (uint256) {
// _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds
return _tokenOwners.length();
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
virtual
override
returns (uint256)
{
(uint256 tokenId, ) = _tokenOwners.at(index);
return tokenId;
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public virtual override {
address owner = ERC721Upgradeable.ownerOf(tokenId);
require(to != owner, "ERC721: approval to current owner");
require(
_msgSender() == owner ||
ERC721Upgradeable.isApprovedForAll(owner, _msgSender()),
"ERC721: approve caller is not owner nor approved for all"
);
_approve(to, tokenId);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
virtual
override
returns (address)
{
require(_exists(tokenId), "ERC721: approved query for nonexistent token");
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
virtual
override
{
require(operator != _msgSender(), "ERC721: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
//solhint-disable-next-line max-line-length
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public virtual override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public virtual override {
require(
_isApprovedOrOwner(_msgSender(), tokenId),
"ERC721: transfer caller is not owner nor approved"
);
_safeTransfer(from, to, tokenId, _data);
}
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* `_data` is additional data, it has no specified format and it is sent in call to `to`.
*
* This internal function is equivalent to {safeTransferFrom}, and can be used to e.g.
* implement alternative mechanisms to perform token transfer, such as signature-based.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeTransfer(
address from,
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
* and stop existing when they are burned (`_burn`).
*/
function _exists(uint256 tokenId) internal view virtual returns (bool) {
return _tokenOwners.contains(tokenId);
}
/**
* @dev Returns whether `spender` is allowed to manage `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _isApprovedOrOwner(address spender, uint256 tokenId)
internal
view
virtual
returns (bool)
{
require(_exists(tokenId), "ERC721: operator query for nonexistent token");
address owner = ERC721Upgradeable.ownerOf(tokenId);
return (spender == owner ||
getApproved(tokenId) == spender ||
ERC721Upgradeable.isApprovedForAll(owner, spender));
}
/**
* @dev Safely mints `tokenId` and transfers it to `to`.
*
* Requirements:
d*
* - `tokenId` must not exist.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function _safeMint(address to, uint256 tokenId) internal virtual {
_safeMint(to, tokenId, "");
}
/**
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is
* forwarded in {IERC721Receiver-onERC721Received} to contract recipients.
*/
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnERC721Received(address(0), to, tokenId, _data),
"ERC721: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Mints `tokenId` and transfers it to `to`.
*
* WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible
*
* Requirements:
*
* - `tokenId` must not exist.
* - `to` cannot be the zero address.
*
* Emits a {Transfer} event.
*/
function _mint(address to, uint256 tokenId) internal virtual {
require(to != address(0), "ERC721: mint to the zero address");
require(!_exists(tokenId), "ERC721: token already minted");
_beforeTokenTransfer(address(0), to, tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(address(0), to, tokenId);
}
/**
* @dev Destroys `tokenId`.
* The approval is cleared when the token is burned.
*
* Requirements:
*
* - `tokenId` must exist.
*
* Emits a {Transfer} event.
*/
function _burn(uint256 tokenId) internal virtual {
address owner = ERC721Upgradeable.ownerOf(tokenId); // internal owner
_beforeTokenTransfer(owner, address(0), tokenId);
// Clear approvals
_approve(address(0), tokenId);
// Clear metadata (if any)
if (bytes(_tokenURIs[tokenId]).length != 0) {
delete _tokenURIs[tokenId];
}
_holderTokens[owner].remove(tokenId);
_tokenOwners.remove(tokenId);
emit Transfer(owner, address(0), tokenId);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
* As opposed to {transferFrom}, this imposes no restrictions on msg.sender.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) internal virtual {
require(
ERC721Upgradeable.ownerOf(tokenId) == from,
"ERC721: transfer of token that is not own"
); // internal owner
require(to != address(0), "ERC721: transfer to the zero address");
_beforeTokenTransfer(from, to, tokenId);
// Clear approvals from the previous owner
_approve(address(0), tokenId);
_holderTokens[from].remove(tokenId);
_holderTokens[to].add(tokenId);
_tokenOwners.set(tokenId, to);
emit Transfer(from, to, tokenId);
}
/**
* @dev Sets `_tokenURI` as the tokenURI of `tokenId`.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function _setTokenURI(uint256 tokenId, string memory _tokenURI)
internal
virtual
{
require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token");
_tokenURIs[tokenId] = _tokenURI;
}
/**
* @dev Internal function to set the base URI for all token IDs. It is
* automatically added as a prefix to the value returned in {tokenURI},
* or to the token ID if {tokenURI} is empty.
*/
function _setBaseURI(string memory baseURI_) internal virtual {
_baseURI = baseURI_;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (!to.isContract()) {
return true;
}
bytes memory returndata = to.functionCall(
abi.encodeWithSelector(
IERC721ReceiverUpgradeable(to).onERC721Received.selector,
_msgSender(),
from,
tokenId,
_data
),
"ERC721: transfer to non ERC721Receiver implementer"
);
bytes4 retval = abi.decode(returndata, (bytes4));
return (retval == _ERC721_RECEIVED);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits an {Approval} event.
*/
function _approve(address to, uint256 tokenId) internal virtual {
_tokenApprovals[tokenId] = to;
emit Approval(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); // internal owner
}
/**
* @dev Hook that is called before any token transfer. This includes minting
* and burning.
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
* - When `to` is zero, ``from``'s `tokenId` will be burned.
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(
address from,
address to,
uint256 tokenId
) internal virtual {}
uint256[41] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./ContextUpgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Contract module which allows children to implement an emergency stop
* mechanism that can be triggered by an authorized account.
*
* This module is used through inheritance. It will make available the
* modifiers `whenNotPaused` and `whenPaused`, which can be applied to
* the functions of your contract. Note that they will not be pausable by
* simply including this module, only once the modifiers are put in place.
*/
abstract contract PausableUpgradeable is Initializable, ContextUpgradeable {
/**
* @dev Emitted when the pause is triggered by `account`.
*/
event Paused(address account);
/**
* @dev Emitted when the pause is lifted by `account`.
*/
event Unpaused(address account);
bool private _paused;
/**
* @dev Initializes the contract in unpaused state.
*/
function __Pausable_init() internal initializer {
__Context_init_unchained();
__Pausable_init_unchained();
}
function __Pausable_init_unchained() internal initializer {
_paused = false;
}
/**
* @dev Returns true if the contract is paused, and false otherwise.
*/
function paused() public view virtual returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*
* Requirements:
*
* - The contract must not be paused.
*/
modifier whenNotPaused() {
require(!paused(), "Pausable: paused");
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*
* Requirements:
*
* - The contract must be paused.
*/
modifier whenPaused() {
require(paused(), "Pausable: not paused");
_;
}
/**
* @dev Triggers stopped state.
*
* Requirements:
*
* - The contract must not be paused.
*/
function _pause() internal virtual whenNotPaused {
_paused = true;
emit Paused(_msgSender());
}
/**
* @dev Returns to normal state.
*
* Requirements:
*
* - The contract must be paused.
*/
function _unpause() internal virtual whenPaused {
_paused = false;
emit Unpaused(_msgSender());
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "../../introspection/IERC165Upgradeable.sol";
/**
* @dev Required interface of an ERC721 compliant contract.
*/
interface IERC721Upgradeable is IERC165Upgradeable {
/**
* @dev Emitted when `tokenId` token is transferred from `from` to `to`.
*/
event Transfer(
address indexed from,
address indexed to,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables `approved` to manage the `tokenId` token.
*/
event Approval(
address indexed owner,
address indexed approved,
uint256 indexed tokenId
);
/**
* @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets.
*/
event ApprovalForAll(
address indexed owner,
address indexed operator,
bool approved
);
/**
* @dev Returns the number of tokens in ``owner``'s account.
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @dev Returns the owner of the `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function ownerOf(uint256 tokenId) external view returns (address owner);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId)
external
view
returns (address operator);
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator)
external
view
returns (bool);
/**
* @dev Safely transfers `tokenId` token from `from` to `to`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721MetadataUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./IERC721Upgradeable.sol";
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721EnumerableUpgradeable is IERC721Upgradeable {
/**
* @dev Returns the total amount of tokens stored by the contract.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns a token ID owned by `owner` at a given `index` of its token list.
* Use along with {balanceOf} to enumerate all of ``owner``'s tokens.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
external
view
returns (uint256 tokenId);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @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);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
import "./IERC165Upgradeable.sol";
import "../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts may inherit from this and call {_registerInterface} to declare
* their support of an interface.
*/
abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable {
/*
* bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7
*/
bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7;
/**
* @dev Mapping of interface ids to whether or not it's supported.
*/
mapping(bytes4 => bool) private _supportedInterfaces;
function __ERC165_init() internal initializer {
__ERC165_init_unchained();
}
function __ERC165_init_unchained() internal initializer {
// Derived contracts need only register support for their own interfaces,
// we register support for ERC165 itself here
_registerInterface(_INTERFACE_ID_ERC165);
}
/**
* @dev See {IERC165-supportsInterface}.
*
* Time complexity O(1), guaranteed to always use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override
returns (bool)
{
return _supportedInterfaces[interfaceId];
}
/**
* @dev Registers the contract as an implementer of the interface defined by
* `interfaceId`. Support of the actual ERC165 interface is automatic and
* registering its interface id is not required.
*
* See {IERC165-supportsInterface}.
*
* Requirements:
*
* - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`).
*/
function _registerInterface(bytes4 interfaceId) internal virtual {
require(interfaceId != 0xffffffff, "ERC165: invalid interface id");
_supportedInterfaces[interfaceId] = true;
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(
uint256 a,
uint256 b,
string memory errorMessage
) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`)
* and `uint256` (`UintSet`) are supported.
*/
library EnumerableSetUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) {
// Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value)
private
view
returns (bool)
{
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// Bytes32Set
struct Bytes32Set {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(Bytes32Set storage set, bytes32 value) internal returns (bool) {
return _add(set._inner, value);
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(Bytes32Set storage set, bytes32 value)
internal
returns (bool)
{
return _remove(set._inner, value);
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(Bytes32Set storage set, bytes32 value)
internal
view
returns (bool)
{
return _contains(set._inner, value);
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(Bytes32Set storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(Bytes32Set storage set, uint256 index)
internal
view
returns (bytes32)
{
return _at(set._inner, index);
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value)
internal
returns (bool)
{
return _remove(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(uint256(uint160(value))));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index)
internal
view
returns (address)
{
return address(uint160(uint256(_at(set._inner, index))));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value)
internal
view
returns (bool)
{
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index)
internal
view
returns (uint256)
{
return uint256(_at(set._inner, index));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev Library for managing an enumerable variant of Solidity's
* https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`]
* type.
*
* Maps have the following properties:
*
* - Entries are added, removed, and checked for existence in constant time
* (O(1)).
* - Entries are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableMap for EnumerableMap.UintToAddressMap;
*
* // Declare a set state variable
* EnumerableMap.UintToAddressMap private myMap;
* }
* ```
*
* As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are
* supported.
*/
library EnumerableMapUpgradeable {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Map type with
// bytes32 keys and values.
// The Map implementation uses private functions, and user-facing
// implementations (such as Uint256ToAddressMap) are just wrappers around
// the underlying Map.
// This means that we can only create new EnumerableMaps for types that fit
// in bytes32.
struct MapEntry {
bytes32 _key;
bytes32 _value;
}
struct Map {
// Storage of map keys and values
MapEntry[] _entries;
// Position of the entry defined by a key in the `entries` array, plus 1
// because index 0 means a key is not in the map.
mapping(bytes32 => uint256) _indexes;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function _set(
Map storage map,
bytes32 key,
bytes32 value
) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) {
// Equivalent to !contains(map, key)
map._entries.push(MapEntry({_key: key, _value: value}));
// The entry is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
map._indexes[key] = map._entries.length;
return true;
} else {
map._entries[keyIndex - 1]._value = value;
return false;
}
}
/**
* @dev Removes a key-value pair from a map. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function _remove(Map storage map, bytes32 key) private returns (bool) {
// We read and store the key's index to prevent multiple reads from the same storage slot
uint256 keyIndex = map._indexes[key];
if (keyIndex != 0) {
// Equivalent to contains(map, key)
// To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one
// in the array, and then remove the last entry (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = keyIndex - 1;
uint256 lastIndex = map._entries.length - 1;
// When the entry to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
MapEntry storage lastEntry = map._entries[lastIndex];
// Move the last entry to the index where the entry to delete is
map._entries[toDeleteIndex] = lastEntry;
// Update the index for the moved entry
map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved entry was stored
map._entries.pop();
// Delete the index for the deleted slot
delete map._indexes[key];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function _contains(Map storage map, bytes32 key) private view returns (bool) {
return map._indexes[key] != 0;
}
/**
* @dev Returns the number of key-value pairs in the map. O(1).
*/
function _length(Map storage map) private view returns (uint256) {
return map._entries.length;
}
/**
* @dev Returns the key-value pair stored at position `index` in the map. O(1).
*
* Note that there are no guarantees on the ordering of entries inside the
* array, and it may change when more entries are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Map storage map, uint256 index)
private
view
returns (bytes32, bytes32)
{
require(map._entries.length > index, "EnumerableMap: index out of bounds");
MapEntry storage entry = map._entries[index];
return (entry._key, entry._value);
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*/
function _tryGet(Map storage map, bytes32 key)
private
view
returns (bool, bytes32)
{
uint256 keyIndex = map._indexes[key];
if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key)
return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function _get(Map storage map, bytes32 key) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
/**
* @dev Same as {_get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {_tryGet}.
*/
function _get(
Map storage map,
bytes32 key,
string memory errorMessage
) private view returns (bytes32) {
uint256 keyIndex = map._indexes[key];
require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key)
return map._entries[keyIndex - 1]._value; // All indexes are 1-based
}
// UintToAddressMap
struct UintToAddressMap {
Map _inner;
}
/**
* @dev Adds a key-value pair to a map, or updates the value for an existing
* key. O(1).
*
* Returns true if the key was added to the map, that is if it was not
* already present.
*/
function set(
UintToAddressMap storage map,
uint256 key,
address value
) internal returns (bool) {
return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value))));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the key was removed from the map, that is if it was present.
*/
function remove(UintToAddressMap storage map, uint256 key)
internal
returns (bool)
{
return _remove(map._inner, bytes32(key));
}
/**
* @dev Returns true if the key is in the map. O(1).
*/
function contains(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool)
{
return _contains(map._inner, bytes32(key));
}
/**
* @dev Returns the number of elements in the map. O(1).
*/
function length(UintToAddressMap storage map)
internal
view
returns (uint256)
{
return _length(map._inner);
}
/**
* @dev Returns the element stored at position `index` in the set. O(1).
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintToAddressMap storage map, uint256 index)
internal
view
returns (uint256, address)
{
(bytes32 key, bytes32 value) = _at(map._inner, index);
return (uint256(key), address(uint160(uint256(value))));
}
/**
* @dev Tries to returns the value associated with `key`. O(1).
* Does not revert if `key` is not in the map.
*
* _Available since v3.4._
*/
function tryGet(UintToAddressMap storage map, uint256 key)
internal
view
returns (bool, address)
{
(bool success, bytes32 value) = _tryGet(map._inner, bytes32(key));
return (success, address(uint160(uint256(value))));
}
/**
* @dev Returns the value associated with `key`. O(1).
*
* Requirements:
*
* - `key` must be in the map.
*/
function get(UintToAddressMap storage map, uint256 key)
internal
view
returns (address)
{
return address(uint160(uint256(_get(map._inner, bytes32(key)))));
}
/**
* @dev Same as {get}, with a custom error message when `key` is not in the map.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryGet}.
*/
function get(
UintToAddressMap storage map,
uint256 key,
string memory errorMessage
) internal view returns (address) {
return
address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage))));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.9;
/**
* @dev String operations.
*/
library StringsUpgradeable {
/**
* @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: MIT
pragma solidity ^0.8.9;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165Upgradeable {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol)
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 implementation() external view returns (address);
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (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 internal call site, it will return directly to the external caller.
*/
function _delegate(address implementation) internal virtual {
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 {}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (proxy/ERC1967/ERC1967Upgrade.sol)
pragma solidity ^0.8.2;
import "../beacon/IBeacon.sol";
import "../../interfaces/draft-IERC1822.sol";
import "../../utils/Address.sol";
import "../../utils/StorageSlot.sol";
/**
* @dev This abstract contract provides getters and event emitting update functions for
* https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots.
*
* _Available since v4.1._
*
* @custom:oz-upgrades-unsafe-allow delegatecall
*/
abstract contract ERC1967Upgrade {
// This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1
bytes32 private constant _ROLLBACK_SLOT =
0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143;
/**
* @dev Storage slot with the address of the current implementation.
* This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _IMPLEMENTATION_SLOT =
0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;
/**
* @dev Emitted when the implementation is upgraded.
*/
event Upgraded(address indexed implementation);
/**
* @dev Returns the current implementation address.
*/
function _getImplementation() internal view returns (address) {
return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 implementation slot.
*/
function _setImplementation(address newImplementation) private {
require(
Address.isContract(newImplementation),
"ERC1967: new implementation is not a contract"
);
StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation;
}
/**
* @dev Perform implementation upgrade
*
* Emits an {Upgraded} event.
*/
function _upgradeTo(address newImplementation) internal {
_setImplementation(newImplementation);
emit Upgraded(newImplementation);
}
/**
* @dev Perform implementation upgrade with additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCall(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
_upgradeTo(newImplementation);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(newImplementation, data);
}
}
/**
* @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call.
*
* Emits an {Upgraded} event.
*/
function _upgradeToAndCallUUPS(
address newImplementation,
bytes memory data,
bool forceCall
) internal {
// Upgrades from old implementations will perform a rollback test. This test requires the new
// implementation to upgrade back to the old, non-ERC1822 compliant, implementation. Removing
// this special case will break upgrade paths from old UUPS implementation to new ones.
if (StorageSlot.getBooleanSlot(_ROLLBACK_SLOT).value) {
_setImplementation(newImplementation);
} else {
try IERC1822Proxiable(newImplementation).proxiableUUID() returns (
bytes32 slot
) {
require(
slot == _IMPLEMENTATION_SLOT,
"ERC1967Upgrade: unsupported proxiableUUID"
);
} catch {
revert("ERC1967Upgrade: new implementation is not UUPS");
}
_upgradeToAndCall(newImplementation, data, forceCall);
}
}
/**
* @dev Storage slot with the admin of the contract.
* This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is
* validated in the constructor.
*/
bytes32 internal constant _ADMIN_SLOT =
0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103;
/**
* @dev Emitted when the admin account has changed.
*/
event AdminChanged(address previousAdmin, address newAdmin);
/**
* @dev Returns the current admin.
*/
function _getAdmin() internal view returns (address) {
return StorageSlot.getAddressSlot(_ADMIN_SLOT).value;
}
/**
* @dev Stores a new address in the EIP1967 admin slot.
*/
function _setAdmin(address newAdmin) private {
require(newAdmin != address(0), "ERC1967: new admin is the zero address");
StorageSlot.getAddressSlot(_ADMIN_SLOT).value = newAdmin;
}
/**
* @dev Changes the admin of the proxy.
*
* Emits an {AdminChanged} event.
*/
function _changeAdmin(address newAdmin) internal {
emit AdminChanged(_getAdmin(), newAdmin);
_setAdmin(newAdmin);
}
/**
* @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 internal constant _BEACON_SLOT =
0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50;
/**
* @dev Emitted when the beacon is upgraded.
*/
event BeaconUpgraded(address indexed beacon);
/**
* @dev Returns the current beacon.
*/
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
/**
* @dev Stores a new beacon in the EIP1967 beacon slot.
*/
function _setBeacon(address newBeacon) private {
require(
Address.isContract(newBeacon),
"ERC1967: new beacon is not a contract"
);
require(
Address.isContract(IBeacon(newBeacon).implementation()),
"ERC1967: beacon implementation is not a contract"
);
StorageSlot.getAddressSlot(_BEACON_SLOT).value = newBeacon;
}
/**
* @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does
* not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that).
*
* Emits a {BeaconUpgraded} event.
*/
function _upgradeBeaconToAndCall(
address newBeacon,
bytes memory data,
bool forceCall
) internal {
_setBeacon(newBeacon);
emit BeaconUpgraded(newBeacon);
if (data.length > 0 || forceCall) {
Address.functionDelegateCall(IBeacon(newBeacon).implementation(), data);
}
}
}
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts (last updated v4.5.0) (interfaces/draft-IERC1822.sol)
pragma solidity ^0.8.0;
/**
* @dev ERC1822: Universal Upgradeable Proxy Standard (UUPS) documents a method for upgradeability through a simplified
* proxy whose upgrades are fully controlled by the current implementation.
*/
interface IERC1822Proxiable {
/**
* @dev Returns the storage slot that the proxiable contract assumes is being used to store the implementation
* address.
*
* IMPORTANT: A proxy pointing at a proxiable contract should not be considered proxiable itself, because this risks
* bricking a proxy that upgrades to it, by delegating to itself until out of gas. Thus it is critical that this
* function revert if invoked through a proxy.
*/
function proxiableUUID() external view returns (bytes32);
}
// 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);
}
}
}
}
|
Returns the current beacon./
|
function _getBeacon() internal view returns (address) {
return StorageSlot.getAddressSlot(_BEACON_SLOT).value;
}
| 144,000 |
/*
* Lottery oracle
*
* Copyright (C) 2017-2019 Hubii AS
*/
pragma solidity ^0.5.11;
import {Resolvable} from "./Resolvable.sol";
import {ResolutionEngine} from "./ResolutionEngine.sol";
/// @title NaiveTotalResolutionEngine
/// @author Jens Ivar Jørdre <[email protected]>
/// @notice A naïve total resolution engine
/// Resolve the staking market when:
/// - The total number of tokens staked on either option reaches the defined amount criterion
contract NaiveTotalResolutionEngine is Resolvable, ResolutionEngine {
event NextAmountSet(uint256 amount);
uint256 public nextAmount;
/// @notice `msg.sender` will be added as accessor to the owner role
/// @param _oracle The address of oracle
/// @param _operator The address of operator
/// @param _bountyFund The address of bounty fund
/// @param _nextAmount The next amount criterion of this resolution engine
constructor(address _oracle, address _operator, address _bountyFund,
uint256 _nextAmount)
public
ResolutionEngine(_oracle, _operator, _bountyFund)
{
nextAmount = _nextAmount;
}
/// @notice Return the amount needed to resolve the current market for the given status
/// @param _status The concerned status
/// @return the amount needed to obtain to resolve the market
function resolutionDeltaAmount(bool _status)
public
view
returns (uint256)
{
return (
amountByPhaseNumber(verificationPhaseNumber) >
verificationPhaseByPhaseNumber[verificationPhaseNumber].stakedAmountByStatus[_status] ?
amountByPhaseNumber(verificationPhaseNumber).sub(
verificationPhaseByPhaseNumber[verificationPhaseNumber].stakedAmountByStatus[_status]
) :
0
);
}
/// @notice Gauge whether the resolution criteria have been met
/// @return true if resolution criteria have been met, else false
function resolutionCriteriaMet()
public
view
returns (bool)
{
return verificationPhaseByPhaseNumber[verificationPhaseNumber].stakedAmountByStatus[true] >=
amountByPhaseNumber(verificationPhaseNumber) ||
verificationPhaseByPhaseNumber[verificationPhaseNumber].stakedAmountByStatus[false] >=
amountByPhaseNumber(verificationPhaseNumber);
}
/// @notice Set the next amount criterion
/// @dev Only enabled when the resolution engine is not frozen
/// @param _nextAmount The next amount
function setNextAmount(uint256 _nextAmount)
public
onlyRoleAccessor(OWNER_ROLE)
onlyNotFrozen
{
// Set the amount
nextAmount = _nextAmount;
// Emit event
emit NextAmountSet(nextAmount);
}
/// @notice Get the amount parameter by the given verification phase number
/// @param _verificationPhaseNumber The concerned verification phase number
/// @return the amount value
function amountByPhaseNumber(uint256 _verificationPhaseNumber)
public
view
returns (uint256)
{
return verificationPhaseByPhaseNumber[_verificationPhaseNumber].uintCriteria[0];
}
/// @notice Augment the verification phase with verification criteria params
function _addVerificationCriteria()
internal
{
verificationPhaseByPhaseNumber[verificationPhaseNumber].uintCriteria.push(nextAmount);
}
}
|
Augment the verification phase with verification criteria params
|
function _addVerificationCriteria()
internal
{
verificationPhaseByPhaseNumber[verificationPhaseNumber].uintCriteria.push(nextAmount);
}
| 12,920,258 |
// Sources flattened with hardhat v2.0.2 https://hardhat.org
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.6.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File @openzeppelin/contracts/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 @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) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.6.0;
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// File @openzeppelin/contracts/utils/[email protected]
pragma solidity ^0.6.0;
/**
* @dev Library for managing
* https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive
* types.
*
* Sets have the following properties:
*
* - Elements are added, removed, and checked for existence in constant time
* (O(1)).
* - Elements are enumerated in O(n). No guarantees are made on the ordering.
*
* ```
* contract Example {
* // Add the library methods
* using EnumerableSet for EnumerableSet.AddressSet;
*
* // Declare a set state variable
* EnumerableSet.AddressSet private mySet;
* }
* ```
*
* As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256`
* (`UintSet`) are supported.
*/
library EnumerableSet {
// To implement this library for multiple types with as little code
// repetition as possible, we write it in terms of a generic Set type with
// bytes32 values.
// The Set implementation uses private functions, and user-facing
// implementations (such as AddressSet) are just wrappers around the
// underlying Set.
// This means that we can only create new EnumerableSets for types that fit
// in bytes32.
struct Set {
// Storage of set values
bytes32[] _values;
// Position of the value in the `values` array, plus 1 because index 0
// means a value is not in the set.
mapping (bytes32 => uint256) _indexes;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function _add(Set storage set, bytes32 value) private returns (bool) {
if (!_contains(set, value)) {
set._values.push(value);
// The value is stored at length-1, but we add 1 to all indexes
// and use 0 as a sentinel value
set._indexes[value] = set._values.length;
return true;
} else {
return false;
}
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function _remove(Set storage set, bytes32 value) private returns (bool) {
// We read and store the value's index to prevent multiple reads from the same storage slot
uint256 valueIndex = set._indexes[value];
if (valueIndex != 0) { // Equivalent to contains(set, value)
// To delete an element from the _values array in O(1), we swap the element to delete with the last one in
// the array, and then remove the last element (sometimes called as 'swap and pop').
// This modifies the order of the array, as noted in {at}.
uint256 toDeleteIndex = valueIndex - 1;
uint256 lastIndex = set._values.length - 1;
// When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs
// so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement.
bytes32 lastvalue = set._values[lastIndex];
// Move the last value to the index where the value to delete is
set._values[toDeleteIndex] = lastvalue;
// Update the index for the moved value
set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based
// Delete the slot where the moved value was stored
set._values.pop();
// Delete the index for the deleted slot
delete set._indexes[value];
return true;
} else {
return false;
}
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function _contains(Set storage set, bytes32 value) private view returns (bool) {
return set._indexes[value] != 0;
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function _length(Set storage set) private view returns (uint256) {
return set._values.length;
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function _at(Set storage set, uint256 index) private view returns (bytes32) {
require(set._values.length > index, "EnumerableSet: index out of bounds");
return set._values[index];
}
// AddressSet
struct AddressSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(AddressSet storage set, address value) internal returns (bool) {
return _add(set._inner, bytes32(uint256(value)));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(AddressSet storage set, address value) internal returns (bool) {
return _remove(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(AddressSet storage set, address value) internal view returns (bool) {
return _contains(set._inner, bytes32(uint256(value)));
}
/**
* @dev Returns the number of values in the set. O(1).
*/
function length(AddressSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(AddressSet storage set, uint256 index) internal view returns (address) {
return address(uint256(_at(set._inner, index)));
}
// UintSet
struct UintSet {
Set _inner;
}
/**
* @dev Add a value to a set. O(1).
*
* Returns true if the value was added to the set, that is if it was not
* already present.
*/
function add(UintSet storage set, uint256 value) internal returns (bool) {
return _add(set._inner, bytes32(value));
}
/**
* @dev Removes a value from a set. O(1).
*
* Returns true if the value was removed from the set, that is if it was
* present.
*/
function remove(UintSet storage set, uint256 value) internal returns (bool) {
return _remove(set._inner, bytes32(value));
}
/**
* @dev Returns true if the value is in the set. O(1).
*/
function contains(UintSet storage set, uint256 value) internal view returns (bool) {
return _contains(set._inner, bytes32(value));
}
/**
* @dev Returns the number of values on the set. O(1).
*/
function length(UintSet storage set) internal view returns (uint256) {
return _length(set._inner);
}
/**
* @dev Returns the value stored at position `index` in the set. O(1).
*
* Note that there are no guarantees on the ordering of values inside the
* array, and it may change when more values are added or removed.
*
* Requirements:
*
* - `index` must be strictly less than {length}.
*/
function at(UintSet storage set, uint256 index) internal view returns (uint256) {
return uint256(_at(set._inner, index));
}
}
// File @openzeppelin/contracts/GSN/[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 @openzeppelin/contracts/access/[email protected]
pragma solidity ^0.6.0;
/**
* @dev Contract module that allows children to implement role-based access
* control mechanisms.
*
* Roles are referred to by their `bytes32` identifier. These should be exposed
* in the external API and be unique. The best way to achieve this is by
* using `public constant` hash digests:
*
* ```
* bytes32 public constant MY_ROLE = keccak256("MY_ROLE");
* ```
*
* Roles can be used to represent a set of permissions. To restrict access to a
* function call, use {hasRole}:
*
* ```
* function foo() public {
* require(hasRole(MY_ROLE, msg.sender));
* ...
* }
* ```
*
* Roles can be granted and revoked dynamically via the {grantRole} and
* {revokeRole} functions. Each role has an associated admin role, and only
* accounts that have a role's admin role can call {grantRole} and {revokeRole}.
*
* By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means
* that only accounts with this role will be able to grant or revoke other
* roles. More complex role relationships can be created by using
* {_setRoleAdmin}.
*
* WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to
* grant and revoke this role. Extra precautions should be taken to secure
* accounts that have been granted it.
*/
abstract contract AccessControl is Context {
using EnumerableSet for EnumerableSet.AddressSet;
using Address for address;
struct RoleData {
EnumerableSet.AddressSet members;
bytes32 adminRole;
}
mapping (bytes32 => RoleData) private _roles;
bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00;
/**
* @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole`
*
* `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite
* {RoleAdminChanged} not being emitted signaling this.
*
* _Available since v3.1._
*/
event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole);
/**
* @dev Emitted when `account` is granted `role`.
*
* `sender` is the account that originated the contract call, an admin role
* bearer except when using {_setupRole}.
*/
event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Emitted when `account` is revoked `role`.
*
* `sender` is the account that originated the contract call:
* - if using `revokeRole`, it is the admin role bearer
* - if using `renounceRole`, it is the role bearer (i.e. `account`)
*/
event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender);
/**
* @dev Returns `true` if `account` has been granted `role`.
*/
function hasRole(bytes32 role, address account) public view returns (bool) {
return _roles[role].members.contains(account);
}
/**
* @dev Returns the number of accounts that have `role`. Can be used
* together with {getRoleMember} to enumerate all bearers of a role.
*/
function getRoleMemberCount(bytes32 role) public view returns (uint256) {
return _roles[role].members.length();
}
/**
* @dev Returns one of the accounts that have `role`. `index` must be a
* value between 0 and {getRoleMemberCount}, non-inclusive.
*
* Role bearers are not sorted in any particular way, and their ordering may
* change at any point.
*
* WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure
* you perform all queries on the same block. See the following
* https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post]
* for more information.
*/
function getRoleMember(bytes32 role, uint256 index) public view returns (address) {
return _roles[role].members.at(index);
}
/**
* @dev Returns the admin role that controls `role`. See {grantRole} and
* {revokeRole}.
*
* To change a role's admin, use {_setRoleAdmin}.
*/
function getRoleAdmin(bytes32 role) public view returns (bytes32) {
return _roles[role].adminRole;
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function grantRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant");
_grantRole(role, account);
}
/**
* @dev Revokes `role` from `account`.
*
* If `account` had been granted `role`, emits a {RoleRevoked} event.
*
* Requirements:
*
* - the caller must have ``role``'s admin role.
*/
function revokeRole(bytes32 role, address account) public virtual {
require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke");
_revokeRole(role, account);
}
/**
* @dev Revokes `role` from the calling account.
*
* Roles are often managed via {grantRole} and {revokeRole}: this function's
* purpose is to provide a mechanism for accounts to lose their privileges
* if they are compromised (such as when a trusted device is misplaced).
*
* If the calling account had been granted `role`, emits a {RoleRevoked}
* event.
*
* Requirements:
*
* - the caller must be `account`.
*/
function renounceRole(bytes32 role, address account) public virtual {
require(account == _msgSender(), "AccessControl: can only renounce roles for self");
_revokeRole(role, account);
}
/**
* @dev Grants `role` to `account`.
*
* If `account` had not been already granted `role`, emits a {RoleGranted}
* event. Note that unlike {grantRole}, this function doesn't perform any
* checks on the calling account.
*
* [WARNING]
* ====
* This function should only be called from the constructor when setting
* up the initial roles for the system.
*
* Using this function in any other way is effectively circumventing the admin
* system imposed by {AccessControl}.
* ====
*/
function _setupRole(bytes32 role, address account) internal virtual {
_grantRole(role, account);
}
/**
* @dev Sets `adminRole` as ``role``'s admin role.
*
* Emits a {RoleAdminChanged} event.
*/
function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual {
emit RoleAdminChanged(role, _roles[role].adminRole, adminRole);
_roles[role].adminRole = adminRole;
}
function _grantRole(bytes32 role, address account) private {
if (_roles[role].members.add(account)) {
emit RoleGranted(role, account, _msgSender());
}
}
function _revokeRole(bytes32 role, address account) private {
if (_roles[role].members.remove(account)) {
emit RoleRevoked(role, account, _msgSender());
}
}
}
// File @openzeppelin/contracts/token/ERC20/[email protected]
pragma solidity ^0.6.0;
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// File contracts/token/WePiggyToken.sol
pragma solidity 0.6.12;
// Copied and modified from SUSHI code:
// https://github.com/sushiswap/sushiswap/blob/master/contracts/SushiToken.sol
// WePiggyToken with Governance.
contract WePiggyToken is ERC20, AccessControl {
// Create a new role identifier for the minter role
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
constructor() public ERC20("WePiggy Token", "WPT") {
// Grant the contract deployer the default admin role: it will be able
// to grant and revoke any roles
_setupRole(DEFAULT_ADMIN_ROLE, msg.sender);
}
/// @notice Creates `_amount` token to `_to`.Must only be called by the minter role.
function mint(address _to, uint256 _amount) public {
// Check that the calling account has the minter role
require(hasRole(MINTER_ROLE, msg.sender), "Caller is not a minter");
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
// transfers delegate authority when sending a token.
// https://medium.com/bulldax-finance/sushiswap-delegation-double-spending-bug-5adcc7b3830f
function _transfer(address sender, address recipient, uint256 amount) internal override virtual {
super._transfer(sender, recipient, amount);
_moveDelegates(_delegates[sender], _delegates[recipient], amount);
}
// Copied and modified from YAM code:
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol
// https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol
// Which is copied and modified from COMPOUND:
// https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol
/// @dev A record of each accounts delegate
mapping(address => address) internal _delegates;
/// @notice A checkpoint for marking number of votes from a given block
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping(address => mapping(uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping(address => uint32) public numCheckpoints;
/// @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 delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping(address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "WePiggyToken::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "WePiggyToken::delegateBySig: invalid nonce");
require(now <= expiry, "WePiggyToken::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "WePiggyToken::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
// ceil, avoiding overflow
uint32 center = upper - (upper - lower) / 2;
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
// balance of underlying WePiggyTokens (not scaled);
uint256 delegatorBalance = balanceOf(delegator);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "WePiggyToken::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2 ** 32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly {chainId := chainid()}
return chainId;
}
}
// File contracts/farm/PiggyBreeder.sol
pragma solidity 0.6.12;
// Copied and modified from sushiswap code:
// https://github.com/sushiswap/sushiswap/blob/master/contracts/MasterChef.sol
interface IMigrator {
function replaceMigrate(IERC20 lpToken) external returns (IERC20, uint);
function migrate(IERC20 lpToken) external returns (IERC20, uint);
}
// PiggyBreeder is the master of PiggyToken.
contract PiggyBreeder is Ownable {
using SafeMath for uint256;
using SafeERC20 for IERC20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt.
uint256 pendingReward;
bool unStakeBeforeEnableClaim;
}
// Info of each pool.
struct PoolInfo {
IERC20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. PiggyTokens to distribute per block.
uint256 lastRewardBlock; // Last block number that PiggyTokens distribution occurs.
uint256 accPiggyPerShare; // Accumulated PiggyTokens per share, times 1e12. See below.
uint256 totalDeposit; // Accumulated deposit tokens.
IMigrator migrator;
}
// The WePiggyToken !
WePiggyToken public piggy;
// Dev address.
address public devAddr;
// Percentage of developers mining
uint256 public devMiningRate;
// PIGGY tokens created per block.
uint256 public piggyPerBlock;
// The block number when WPC mining starts.
uint256 public startBlock;
// The block number when WPC claim starts.
uint256 public enableClaimBlock;
// Interval blocks to reduce mining volume.
uint256 public reduceIntervalBlock;
// reduce rate
uint256 public reduceRate;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
mapping(uint256 => address[]) public userAddresses;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
event Stake(address indexed user, uint256 indexed pid, uint256 amount);
event Claim(address indexed user, uint256 indexed pid);
event UnStake(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
event ReplaceMigrate(address indexed user, uint256 pid, uint256 amount);
event Migrate(address indexed user, uint256 pid, uint256 targetPid, uint256 amount);
constructor (
WePiggyToken _piggy,
address _devAddr,
uint256 _piggyPerBlock,
uint256 _startBlock,
uint256 _enableClaimBlock,
uint256 _reduceIntervalBlock,
uint256 _reduceRate,
uint256 _devMiningRate
) public {
piggy = _piggy;
devAddr = _devAddr;
piggyPerBlock = _piggyPerBlock;
startBlock = _startBlock;
reduceIntervalBlock = _reduceIntervalBlock;
reduceRate = _reduceRate;
devMiningRate = _devMiningRate;
enableClaimBlock = _enableClaimBlock;
totalAllocPoint = 0;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function usersLength(uint256 _pid) external view returns (uint256) {
return userAddresses[_pid].length;
}
// Update dev address by the previous dev.
function setDevAddr(address _devAddr) public onlyOwner {
devAddr = _devAddr;
}
// Set the migrator contract. Can only be called by the owner.
function setMigrator(uint256 _pid, IMigrator _migrator) public onlyOwner {
poolInfo[_pid].migrator = _migrator;
}
// set the enable claim block
function setEnableClaimBlock(uint256 _enableClaimBlock) public onlyOwner {
enableClaimBlock = _enableClaimBlock;
}
// update reduceIntervalBlock
function setReduceIntervalBlock(uint256 _reduceIntervalBlock, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
reduceIntervalBlock = _reduceIntervalBlock;
}
// Update the given pool's PIGGY allocation point. Can only be called by the owner.
function setAllocPoint(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
//update totalAllocPoint
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
//update poolInfo
poolInfo[_pid].allocPoint = _allocPoint;
}
// update reduce rate
function setReduceRate(uint256 _reduceRate, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
reduceRate = _reduceRate;
}
// update dev mining rate
function setDevMiningRate(uint256 _devMiningRate) public onlyOwner {
devMiningRate = _devMiningRate;
}
// Migrate lp token to another lp contract.
function replaceMigrate(uint256 _pid) public onlyOwner {
PoolInfo storage pool = poolInfo[_pid];
IMigrator migrator = pool.migrator;
require(address(migrator) != address(0), "migrate: no migrator");
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
(IERC20 newLpToken, uint mintBal) = migrator.replaceMigrate(lpToken);
require(bal == newLpToken.balanceOf(address(this)), "migrate: bad");
pool.lpToken = newLpToken;
emit ReplaceMigrate(address(migrator), _pid, bal);
}
// Move lp token data to another lp contract.
function migrate(uint256 _pid, uint256 _targetPid, uint256 begin) public onlyOwner {
require(begin < userAddresses[_pid].length, "migrate: begin error");
PoolInfo storage pool = poolInfo[_pid];
IMigrator migrator = pool.migrator;
require(address(migrator) != address(0), "migrate: no migrator");
IERC20 lpToken = pool.lpToken;
uint256 bal = lpToken.balanceOf(address(this));
lpToken.safeApprove(address(migrator), bal);
(IERC20 newLpToken, uint mintBal) = migrator.migrate(lpToken);
PoolInfo storage targetPool = poolInfo[_targetPid];
require(address(targetPool.lpToken) == address(newLpToken), "migrate: bad");
uint rate = mintBal.mul(1e12).div(bal);
for (uint i = begin; i < begin.add(20); i++) {
if (i < userAddresses[_pid].length) {
updatePool(_targetPid);
address addr = userAddresses[_pid][i];
UserInfo storage user = userInfo[_pid][addr];
UserInfo storage tUser = userInfo[_targetPid][addr];
if (user.amount <= 0) {
continue;
}
uint tmp = user.amount.mul(rate).div(1e12);
tUser.amount = tUser.amount.add(tmp);
tUser.rewardDebt = tUser.rewardDebt.add(user.rewardDebt.mul(rate).div(1e12));
targetPool.totalDeposit = targetPool.totalDeposit.add(tmp);
pool.totalDeposit = pool.totalDeposit.sub(user.amount);
user.rewardDebt = 0;
user.amount = 0;
} else {
break;
}
}
emit Migrate(address(migrator), _pid, _targetPid, bal);
}
// Safe piggy transfer function, just in case if rounding error causes pool to not have enough PiggyToken.
function safePiggyTransfer(address _to, uint256 _amount) internal {
uint256 piggyBal = piggy.balanceOf(address(this));
if (_amount > piggyBal) {
piggy.transfer(_to, piggyBal);
} else {
piggy.transfer(_to, _amount);
}
}
// Return piggyPerBlock, baseOn power --> piggyPerBlock * (reduceRate/100)^power
function getPiggyPerBlock(uint256 _power) public view returns (uint256){
if (_power == 0) {
return piggyPerBlock;
} else {
uint256 z = piggyPerBlock;
for (uint256 i = 0; i < _power; i++) {
z = z.mul(reduceRate).div(1000);
}
return z;
}
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) {
return _to.sub(_from);
}
// View function to see all pending PiggyToken on frontend.
function allPendingPiggy(address _user) external view returns (uint256){
uint sum = 0;
for (uint i = 0; i < poolInfo.length; i++) {
sum = sum.add(_pending(i, _user));
}
return sum;
}
// View function to see pending PiggyToken on frontend.
function pendingPiggy(uint256 _pid, address _user) external view returns (uint256) {
return _pending(_pid, _user);
}
//internal function
function _pending(uint256 _pid, address _user) internal view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accPiggyPerShare = pool.accPiggyPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
// pending piggy reward
uint256 piggyReward = 0;
uint256 lastRewardBlockPower = pool.lastRewardBlock.sub(startBlock).div(reduceIntervalBlock);
uint256 blockNumberPower = block.number.sub(startBlock).div(reduceIntervalBlock);
// get piggyReward from pool.lastRewardBlock to block.number.
// different interval different multiplier and piggyPerBlock, sum piggyReward
if (lastRewardBlockPower == blockNumberPower) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
piggyReward = piggyReward.add(multiplier.mul(getPiggyPerBlock(blockNumberPower)).mul(pool.allocPoint).div(totalAllocPoint));
} else {
for (uint256 i = lastRewardBlockPower; i <= blockNumberPower; i++) {
uint256 multiplier = 0;
if (i == lastRewardBlockPower) {
multiplier = getMultiplier(pool.lastRewardBlock, startBlock.add(lastRewardBlockPower.add(1).mul(reduceIntervalBlock)).sub(1));
} else if (i == blockNumberPower) {
multiplier = getMultiplier(startBlock.add(blockNumberPower.mul(reduceIntervalBlock)), block.number);
} else {
multiplier = reduceIntervalBlock;
}
piggyReward = piggyReward.add(multiplier.mul(getPiggyPerBlock(i)).mul(pool.allocPoint).div(totalAllocPoint));
}
}
accPiggyPerShare = accPiggyPerShare.add(piggyReward.mul(1e12).div(lpSupply));
}
// get pending value
uint256 pendingValue = user.amount.mul(accPiggyPerShare).div(1e12).sub(user.rewardDebt);
// if enableClaimBlock after block.number, return pendingValue + user.pendingReward.
// else return pendingValue.
if (enableClaimBlock > block.number) {
return pendingValue.add(user.pendingReward);
} else if (user.pendingReward > 0 && user.unStakeBeforeEnableClaim) {
return pendingValue.add(user.pendingReward);
}
return pendingValue;
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0) {
pool.lastRewardBlock = block.number;
return;
}
// get piggyReward. piggyReward base on current PiggyPerBlock.
uint256 power = block.number.sub(startBlock).div(reduceIntervalBlock);
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 piggyReward = multiplier.mul(getPiggyPerBlock(power)).mul(pool.allocPoint).div(totalAllocPoint);
// mint
piggy.mint(devAddr, piggyReward.mul(devMiningRate).div(100));
piggy.mint(address(this), piggyReward);
//update pool
pool.accPiggyPerShare = pool.accPiggyPerShare.add(piggyReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Add a new lp to the pool. Can only be called by the owner.
// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
function add(uint256 _allocPoint, IERC20 _lpToken, IMigrator _migrator, bool _withUpdate) public onlyOwner {
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
//update totalAllocPoint
totalAllocPoint = totalAllocPoint.add(_allocPoint);
// add poolInfo
poolInfo.push(PoolInfo({
lpToken : _lpToken,
allocPoint : _allocPoint,
lastRewardBlock : lastRewardBlock,
accPiggyPerShare : 0,
totalDeposit : 0,
migrator : _migrator
}));
}
// Stake LP tokens to PiggyBreeder for WPC allocation.
function stake(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
//update poolInfo by pid
updatePool(_pid);
// if user's amount bigger than zero, transfer PiggyToken to user.
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accPiggyPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
// if enableClaimBlock after block.number, save the pending to user.pendingReward.
if (enableClaimBlock <= block.number) {
safePiggyTransfer(msg.sender, pending);
// transfer user.pendingReward if user.pendingReward > 0, and update user.pendingReward to 0
if (user.pendingReward > 0) {
safePiggyTransfer(msg.sender, user.pendingReward);
user.pendingReward = 0;
}
} else {
user.pendingReward = user.pendingReward.add(pending);
}
}
}
if (_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
user.amount = user.amount.add(_amount);
pool.totalDeposit = pool.totalDeposit.add(_amount);
userAddresses[_pid].push(msg.sender);
}
user.rewardDebt = user.amount.mul(pool.accPiggyPerShare).div(1e12);
emit Stake(msg.sender, _pid, _amount);
}
// UnStake LP tokens from PiggyBreeder.
function unStake(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "unStake: not good");
//update poolInfo by pid
updatePool(_pid);
//transfer PiggyToken to user.
uint256 pending = user.amount.mul(pool.accPiggyPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
// if enableClaimBlock after block.number, save the pending to user.pendingReward.
if (enableClaimBlock <= block.number) {
safePiggyTransfer(msg.sender, pending);
// transfer user.pendingReward if user.pendingReward > 0, and update user.pendingReward to 0
if (user.pendingReward > 0) {
safePiggyTransfer(msg.sender, user.pendingReward);
user.pendingReward = 0;
}
} else {
user.pendingReward = user.pendingReward.add(pending);
user.unStakeBeforeEnableClaim = true;
}
}
if (_amount > 0) {
// transfer LP tokens to user
pool.lpToken.safeTransfer(address(msg.sender), _amount);
// update user info
user.amount = user.amount.sub(_amount);
pool.totalDeposit = pool.totalDeposit.sub(_amount);
}
user.rewardDebt = user.amount.mul(pool.accPiggyPerShare).div(1e12);
emit UnStake(msg.sender, _pid, _amount);
}
// claim WPC
function claim(uint256 _pid) public {
require(enableClaimBlock <= block.number, "too early to claim");
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
//update poolInfo by pid
updatePool(_pid);
// if user's amount bigger than zero, transfer PiggyToken to user.
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accPiggyPerShare).div(1e12).sub(user.rewardDebt);
if (pending > 0) {
safePiggyTransfer(msg.sender, pending);
}
}
// transfer user.pendingReward if user.pendingReward > 0, and update user.pendingReward to 0
if (user.pendingReward > 0) {
safePiggyTransfer(msg.sender, user.pendingReward);
user.pendingReward = 0;
}
// update user info
user.rewardDebt = user.amount.mul(pool.accPiggyPerShare).div(1e12);
emit Claim(msg.sender, _pid);
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
// transfer LP tokens to user
pool.lpToken.safeTransfer(address(msg.sender), amount);
pool.totalDeposit = pool.totalDeposit.sub(user.amount);
// update user info
user.amount = 0;
user.rewardDebt = 0;
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
}
|
internal function pending piggy reward get piggyReward from pool.lastRewardBlock to block.number. different interval different multiplier and piggyPerBlock, sum piggyReward if enableClaimBlock after block.number, return pendingValue + user.pendingReward. else return pendingValue.
|
function _pending(uint256 _pid, address _user) internal view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accPiggyPerShare = pool.accPiggyPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 piggyReward = 0;
uint256 lastRewardBlockPower = pool.lastRewardBlock.sub(startBlock).div(reduceIntervalBlock);
uint256 blockNumberPower = block.number.sub(startBlock).div(reduceIntervalBlock);
if (lastRewardBlockPower == blockNumberPower) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
piggyReward = piggyReward.add(multiplier.mul(getPiggyPerBlock(blockNumberPower)).mul(pool.allocPoint).div(totalAllocPoint));
for (uint256 i = lastRewardBlockPower; i <= blockNumberPower; i++) {
uint256 multiplier = 0;
if (i == lastRewardBlockPower) {
multiplier = getMultiplier(pool.lastRewardBlock, startBlock.add(lastRewardBlockPower.add(1).mul(reduceIntervalBlock)).sub(1));
multiplier = getMultiplier(startBlock.add(blockNumberPower.mul(reduceIntervalBlock)), block.number);
multiplier = reduceIntervalBlock;
}
piggyReward = piggyReward.add(multiplier.mul(getPiggyPerBlock(i)).mul(pool.allocPoint).div(totalAllocPoint));
}
}
accPiggyPerShare = accPiggyPerShare.add(piggyReward.mul(1e12).div(lpSupply));
}
if (enableClaimBlock > block.number) {
return pendingValue.add(user.pendingReward);
return pendingValue.add(user.pendingReward);
}
return pendingValue;
}
| 1,339,960 |
./full_match/43113/0x99fCa0B1D9b982B1cbE001e6F059413Be5920D59/sources/Happy/Happy.sol
|
return current interval (in days) /
|
function interval() public view returns (uint256) {
uint256 _interval = block.timestamp / (1 days);
require(_interval > 0, "invalid interval");
return _interval;
}
| 13,177,025 |
pragma solidity ^0.4.23;
library SafeMath{
// Multiples 2 numbers, throws on overflow is detected.
function mul(uint256 _x, uint256 _y) internal pure returns (uint256 result){
if(_y == 0){
return 0;
}
result = _x*_y;
assert(_x == result/_y);
return result;
}
//Divides 2 numbers, solidity automatically throws if _y is 0.
function div(uint256 _x, uint256 _y) internal pure returns (uint256 result){
result = _x / _y;
return result;
}
//Adds 2 numbers, throws on overflow.
function add(uint256 _x, uint256 _y) internal pure returns (uint256 result){
result = _x + _y;
assert(result >= _x);
return result;
}
function sub(uint256 _x, uint256 _y) internal pure returns (uint256 result){
assert(_x >= _y);
result = _x - _y;
return result;
}
}
interface ReceiverContract{
function tokenFallback(address _sender, uint256 _amount, bytes _data) external;
}
contract ERC20Interface {
function balanceOf(address tokenOwner) public view returns (uint balance);
function transfer(address to, uint tokens) public returns (bool success);
function allowance(address tokenOwner, address spender) public view returns (uint remaining);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
contract Ownable{
address public owner;
event ownerTransfer(address indexed oldOwner, address indexed newOwner);
event ownerGone(address indexed oldOwner);
constructor(){
owner = msg.sender;
}
modifier onlyOwner(){
require(msg.sender == owner);
_;
}
function changeOwner(address _newOwner) public onlyOwner{
require(_newOwner != address(0x0));
emit ownerTransfer(owner, _newOwner);
owner = _newOwner;
}
function deleteOwner() public onlyOwner{
emit ownerGone(owner);
owner = 0x0;
}
}
contract Haltable is Ownable{
bool public paused;
event ContractPaused(address by);
event ContractUnpaused(address by);
constructor(){
paused = false;
}
function pause() public onlyOwner {
paused = true;
emit ContractPaused(owner);
}
function unpause() public onlyOwner {
paused = false;
emit ContractUnpaused(owner);
}
modifier stopOnPause(){
require(paused == false);
_;
}
}
contract ERC223Interface is Haltable, ERC20Interface{
function transfer(address _to, uint _amount, bytes _data) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens, bytes data);
event BalanceBurned(address indexed from, uint amount);
}
contract ABIO is ERC223Interface{
using SafeMath for uint256;
mapping (address => uint256) balances;
mapping (address => mapping (address => uint256)) internal allowed;
//Getter functions are defined automatically for the following variables.
string public name;
string public symbol;
uint8 public decimals;
uint256 public totalSupply;
address ICOAddress;
address PICOAddress;
constructor(string _name, string _symbol, uint8 _decimals, uint256 _supply) public{
name = _name;
symbol = _symbol;
decimals = _decimals;
totalSupply = _supply;
balances[msg.sender] = totalSupply;
}
function supplyPICO(address _preIco) onlyOwner{
require(_preIco != 0x0 && PICOAddress == 0x0);
PICOAddress = _preIco;
}
function supplyICO(address _ico) onlyOwner{
require(_ico != 0x0 && ICOAddress == 0x0);
ICOAddress = _ico;
}
function burnMyBalance() public {
require(msg.sender != 0x0);
require(msg.sender == ICOAddress || msg.sender == PICOAddress);
uint b = balanceOf(msg.sender);
totalSupply = totalSupply.sub(b);
balances[msg.sender] = 0;
emit BalanceBurned(msg.sender, b);
}
/**
* @notice Underlying transfer function; it is called by public functions later.
* @dev This architecture saves >30000 gas as compared to having two independent public functions
* for transfer with and without `_data`.
**/
function _transfer(address _from, address _to, uint256 _amount, bytes _data) internal returns (bool success){
require(_to != 0x0);
require(_amount <= balanceOf(_from));
uint256 initialBalances = balanceOf(_from).add(balanceOf(_to));
balances[_from] = balanceOf(_from).sub(_amount);
balances[_to] = balanceOf(_to).add(_amount);
if(isContract(_to)){
ReceiverContract receiver = ReceiverContract(_to);
receiver.tokenFallback(_from, _amount, _data);
}
assert(initialBalances == balanceOf(_from).add(balanceOf(_to)));
return true;
}
/**
* @notice Transfer with addidition data.
* @param _data will be sent to tokenFallback() if receiver is a contract.
**/
function transfer(address _to, uint256 _amount, bytes _data) stopOnPause public returns (bool success){
if (_transfer(msg.sender, _to, _amount, _data)){
emit Transfer(msg.sender, _to, _amount, _data);
return true;
}
return false;
}
/**
* @notice Transfer without additional data.
* @dev An empty `bytes` instance will be created and sent to `tokenFallback()` if receiver is a contract.
**/
function transfer(address _to, uint256 _amount) stopOnPause public returns (bool success){
bytes memory empty;
if (_transfer(msg.sender, _to, _amount, empty)){
emit Transfer(msg.sender , _to, _amount);
return true;
}
return false;
}
/**
* @notice Transfers `_amount` from `_from` to `_to` without additional data.
* @dev Only if `approve` has been called before!
* @param _data will be sent to tokenFallback() if receiver is a contract.
**/
function transferFrom(address _from, address _to, uint256 _amount, bytes _data) stopOnPause public returns (bool success){
require(_from != 0x0);
require(allowance(_from, msg.sender) >= _amount);
allowed[_from][msg.sender] = allowance(_from, msg.sender).sub(_amount);
assert(_transfer(_from, _to, _amount, _data));
emit Transfer(_from, _to, _amount, _data);
return true;
}
/**
* @notice Transfers `_amount` from `_from` to `_to` with additional data.
* @dev Only if `approve` has been called before!
* @dev An empty `bytes` instance will be created and sent to `tokenFallback()` if receiver is a contract.
**/
function transferFrom(address _from, address _to, uint256 _amount) stopOnPause public returns (bool success){
require(_from != 0x0);
require(allowance(_from, msg.sender) >= _amount);
bytes memory empty;
allowed[_from][msg.sender] = allowance(_from, msg.sender).sub(_amount);
assert(_transfer(_from, _to, _amount, empty));
emit Transfer(_from, _to, _amount, empty);
return true;
}
/**
* @notice gives `_spender` allowance to spend `amount` from sender's balance.
**/
function approve(address _spender, uint256 _amount) stopOnPause public returns (bool success){
require(_spender != 0x0);
allowed[msg.sender][_spender] = _amount;
emit Approval(msg.sender, _spender, _amount);
return true;
}
/**
* @notice Checks how much a certain user allowed to a different one.
**/
function allowance(address _owner, address _spender) public view returns (uint256){
return allowed[_owner][_spender];
}
/**
* @notice Checks if a contract is behind an address.
* @dev Does it by checking if it has ANY code.
**/
function isContract(address _addr) public view returns(bool is_contract){
uint length;
assembly {
//retrieve the code length/size on target address
length := extcodesize(_addr)
}
return (length>0);
}
/**
* @notice Returns balance of an address.
* @dev Returns `0` the address was never seen before.
**/
function balanceOf(address _addr) public view returns (uint256){
return balances[_addr];
}
}
|
Transfers `_amount` from `_from` to `_to` with additional data. Only if `approve` has been called before! An empty `bytes` instance will be created and sent to `tokenFallback()` if receiver is a contract./
|
function transferFrom(address _from, address _to, uint256 _amount) stopOnPause public returns (bool success){
require(_from != 0x0);
require(allowance(_from, msg.sender) >= _amount);
bytes memory empty;
allowed[_from][msg.sender] = allowance(_from, msg.sender).sub(_amount);
assert(_transfer(_from, _to, _amount, empty));
emit Transfer(_from, _to, _amount, empty);
return true;
}
| 7,935,639 |
pragma solidity 0.5.17;
library Address {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param account address to check
* @return whether the target address is a contract
*/
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);
}
}
contract ERC20Interface {
function balanceOf(address tokenOwner) public view returns (uint256 balance);
function allowance(address tokenOwner, address spender) public view returns (uint256 remaining);
function transfer(address to, uint256 tokens) public returns (bool success);
function approve(address spender, uint256 tokens) public returns (bool success);
function transferFrom(address from, address to, uint256 tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint256 tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint256 tokens);
}
library SafeMath {
/**
The MIT License (MIT)
Copyright (c) 2016-2020 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.
*/
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 && c >= b);
return c;
}
}
interface TokenRecipient {
function receiveApproval(address _from, uint256 _value, address _token, bytes calldata _extraData) external;
function tokenFallback(address _from, uint256 _value, bytes calldata _data) external;
}
contract Ownership {
address public owner;
event OwnershipUpdated(address oldOwner, address newOwner);
constructor() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner, "Not owner");
_;
}
/**
* @dev Transfer the ownership to some other address.
* new owner can not be a zero address.
* Only owner can call this function
* @param _newOwner Address to which ownership is being transferred
*/
function updateOwner(address _newOwner)
public
onlyOwner
{
require(_newOwner != address(0x0), "Invalid address");
owner = _newOwner;
emit OwnershipUpdated(msg.sender, owner);
}
/**
* @dev Renounce the ownership.
* This will leave the contract without any owner.
* Only owner can call this function
* @param _validationCode A code to prevent aaccidental calling of this function
*/
function renounceOwnership(uint _validationCode)
public
onlyOwner
{
require(_validationCode == 123456789, "Invalid code");
owner = address(0);
emit OwnershipUpdated(msg.sender, owner);
}
}
library SafeERC20 {
/**
The MIT License (MIT)
Copyright (c) 2016-2020 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.
*/
using Address for address;
function safeTransfer(ERC20Interface token, address to, uint256 value) internal {
require(address(token).isContract(), "SafeERC20: call to non-contract");
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function _callOptionalReturn(ERC20Interface token, bytes memory data) private {
(bool success, bytes memory returndata) = address(token).call(data);
require(success, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
contract OToken is ERC20Interface, Ownership {
using SafeMath for uint256;
using Address for address;
using SafeERC20 for ERC20Interface;
// State variables
string public constant name = 'O Token'; // Name of token
string public constant symbol = 'OT'; // Symbol of token
uint256 public constant decimals = 8; // Decimals in token
address public deputyOwner; // to perform tasks on behalf of owner in automated applications
uint256 public totalSupply = 0; // initially totalSupply 0
// external wallet addresses
address public suspenseWallet; // the contract resposible for burning tokens
address public centralRevenueWallet; // platform wallet to collect commission
address public minter; // adddress of minter
// to hold commissions on each token transfer
uint256 public commission_numerator; // commission percentage numerator
uint256 public commission_denominator;// commission percentage denominator
// mappings
mapping (address => uint256) balances; // balances mapping to hold OT balance of address
mapping (address => mapping (address => uint256) ) allowed; // mapping to hold allowances
mapping (address => bool) public isTaxFreeSender; // tokens transferred from these users won't be taxed
mapping (address => bool) public isTaxFreeRecipeint; // if token transferred to these addresses won't be taxed
mapping (string => mapping(string => bool)) public sawtoothHashMapping;
mapping (address => bool) public trustedContracts; // contracts on which tokenFallback will be called
// events
event MintOrBurn(address _from, address to, uint256 _token, string sawtoothHash, string orderId );
event CommssionUpdate(uint256 _numerator, uint256 _denominator);
event TaxFreeUserUpdate(address _user, bool _isWhitelisted, string _type);
event TrustedContractUpdate(address _contractAddress, bool _isActive);
event MinterUpdated(address _newMinter, address _oldMinter);
event SuspenseWalletUpdated(address _newSuspenseWallet, address _oldSuspenseWallet);
event DeputyOwnerUpdated(address _oldOwner, address _newOwner);
event CRWUpdated(address _newCRW, address _oldCRW);
constructor (address _minter, address _crw, address _newDeputyOwner)
public
onlyNonZeroAddress(_minter)
onlyNonZeroAddress(_crw)
onlyNonZeroAddress(_newDeputyOwner)
{
owner = msg.sender; // set owner address to be msg.sender
minter = _minter; // set minter address
centralRevenueWallet = _crw; // set central revenue wallet address
deputyOwner = _newDeputyOwner; // set deputy owner
commission_numerator = 1; // set commission
commission_denominator = 100;
// emit proper events
emit MinterUpdated(_minter, address(0));
emit CRWUpdated(_crw, address(0));
emit DeputyOwnerUpdated(_newDeputyOwner, address(0));
emit CommssionUpdate(1, 100);
}
// Modifiers
modifier canBurn() {
require(msg.sender == suspenseWallet, "only suspense wallet is allowed");
_;
}
modifier onlyMinter() {
require(msg.sender == minter,"only minter is allowed");
_;
}
modifier onlyDeputyOrOwner() {
require(msg.sender == owner || msg.sender == deputyOwner, "Only owner or deputy owner is allowed");
_;
}
modifier onlyNonZeroAddress(address _user) {
require(_user != address(0), "Zero address not allowed");
_;
}
modifier onlyValidSawtoothEntry(string memory _sawtoothHash, string memory _orderId) {
require(!sawtoothHashMapping[_sawtoothHash][_orderId], "Sawtooth hash amd orderId combination already used");
_;
}
////////////////////////////////////////////////////////////////
// Public Functions
////////////////////////////////////////////////////////////////
/**
* @notice Standard transfer function to Transfer token
* @dev The commission will be charged on top of _value
* @param _to recipient address
* @param _value amount of tokens to be transferred to recipient
* @return Bool value
*/
function transfer(address _to, uint256 _value) public returns (bool) {
return privateTransfer(msg.sender, _to, _value, false, false); // internal method
}
/**
* @notice Alternate method to standard transfer with fee deducted from transfer amount
* @dev The commission will be deducted from _value
* @param _to recipient address
* @param _value amount of tokens to be transferred to recipient
* @return Bool value
*/
function transferIncludingFee(address _to, uint256 _value)
public
onlyNonZeroAddress(_to)
returns(bool)
{
return privateTransfer(msg.sender, _to, _value, false, true);
}
/**
* @notice Bulk transfer
* @dev The commission will be charged on top of _value
* @param _addressArr array of recipient address
* @param _amountArr array of amounts corresponding to index on _addressArr
* @param _includingFees Denotes if fee should be deducted from amount or added to amount
* @return Bool value
*/
function bulkTransfer (address[] memory _addressArr, uint256[] memory _amountArr, bool _includingFees) public returns (bool) {
require(_addressArr.length == _amountArr.length, "Invalid params");
for(uint256 i = 0 ; i < _addressArr.length; i++){
uint256 _value = _amountArr[i];
address _to = _addressArr[i];
privateTransfer(msg.sender, _to, _value, false, _includingFees); // internal method
}
return true;
}
/**
* @notice Standard Approve function
* @dev This suffers from race condition. Use increaseApproval/decreaseApproval instead
* @param _spender The user which is allowed to spend on behalf of msg.sender
* @param _value amount of token allowed
* @return Bool value
*/
function approve(address _spender, uint256 _value) public returns (bool) {
return _approve(msg.sender, _spender, _value);
}
/**
* @notice Increase allowance
* @param _spender The user which is allowed to spend on behalf of msg.sender
* @param _addedValue amount by which allowance needs to be increased
* @return Bool value
*/
function increaseApproval(address _spender, uint256 _addedValue) public returns (bool) {
return _increaseApproval(msg.sender, _spender, _addedValue);
}
/**
* @notice Decrease allowance
* @dev if the _subtractedValue is more than previous allowance, allowance will be set to 0
* @param _spender The user which is allowed to spend on behalf of msg.sender
* @param _subtractedValue amount by which allowance needs to be decreases
* @return Bool value
*/
function decreaseApproval (address _spender, uint256 _subtractedValue) public returns (bool) {
return _decreaseApproval(msg.sender, _spender, _subtractedValue);
}
/**
* @notice Approve and call
* @param _spender The user which is allowed to spend on behalf of msg.sender
* @param _value amount of token allowed
* @param _extraData The extra data that will be send to recipient contract
* @return Bool value
*/
function approveAndCall(address _spender, uint256 _value, bytes memory _extraData) public returns (bool) {
TokenRecipient spender = TokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, address(this), _extraData);
return true;
}else{
return false;
}
}
/**
* @notice Standard transferFrom. Send tokens on behalf of spender
* @dev from must have allowed msg.sender atleast _value to spend
* @param _from Spender which has allowed msg.sender to spend on his behalf
* @param _to Recipient to which tokens are to be transferred
* @param _value The amount of token that will be transferred
* @return Bool value
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_value <= allowed[_from][msg.sender] ,"Insufficient approval");
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
privateTransfer(_from, _to, _value, false, false);
}
////////////////////////////////////////////////////////////////
// Special User functions
////////////////////////////////////////////////////////////////
/**
* @notice Mint function.
* @dev Only minter address is allowed to mint
* @param _to The address to which tokens will be minted
* @param _value No of tokens to be minted
* @param _sawtoothHash The hash on sawtooth blockchain to track complete token generation cycle
* @return Bool value
*/
function mint(address _to, uint256 _value, string memory _sawtoothHash, string memory _orderId)
public
onlyMinter
onlyNonZeroAddress(_to)
onlyValidSawtoothEntry(_sawtoothHash, _orderId)
returns (bool)
{
sawtoothHashMapping[_sawtoothHash][_orderId] = true;
totalSupply = totalSupply.add(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(address(0), _to, _value);
emit MintOrBurn(address(0), _to, _value, _sawtoothHash, _orderId);
return true;
}
/**
* @notice Bulk Mint function.
* @dev Only minter address is allowed to mint
* @param _addressArr The array of address to which tokens will be minted
* @param _amountArr The array of tokens that will be minted
* @param _sawtoothHash The hash on sawtooth blockchain to track complete token generation cycle
* @param _orderId The id of order in sawtooth blockchain
* @return Bool value
*/
function bulkMint (address[] memory _addressArr, uint256[] memory _amountArr, string memory _sawtoothHash, string memory _orderId)
public
onlyMinter
onlyValidSawtoothEntry(_sawtoothHash, _orderId)
returns (bool)
{
require(_addressArr.length == _amountArr.length, "Invalid params");
for(uint256 i = 0; i < _addressArr.length; i++){
uint256 _value = _amountArr[i];
address _to = _addressArr[i];
require(_to != address(0),"Zero address not allowed");
totalSupply = totalSupply.add(_value);
balances[_to] = balances[_to].add(_value);
sawtoothHashMapping[_sawtoothHash][_orderId] = true;
emit Transfer(address(0), _to, _value);
emit MintOrBurn(address(0), _to, _value, _sawtoothHash, _orderId);
}
return true;
}
/**
* @notice Standard burn function.
* @dev Only address allowd can burn
* @param _value No of tokens to be burned
* @param _sawtoothHash The hash on sawtooth blockchain to track gold withdrawal
* @param _orderId The id of order in sawtooth blockchain
* @return Bool value
*/
function burn(uint256 _value, string memory _sawtoothHash, string memory _orderId)
public
canBurn
onlyValidSawtoothEntry(_sawtoothHash, _orderId)
returns (bool)
{
require(balances[msg.sender] >= _value, "Insufficient balance");
sawtoothHashMapping[_sawtoothHash][_orderId] = true;
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Transfer(msg.sender, address(0), _value);
emit MintOrBurn(msg.sender, address(0), _value, _sawtoothHash, _orderId);
return true;
}
/**
* @notice Add/Remove a whitelisted recipient. Token transfer to this address won't be taxed
* @dev Only Deputy owner can call
* @param _users The array of addresses to be whitelisted/blacklisted
* @param _isSpecial true means user will be added; false means user will be removed
* @return Bool value
*/
function updateTaxFreeRecipient(address[] memory _users, bool _isSpecial)
public
onlyDeputyOrOwner
returns (bool)
{
for(uint256 i=0; i<_users.length; i++) {
require(_users[i] != address(0), "Zero address not allowed");
isTaxFreeRecipeint[_users[i]] = _isSpecial;
emit TaxFreeUserUpdate(_users[i], _isSpecial, 'Recipient');
}
return true;
}
/**
* @notice Add/Remove a whitelisted sender. Token transfer from this address won't be taxed
* @dev Only Deputy owner can call
* @param _users The array of addresses to be whitelisted/blacklisted
* @param _isSpecial true means user will be added; false means user will be removed
* @return Bool value
*/
function updateTaxFreeSender(address[] memory _users, bool _isSpecial)
public
onlyDeputyOrOwner
returns (bool)
{
for(uint256 i=0; i<_users.length; i++) {
require(_users[i] != address(0), "Zero address not allowed");
isTaxFreeSender[_users[i]] = _isSpecial;
emit TaxFreeUserUpdate(_users[i], _isSpecial, 'Sender');
}
return true;
}
////////////////////////////////////////////////////////////////
// Only Owner functions
////////////////////////////////////////////////////////////////
/**
* @notice Add Suspense wallet address. This can be updated again in case of suspense contract is upgraded.
* @dev Only owner can call
* @param _suspenseWallet The address suspense wallet
* @return Bool value
*/
function addSuspenseWallet(address _suspenseWallet)
public
onlyOwner
onlyNonZeroAddress(_suspenseWallet)
returns (bool)
{
emit SuspenseWalletUpdated(_suspenseWallet, suspenseWallet);
suspenseWallet = _suspenseWallet;
return true;
}
/**
* @notice Add Minter wallet address. This address will be responsible for minting tokens
* @dev Only owner can call
* @param _minter The address of minter wallet
* @return Bool value
*/
function updateMinter(address _minter)
public
onlyOwner
onlyNonZeroAddress(_minter)
returns (bool)
{
emit MinterUpdated(_minter, minter);
minter = _minter;
return true;
}
/**
* @notice Add/Remove trusted contracts. The trusted contracts will be notified in case of tokens are transferred to them
* @dev Only owner can call and only contract address can be added
* @param _contractAddress The address of trusted contract
* @param _isActive true means whitelited; false means blackkisted
*/
function addTrustedContracts(address _contractAddress, bool _isActive) public onlyDeputyOrOwner {
require(_contractAddress.isContract(), "Only contract address can be added");
trustedContracts[_contractAddress] = _isActive;
emit TrustedContractUpdate(_contractAddress, _isActive);
}
/**
* @notice Update commission to be charged on each token transfer
* @dev Only owner can call
* @param _numerator The numerator of commission
* @param _denominator The denominator of commission
*/
function updateCommssion(uint256 _numerator, uint256 _denominator)
public
onlyDeputyOrOwner
{
commission_denominator = _denominator;
commission_numerator = _numerator;
emit CommssionUpdate(_numerator, _denominator);
}
/**
* @notice Update deputy owner. The Hot wallet version of owner
* @dev Only owner can call
* @param _newDeputyOwner The address of new deputy owner
*/
function updateDeputyOwner(address _newDeputyOwner)
public
onlyOwner
onlyNonZeroAddress(_newDeputyOwner)
{
emit DeputyOwnerUpdated(_newDeputyOwner, deputyOwner);
deputyOwner = _newDeputyOwner;
}
/**
* @notice Update central revenue wallet
* @dev Only owner can call
* @param _newCrw The address of new central revenue wallet
*/
function updateCRW(address _newCrw)
public
onlyOwner
onlyNonZeroAddress(_newCrw)
{
emit CRWUpdated(_newCrw, centralRevenueWallet);
centralRevenueWallet = _newCrw;
}
/**
* @notice Owner can transfer out any accidentally sent ERC20 tokens
* @param _tokenAddress The contract address of ERC-20 compitable token
* @param _value The number of tokens to be transferred to owner
*/
function transferAnyERC20Token(address _tokenAddress, uint256 _value) public onlyOwner {
ERC20Interface(_tokenAddress).safeTransfer(owner, _value);
}
////////////////////////////////////////////////////////////////
// Internal/ Private methods
////////////////////////////////////////////////////////////////
/**
* @notice Internal method to handle transfer logic
* @dev Notifies recipient, if recipient is a trusted contract
* @param _from Sender address
* @param _to Recipient address
* @param _amount amount of tokens to be transferred
* @param _withoutFees If true, commission will not be charged
* @param _includingFees Denotes if fee should be deducted from amount or added to amount
* @return bool
*/
function privateTransfer(address _from, address _to, uint256 _amount, bool _withoutFees, bool _includingFees)
internal
onlyNonZeroAddress(_to)
returns (bool)
{
uint256 _amountToTransfer = _amount;
if(_withoutFees || isTaxFreeTx(_from, _to)) {
require(balances[_from] >= _amount, "Insufficient balance");
_transferWithoutFee(_from, _to, _amountToTransfer);
} else {
uint256 fee = calculateCommission(_amount);
if(_includingFees) {
require(balances[_from] >= _amount, "Insufficient balance");
_amountToTransfer = _amount.sub(fee);
} else {
require(balances[_from] >= _amount.add(fee), "Insufficient balance");
}
if(fee > 0 ) _transferWithoutFee(_from, centralRevenueWallet, fee);
_transferWithoutFee(_from, _to, _amountToTransfer);
}
notifyTrustedContract(_from, _to, _amountToTransfer);
return true;
}
/**
* @notice Internal method to facilitate token approval
* @param _sender The user which allows _spender to spend on his behalf
* @param _spender The user which is allowed to spend on behalf of msg.sender
* @param _value amount of token allowed
* @return Bool value
*/
function _approve(address _sender, address _spender, uint256 _value)
internal returns (bool)
{
allowed[_sender][_spender] = _value;
emit Approval (_sender, _spender, _value);
return true;
}
/**
* @notice Internal method to Increase allowance
* @param _sender The user which allows _spender to spend on his behalf
* @param _spender The user which is allowed to spend on behalf of msg.sender
* @param _addedValue amount by which allowance needs to be increased
* @return Bool value
*/
function _increaseApproval(address _sender, address _spender, uint256 _addedValue)
internal returns (bool)
{
allowed[_sender][_spender] = allowed[_sender][_spender].add(_addedValue);
emit Approval(_sender, _spender, allowed[_sender][_spender]);
return true;
}
/**
* @notice Internal method to Decrease allowance
* @dev if the _subtractedValue is more than previous allowance, allowance will be set to 0
* @param _sender The user which allows _spender to spend on his behalf
* @param _spender The user which is allowed to spend on behalf of msg.sender
* @param _subtractedValue amount by which allowance needs to be decreases
* @return Bool value
*/
function _decreaseApproval (address _sender, address _spender, uint256 _subtractedValue )
internal returns (bool)
{
uint256 oldValue = allowed[_sender][_spender];
if (_subtractedValue > oldValue) {
allowed[_sender][_spender] = 0;
} else {
allowed[_sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(_sender, _spender, allowed[_sender][_spender]);
return true;
}
/**
* @notice Internal method to transfer tokens without commission
* @param _from Sender address
* @param _to Recipient address
* @param _amount amount of tokens to be transferred
* @return Bool value
*/
function _transferWithoutFee(address _from, address _to, uint256 _amount)
private
returns (bool)
{
balances[_from] = balances[_from].sub(_amount);
balances[_to] = balances[_to].add(_amount);
emit Transfer(_from, _to, _amount);
return true;
}
/**
* @notice Notifies recipient about transfer only if recipient is trused contract
* @param _from Sender address
* @param _to Recipient contract address
* @param _value amount of tokens to be transferred
* @return Bool value
*/
function notifyTrustedContract(address _from, address _to, uint256 _value) internal {
// if the contract is trusted, notify it about the transfer
if(trustedContracts[_to]) {
TokenRecipient trustedContract = TokenRecipient(_to);
trustedContract.tokenFallback(_from, _value, '0x');
}
}
////////////////////////////////////////////////////////////////
// Public View functions
////////////////////////////////////////////////////////////////
/**
* @notice Get allowance from token owner to spender
* @param _tokenOwner The token owner
* @param _spender The user which is allowed to spend
* @return uint256 Remaining allowance
*/
function allowance(address _tokenOwner, address _spender) public view returns (uint256 remaining) {
return allowed[_tokenOwner][_spender];
}
/**
* @notice Get balance of user
* @param _tokenOwner User address
* @return uint256 Current token balance
*/
function balanceOf(address _tokenOwner) public view returns (uint256 balance) {
return balances[_tokenOwner];
}
/**
* @notice check transer fee
* @dev Does not checks if sender/recipient is whitelisted
* @param _amount The intended amount of transfer
* @return uint256 Calculated commission
*/
function calculateCommission(uint256 _amount) public view returns (uint256) {
return _amount.mul(commission_numerator).div(commission_denominator).div(100);
}
/**
* @notice Checks if transfer between parties will be taxed or not
* @param _from Sender address
* @param _to Recipient address
* @return bool true if no commission will be charged
*/
function isTaxFreeTx(address _from, address _to) public view returns(bool) {
if(isTaxFreeRecipeint[_to] || isTaxFreeSender[_from]) return true;
else return false;
}
/**
* @notice Prevents contract from accepting ETHs
* @dev Contracts can still be sent ETH with self destruct. If anyone deliberately does that, the ETHs will be lost
*/
function () external payable {
revert("Contract does not accept ethers");
}
}
contract AdvancedOToken is OToken {
mapping(address => mapping(bytes32 => bool)) public tokenUsed; // mapping to track token is used or not
bytes4 public methodWord_transfer = bytes4(keccak256("transfer(address,uint256)"));
bytes4 public methodWord_approve = bytes4(keccak256("approve(address,uint256)"));
bytes4 public methodWord_increaseApproval = bytes4(keccak256("increaseApproval(address,uint256)"));
bytes4 public methodWord_decreaseApproval = bytes4(keccak256("decreaseApproval(address,uint256)"));
constructor(address minter, address crw, address deputyOwner) public OToken(minter, crw, deputyOwner) {
}
/**
*/
function getChainID() public pure returns (uint256) {
uint256 id;
assembly {
id := chainid()
}
return id;
}
/**
* @notice Delegated Bulk transfer. Gas fee will be paid by relayer
* @param message The message that user signed
* @param r Signature component
* @param s Signature component
* @param v Signature component
* @param token The unique token for each delegated function
* @param networkFee The fee that will be paid to relayer for gas fee he spends
* @param _addressArr The array of recipients
* @param _amountArr The array of amounts to be transferred
* @param _includingFees Denotes if fee should be deducted from amount or added to amount
* @return Bool value
*/
function preAuthorizedBulkTransfer(
bytes32 message, bytes32 r, bytes32 s, uint8 v, bytes32 token, uint256 networkFee, address[] memory _addressArr,
uint256[] memory _amountArr, bool _includingFees )
public
returns (bool)
{
require(_addressArr.length == _amountArr.length, "Invalid params");
bytes32 proof = getProofBulkTransfer(
token, networkFee, msg.sender, _addressArr, _amountArr, _includingFees
);
address signer = preAuthValidations(proof, message, token, r, s, v);
// Deduct network fee if broadcaster charges network fee
if (networkFee > 0) {
privateTransfer(signer, msg.sender, networkFee, true, false);
}
// Execute original transfer function
for(uint256 i = 0; i < _addressArr.length; i++){
uint256 _value = _amountArr[i];
address _to = _addressArr[i];
privateTransfer(signer, _to, _value, false, _includingFees);
}
return true;
}
/**
* @notice Delegated transfer. Gas fee will be paid by relayer
* @param message The message that user signed
* @param r Signature component
* @param s Signature component
* @param v Signature component
* @param token The unique token for each delegated function
* @param networkFee The fee that will be paid to relayer for gas fee he spends
* @param to The recipient address
* @param amount The amount to be transferred
* @param includingFees Denotes if fee should be deducted from amount or added to amount
* @return Bool value
*/
function preAuthorizedTransfer(
bytes32 message, bytes32 r, bytes32 s, uint8 v, bytes32 token, uint256 networkFee, address to, uint256 amount, bool includingFees)
public
{
bytes32 proof = getProofTransfer(methodWord_transfer, token, networkFee, msg.sender, to, amount, includingFees);
address signer = preAuthValidations(proof, message, token, r, s, v);
// Deduct network fee if broadcaster charges network fee
if (networkFee > 0) {
privateTransfer(signer, msg.sender, networkFee, true, false);
}
privateTransfer(signer, to, amount, false, includingFees);
}
/**
* @notice Delegated approval. Gas fee will be paid by relayer
* @dev Only approve, increaseApproval and decreaseApproval can be delegated
* @param message The message that user signed
* @param r Signature component
* @param s Signature component
* @param v Signature component
* @param token The unique token for each delegated function
* @param networkFee The fee that will be paid to relayer for gas fee he spends
* @param to The spender address
* @param amount The amount to be allowed
* @return Bool value
*/
function preAuthorizedApproval(
bytes4 methodHash, bytes32 message, bytes32 r, bytes32 s, uint8 v, bytes32 token, uint256 networkFee, address to, uint256 amount)
public
returns (bool)
{
bytes32 proof = getProofApproval (methodHash, token, networkFee, msg.sender, to, amount);
address signer = preAuthValidations(proof, message, token, r, s, v);
// Perform approval
if(methodHash == methodWord_approve) return _approve(signer, to, amount);
else if(methodHash == methodWord_increaseApproval) return _increaseApproval(signer, to, amount);
else if(methodHash == methodWord_decreaseApproval) return _decreaseApproval(signer, to, amount);
}
/**
* @notice Validates the message and signature
* @param proof The message that was expected to be signed by user
* @param message The message that user signed
* @param r Signature component
* @param s Signature component
* @param v Signature component
* @param token The unique token for each delegated function
* @return address Signer of message
*/
function preAuthValidations(bytes32 proof, bytes32 message, bytes32 token, bytes32 r, bytes32 s, uint8 v)
private
returns(address)
{
address signer = getSigner(message, r, s, v);
require(signer != address(0),"Zero address not allowed");
require(!tokenUsed[signer][token],"Token already used");
require(proof == message, "Invalid proof");
tokenUsed[signer][token] = true;
return signer;
}
/**
* @notice Find signer
* @param message The message that user signed
* @param r Signature component
* @param s Signature component
* @param v Signature component
* @return address Signer of message
*/
function getSigner(bytes32 message, bytes32 r, bytes32 s, uint8 v)
public
pure
returns (address)
{
bytes memory prefix = "\x19Ethereum Signed Message:\n32";
bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, message));
address signer = ecrecover(prefixedHash, v, r, s);
return signer;
}
/**
* @notice The message to be signed in case of delegated bulk transfer
* @param token The unique token for each delegated function
* @param networkFee The fee that will be paid to relayer for gas fee he spends
* @param _addressArr The array of recipients
* @param _amountArr The array of amounts to be transferred
* @param _includingFees Denotes if fee should be deducted from amount or added to amount
* @return Bool value
*/
function getProofBulkTransfer(bytes32 token, uint256 networkFee, address broadcaster, address[] memory _addressArr, uint256[] memory _amountArr, bool _includingFees)
public
view
returns (bytes32)
{
bytes32 proof = keccak256(abi.encodePacked(
getChainID(),
bytes4(methodWord_transfer),
address(this),
token,
networkFee,
broadcaster,
_addressArr,
_amountArr,
_includingFees
));
return proof;
}
/**
* @notice Get the message to be signed in case of delegated transfer/approvals
* @param methodHash The method hash for which delegate action in to be performed
* @param token The unique token for each delegated function
* @param networkFee The fee that will be paid to relayer for gas fee he spends
* @param to The recipient or spender
* @param amount The amount to be approved
* @return Bool value
*/
function getProofApproval(bytes4 methodHash, bytes32 token, uint256 networkFee, address broadcaster, address to, uint256 amount)
public
view
returns (bytes32)
{
require(
methodHash == methodWord_approve ||
methodHash == methodWord_increaseApproval ||
methodHash == methodWord_decreaseApproval,
"Method not supported");
bytes32 proof = keccak256(abi.encodePacked(
getChainID(),
bytes4(methodHash),
address(this),
token,
networkFee,
broadcaster,
to,
amount
));
return proof;
}
/**
* @notice Get the message to be signed in case of delegated transfer/approvals
* @param methodHash The method hash for which delegate action in to be performed
* @param token The unique token for each delegated function
* @param networkFee The fee that will be paid to relayer for gas fee he spends
* @param to The recipient or spender
* @param amount The amount to be transferred
* @param includingFees Denotes if fee should be deducted from amount or added to amount
* @return Bool value
*/
function getProofTransfer(bytes4 methodHash, bytes32 token, uint256 networkFee, address broadcaster, address to, uint256 amount, bool includingFees)
public
view
returns (bytes32)
{
require(methodHash == methodWord_transfer, "Method not supported");
bytes32 proof = keccak256(abi.encodePacked(
getChainID(),
bytes4(methodHash),
address(this),
token,
networkFee,
broadcaster,
to,
amount,
includingFees
));
return proof;
}
}
|
Returns whether the target address is a contract This function will return false if invoked during the constructor of a contract, as the code is not actually created until after the constructor finishes. account address to check return whether the target address is a contract/ According to EIP-1052, 0x0 is the value returned for not-yet created accounts and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned for accounts without code, i.e. `keccak256('')` solhint-disable-next-line no-inline-assembly
|
function isContract(address account) internal view returns (bool) {
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
return (codehash != accountHash && codehash != 0x0);
}
| 7,370,494 |
./partial_match/42/0x579AbEEE14a52A4CA6707a4590c524Dc149D56a1/sources/CompoundLeverageModule.sol
|
MANAGER ONLY: Decrease leverage for a given collateral position using an enabled borrow asset that is enabled _setToken Instance of the SetToken _collateralAsset Address of collateral asset (underlying of cToken) _repayAsset Address of asset being repaid _redeemQuantity Quantity of collateral asset to delever _minRepayQuantity Minimum amount of repay asset to receive post trade _tradeAdapterName Name of trade adapter _tradeData Arbitrary data for trade/ Note: for delevering, send quantity is derived from collateral asset and receive quantity is derived from repay asset
|
function delever(
ISetToken _setToken,
address _collateralAsset,
address _repayAsset,
uint256 _redeemQuantity,
uint256 _minRepayQuantity,
string memory _tradeAdapterName,
bytes memory _tradeData
)
external
nonReentrant
onlyManagerAndValidSet(_setToken)
{
ActionInfo memory deleverInfo = _createActionInfo(
_setToken,
_collateralAsset,
_repayAsset,
_redeemQuantity,
_minRepayQuantity,
_tradeAdapterName,
false
);
_validateCommon(deleverInfo);
_redeemUnderlying(deleverInfo.setToken, deleverInfo.collateralCTokenAsset, deleverInfo.notionalSendQuantity);
(uint256 protocolFee, uint256 postTradeRepayQuantity) = _tradeAndHandleFees(
_setToken,
_collateralAsset,
_repayAsset,
deleverInfo.notionalSendQuantity,
deleverInfo.minNotionalReceiveQuantity,
deleverInfo.preTradeReceiveTokenBalance,
deleverInfo.exchangeAdapter,
_tradeData
);
_repayBorrow(deleverInfo.setToken, deleverInfo.borrowCTokenAsset, _repayAsset, postTradeRepayQuantity);
_updateCollateralPosition(
deleverInfo.setToken,
deleverInfo.collateralCTokenAsset,
_getCollateralPosition(deleverInfo.setToken, deleverInfo.collateralCTokenAsset, deleverInfo.setTotalSupply)
);
_updateBorrowPosition(
deleverInfo.setToken,
_repayAsset,
_getBorrowPosition(deleverInfo.setToken, deleverInfo.borrowCTokenAsset, deleverInfo.setTotalSupply)
);
emit LeverageDecreased(
_setToken,
_collateralAsset,
_repayAsset,
deleverInfo.exchangeAdapter,
deleverInfo.notionalSendQuantity,
postTradeRepayQuantity,
protocolFee
);
}
| 3,333,983 |
./full_match/4/0xAF4938ff040cD6F3bfe74051930Dabf9AE5bcDE3/sources/cycloape.sol
|
see the current state of sale
|
function saleState() public view returns(State) {
return saleState_;
}
| 12,299,683 |
pragma solidity ^0.4.24;
import "./ERC20.sol";
import "./OMG_ERC20.sol";
import "./SafeMath.sol";
/**
* @title FeeBurner
* @author Piotr Zelazko <pik694@GitHub>
*
* @dev FeeBurner contract is a part of OmiseGO project and
* provides trustless OMG's buyback and burn mechanism.
*/
contract FeeBurner {
using SafeMath for uint256;
/*
* Events
*/
event ExchangeRateChanged(
address token,
uint blockNo,
uint nominator,
uint denominator
);
/*
* Storage
*/
/*
* @notice the exchange rate is a ratio of OMG tokens to otherTokens
* @notice ratio = OMGTokens/otherTokens = nominator/denominator
*/
struct Rate {
uint nominator;
uint denominator;
}
struct ExchangeRate {
uint blockNo;
Rate rate;
}
address public operator;
OMG_ERC20 public OMGToken;
uint constant public NEW_RATE_MATURITY_MARGIN = 5;
mapping (address => ExchangeRate) public previousExchangeRates;
mapping (address => ExchangeRate) public exchangeRates;
/**
* @dev Constructor
*
* @param _OMGToken address of OMGToken contract
*/
constructor(address _OMGToken)
public
{
require(_OMGToken != address(0));
operator = msg.sender;
OMGToken = OMG_ERC20(_OMGToken);
}
/*
* Public functions
*/
/**
* @dev Receives Eth
*/
function () public payable {}
/**
* @dev Adds support for some token
*
* @notice By setting _token address to 0, support for Ether can be added
*
* @param _token contract address of ERC20 token, or 0 for Ether, which support should be added
* @param _nominator nominator of initial exchange rate. See ExchangeRate struct.
* @param _denominator denominator of initial exchange rate. See ExchangeRate struct.
*/
function addSupportFor(address _token, uint _nominator, uint _denominator)
public
{
require(isOperator(msg.sender));
require(isValidRate(_nominator, _denominator));
require(!isTokenSupported(_token));
ExchangeRate memory exchangeRate = ExchangeRate(block.number, Rate(_nominator, _denominator));
previousExchangeRates[_token] = exchangeRate;
exchangeRates[_token] = exchangeRate;
emit ExchangeRateChanged(_token, block.number, _nominator, _denominator);
}
/**
* @dev Sets new exchange rate for a specified token.
*
* @notice Note that the new rate will automatically take
* effect after NEW_RATE_MATURITY_MARGIN number of blocks.
* @notice Once new rate is set it cannot be changed until it has taken effect.
*
* @param _token contract address of the ERC20 token, which rate is changed
* @param _nominator nominator of the new exchange rate. See ExchangeRate struct.
* @param _denominator denominator of the new exchange rate. See ExchangeRate struct.
*/
function setExchangeRate(address _token, uint _nominator, uint _denominator)
public
{
require(isOperator(msg.sender));
require(isValidRate(_nominator, _denominator));
require(isTokenSupported(_token));
require(checkMaturityPeriodPassed(_token));
previousExchangeRates[_token] = exchangeRates[_token];
exchangeRates[_token] = ExchangeRate(block.number, Rate(_nominator, _denominator));
emit ExchangeRateChanged(_token, block.number, _nominator, _denominator);
}
/**
* @dev Exchanges OMGs for the given token and burns received OMGs
*
* @param _token contract address of ERC20 token, or 0 for Ether
* @param _rate_nominator nominator of the rate at which the user wants to make the exchange
* @param _rate_denominator denominator of the rate at which the user wants to make the exchange
* @param _omg_amount amount of OMGs to be exchanged and burnt
* @param _token_amount amount of ERC20 tokens to be exchanged
*
* @notice Rate proposed by the user must equal either to exchangeRate or to previousExchangeRate.
* @notice Rate cannot equal to the previousExchangeRate when the maturity period of the new rate has passed.
* @notice Sender may offer more OMGs than demanded by the exchange rate, the exchange/transaction is then valid.
*/
function exchange(address _token, uint _rate_nominator, uint _rate_denominator, uint _omg_amount, uint _token_amount)
public
{
require(isTokenSupported(_token));
require(checkRateValidity(_token, _rate_nominator, _rate_denominator));
// Check whether user proposed valid values
require(_omg_amount.mul(_rate_denominator) >= _token_amount.mul(_rate_nominator));
OMGToken.transferFrom(msg.sender, address(0xDEAD), _omg_amount);
if (_token == address(0)){
msg.sender.transfer(_token_amount);
}
else {
ERC20 token = ERC20(_token);
token.transfer(msg.sender, _token_amount);
}
}
/*
* Public view functions
*/
/**
* @dev Returns flat exchange rate of the given token.
*
* @param _token address of an ERC20 token, or 0 in case of Ethereum
*
* @return Newest exchange rate of the token in given format (block when the rate was set, rate's nominator, rate's denominator)
*
* @notice If given token is not supported, then (0, 0, 0) is returned
* @notice Token can surely by exchanged at the returned rate.
*/
function getExchangeRate(address _token)
public
view
returns (uint, uint, uint)
{
ExchangeRate memory exchangeRate = exchangeRates[_token];
return (exchangeRate.blockNo, exchangeRate.rate.nominator, exchangeRate.rate.denominator);
}
/**
* @dev Returns flat previous exchange rate of the given token.
*
* @param _token address of an ERC20 token, or 0 in case of Ethereum
*
* @return Previous exchange rate of the token in given format (block when the rate was set, rate's nominator, rate's denominator)
*
* @notice If given token is not supported, then (0, 0, 0) is returned
* @notice Token can be exchanged at the returned rate only before maturity period of the new rate has passed.
*/
function getPreviousExchangeRate(address _token)
public
view
returns (uint, uint, uint)
{
ExchangeRate memory exchangeRate = previousExchangeRates[_token];
return (exchangeRate.blockNo, exchangeRate.rate.nominator, exchangeRate.rate.denominator);
}
/*
* Private functions
*/
/**
* @notice Should be called having previously checked whether the token is supported
*/
function checkRateValidity(address _token, uint _nominator, uint _denominator)
private
view
returns (bool)
{
Rate memory rate = exchangeRates[_token].rate;
//NOTE : _nominator and _denominator have once been checked against zero values
if (rate.nominator == _nominator && rate.denominator == _denominator){
return true;
}
if (!checkMaturityPeriodPassed(_token)){
rate = previousExchangeRates[_token].rate;
if (rate.nominator == _nominator && rate.denominator == _denominator){
return true;
}
}
return false;
}
/**
* @notice Should be called having previously checked whether the token is supported
*/
function checkMaturityPeriodPassed(address _token)
private
view
returns (bool)
{
uint blockNo = exchangeRates[_token].blockNo;
return blockNo.add(NEW_RATE_MATURITY_MARGIN) <= block.number;
}
function isOperator(address _sender)
private
view
returns (bool)
{
return _sender == operator;
}
function isValidRate(uint _nominator, uint _denominator)
private
pure
returns(bool)
{
return _nominator > 0 && _denominator > 0;
}
function isTokenSupported(address _token)
private
view
returns (bool)
{
return exchangeRates[_token].blockNo != 0;
}
}
|
Returns flat exchange rate of the given token. _token address of an ERC20 token, or 0 in case of Ethereum return Newest exchange rate of the token in given format (block when the rate was set, rate's nominator, rate's denominator) If given token is not supported, then (0, 0, 0) is returned Token can surely by exchanged at the returned rate./
|
function getExchangeRate(address _token)
public
view
returns (uint, uint, uint)
{
ExchangeRate memory exchangeRate = exchangeRates[_token];
return (exchangeRate.blockNo, exchangeRate.rate.nominator, exchangeRate.rate.denominator);
}
| 13,080,339 |
pragma solidity ^0.4.18;
// ----------------------------------------------------------------------------
// 'vevcoin' CROWDSALE token contract
//
// Deployed to : 0xd1510bE4989d96E9c4d7937b80b33D59FC75C36e
// Symbol : vev
// Name : vevcoin
// Total supply: Gazillion
// Decimals : 18
//
// Enjoy.
//
// (c) by Moritz Neto & Daniel Bar with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence.
// ----------------------------------------------------------------------------
// ----------------------------------------------------------------------------
// Safe maths
// ----------------------------------------------------------------------------
contract SafeMath {
function safeAdd(uint a, uint b) internal pure returns (uint c) {
c = a + b;
require(c >= a);
}
function safeSub(uint a, uint b) internal pure returns (uint c) {
require(b <= a);
c = a - b;
}
function safeMul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
require(a == 0 || c / a == b);
}
function safeDiv(uint a, uint b) internal pure returns (uint c) {
require(b > 0);
c = a / b;
}
}
// ----------------------------------------------------------------------------
// ERC Token Standard #20 Interface
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// ----------------------------------------------------------------------------
contract ERC20Interface {
function totalSupply() public constant returns (uint);
function balanceOf(address tokenOwner) public constant returns (uint balance);
function allowance(address tokenOwner, address spender) public constant returns (uint remaining);
function transfer(address to, uint tokens) public returns (bool success);
function approve(address spender, uint tokens) public returns (bool success);
function transferFrom(address from, address to, uint tokens) public returns (bool success);
event Transfer(address indexed from, address indexed to, uint tokens);
event Approval(address indexed tokenOwner, address indexed spender, uint tokens);
}
// ----------------------------------------------------------------------------
// Contract function to receive approval and execute function in one call
//
// Borrowed from MiniMeToken
// ----------------------------------------------------------------------------
contract ApproveAndCallFallBack {
function receiveApproval(address from, uint256 tokens, address token, bytes data) public;
}
// ----------------------------------------------------------------------------
// Owned contract
// ----------------------------------------------------------------------------
contract Owned {
address public owner;
address public newOwner;
event OwnershipTransferred(address indexed _from, address indexed _to);
function Owned() public {
owner = msg.sender;
}
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function transferOwnership(address _newOwner) public onlyOwner {
newOwner = _newOwner;
}
function acceptOwnership() public {
require(msg.sender == newOwner);
OwnershipTransferred(owner, newOwner);
owner = newOwner;
newOwner = address(0);
}
}
// ----------------------------------------------------------------------------
// ERC20 Token, with the addition of symbol, name and decimals and assisted
// token transfers
// ----------------------------------------------------------------------------
contract vevcoin is ERC20Interface, Owned, SafeMath {
string public symbol;
string public name;
uint8 public decimals;
uint public _totalSupply;
uint public startDate;
uint public bonusEnds;
uint public endDate;
mapping(address => uint) balances;
mapping(address => mapping(address => uint)) allowed;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
function vevcoin () public {
symbol = "vev";
name = "vevcoin";
decimals = 18;
bonusEnds = now + 1 weeks;
endDate = now + 7 weeks;
}
// ------------------------------------------------------------------------
// Total supply
// ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) {
return _totalSupply - balances[address(0)];
}
// ------------------------------------------------------------------------
// Get the token balance for account `tokenOwner`
// ------------------------------------------------------------------------
function balanceOf(address tokenOwner) public constant returns (uint balance) {
return balances[tokenOwner];
}
// ------------------------------------------------------------------------
// Transfer the balance from token owner's account to `to` account
// - Owner's account must have sufficient balance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transfer(address to, uint tokens) public returns (bool success) {
balances[msg.sender] = safeSub(balances[msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(msg.sender, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account
//
// https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md
// recommends that there are no checks for the approval double-spend attack
// as this should be implemented in user interfaces
// ------------------------------------------------------------------------
function approve(address spender, uint tokens) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
return true;
}
// ------------------------------------------------------------------------
// Transfer `tokens` from the `from` account to the `to` account
//
// The calling account must already have sufficient tokens approve(...)-d
// for spending from the `from` account and
// - From account must have sufficient balance to transfer
// - Spender must have sufficient allowance to transfer
// - 0 value transfers are allowed
// ------------------------------------------------------------------------
function transferFrom(address from, address to, uint tokens) public returns (bool success) {
balances[from] = safeSub(balances[from], tokens);
allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens);
balances[to] = safeAdd(balances[to], tokens);
Transfer(from, to, tokens);
return true;
}
// ------------------------------------------------------------------------
// Returns the amount of tokens approved by the owner that can be
// transferred to the spender's account
// ------------------------------------------------------------------------
function allowance(address tokenOwner, address spender) public constant returns (uint remaining) {
return allowed[tokenOwner][spender];
}
// ------------------------------------------------------------------------
// Token owner can approve for `spender` to transferFrom(...) `tokens`
// from the token owner's account. The `spender` contract function
// `receiveApproval(...)` is then executed
// ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes data) public returns (bool success) {
allowed[msg.sender][spender] = tokens;
Approval(msg.sender, spender, tokens);
ApproveAndCallFallBack(spender).receiveApproval(msg.sender, tokens, this, data);
return true;
}
// ------------------------------------------------------------------------
// 50 vev Tokens per 1 ETH
// ------------------------------------------------------------------------
function () public payable {
require(now >= startDate && now <= endDate);
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 100;
} else {
tokens = msg.value * 50;
}
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
_totalSupply = safeAdd(_totalSupply, tokens);
Transfer(address(0), msg.sender, tokens);
owner.transfer(msg.value);
}
// ------------------------------------------------------------------------
// Owner can transfer out any accidentally sent ERC20 tokens
// ------------------------------------------------------------------------
function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) {
return ERC20Interface(tokenAddress).transfer(owner, tokens);
}
}
|
------------------------------------------------------------------------ 50 vev Tokens per 1 ETH ------------------------------------------------------------------------
|
function () public payable {
require(now >= startDate && now <= endDate);
uint tokens;
if (now <= bonusEnds) {
tokens = msg.value * 100;
tokens = msg.value * 50;
}
balances[msg.sender] = safeAdd(balances[msg.sender], tokens);
_totalSupply = safeAdd(_totalSupply, tokens);
Transfer(address(0), msg.sender, tokens);
owner.transfer(msg.value);
}
| 7,760,380 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "./interfaces/IOniiChainDescriptor.sol";
import "./interfaces/IOniiChain.sol";
import "./libraries/NFTDescriptor.sol";
import "./libraries/DetailHelper.sol";
import "base64-sol/base64.sol";
/// @title Describes Onii
/// @notice Produces a string containing the data URI for a JSON metadata string
contract OniiChainDescriptor is IOniiChainDescriptor {
/// @dev Max value for defining probabilities
uint256 internal constant MAX = 100000;
uint256[] internal BACKGROUND_ITEMS = [4000, 3400, 3080, 2750, 2400, 1900, 1200, 0];
uint256[] internal SKIN_ITEMS = [2000, 1000, 0];
uint256[] internal NOSE_ITEMS = [10, 0];
uint256[] internal MARK_ITEMS = [50000, 40000, 31550, 24550, 18550, 13550, 9050, 5550, 2550, 550, 50, 10, 0];
uint256[] internal EYEBROW_ITEMS = [65000, 40000, 20000, 10000, 4000, 0];
uint256[] internal MASK_ITEMS = [20000, 14000, 10000, 6000, 2000, 1000, 100, 0];
uint256[] internal EARRINGS_ITEMS = [50000, 38000, 28000, 20000, 13000, 8000, 5000, 2900, 1000, 100, 30, 0];
uint256[] internal ACCESSORY_ITEMS = [
50000,
43000,
36200,
29700,
23400,
17400,
11900,
7900,
4400,
1400,
400,
200,
11,
1,
0
];
uint256[] internal MOUTH_ITEMS = [
80000,
63000,
48000,
36000,
27000,
19000,
12000,
7000,
4000,
2000,
1000,
500,
50,
0
];
uint256[] internal HAIR_ITEMS = [
97000,
94000,
91000,
88000,
85000,
82000,
79000,
76000,
73000,
70000,
67000,
64000,
61000,
58000,
55000,
52000,
49000,
46000,
43000,
40000,
37000,
34000,
31000,
28000,
25000,
22000,
19000,
16000,
13000,
10000,
3000,
1000,
0
];
uint256[] internal EYE_ITEMS = [
98000,
96000,
94000,
92000,
90000,
88000,
86000,
84000,
82000,
80000,
78000,
76000,
74000,
72000,
70000,
68000,
60800,
53700,
46700,
39900,
33400,
27200,
21200,
15300,
10600,
6600,
3600,
2600,
1700,
1000,
500,
100,
10,
0
];
/// @inheritdoc IOniiChainDescriptor
function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view override returns (string memory) {
NFTDescriptor.SVGParams memory params = getSVGParams(oniiChain, tokenId);
params.background = getBackgroundId(params);
string memory image = Base64.encode(bytes(NFTDescriptor.generateSVGImage(params)));
string memory name = NFTDescriptor.generateName(params, tokenId);
string memory description = NFTDescriptor.generateDescription(params);
string memory attributes = NFTDescriptor.generateAttributes(params);
return
string(
abi.encodePacked(
"data:application/json;base64,",
Base64.encode(
bytes(
abi.encodePacked(
'{"name":"',
name,
'", "description":"',
description,
'", "attributes":',
attributes,
', "image": "',
"data:image/svg+xml;base64,",
image,
'"}'
)
)
)
)
);
}
/// @inheritdoc IOniiChainDescriptor
function generateHairId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, HAIR_ITEMS, this.generateHairId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateEyeId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, EYE_ITEMS, this.generateEyeId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateEyebrowId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, EYEBROW_ITEMS, this.generateEyebrowId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateNoseId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, NOSE_ITEMS, this.generateNoseId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateMouthId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, MOUTH_ITEMS, this.generateMouthId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateMarkId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, MARK_ITEMS, this.generateMarkId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateEarringsId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, EARRINGS_ITEMS, this.generateEarringsId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateAccessoryId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, ACCESSORY_ITEMS, this.generateAccessoryId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateMaskId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, MASK_ITEMS, this.generateMaskId.selector, tokenId);
}
/// @inheritdoc IOniiChainDescriptor
function generateSkinId(uint256 tokenId, uint256 seed) external view override returns (uint8) {
return DetailHelper.generate(MAX, seed, SKIN_ITEMS, this.generateSkinId.selector, tokenId);
}
/// @dev Get SVGParams from OniiChain.Detail
function getSVGParams(IOniiChain oniiChain, uint256 tokenId) private view returns (NFTDescriptor.SVGParams memory) {
IOniiChain.Detail memory detail = oniiChain.details(tokenId);
return
NFTDescriptor.SVGParams({
hair: detail.hair,
eye: detail.eye,
eyebrow: detail.eyebrow,
nose: detail.nose,
mouth: detail.mouth,
mark: detail.mark,
earring: detail.earrings,
accessory: detail.accessory,
mask: detail.mask,
skin: detail.skin,
original: detail.original,
background: 0,
timestamp: detail.timestamp,
creator: detail.creator
});
}
function getBackgroundId(NFTDescriptor.SVGParams memory params) private view returns (uint8) {
uint256 score = itemScorePosition(params.hair, HAIR_ITEMS) +
itemScoreProba(params.accessory, ACCESSORY_ITEMS) +
itemScoreProba(params.earring, EARRINGS_ITEMS) +
itemScoreProba(params.mask, MASK_ITEMS) +
itemScorePosition(params.mouth, MOUTH_ITEMS) +
(itemScoreProba(params.skin, SKIN_ITEMS) / 2) +
itemScoreProba(params.skin, SKIN_ITEMS) +
itemScoreProba(params.nose, NOSE_ITEMS) +
itemScoreProba(params.mark, MARK_ITEMS) +
itemScorePosition(params.eye, EYE_ITEMS) +
itemScoreProba(params.eyebrow, EYEBROW_ITEMS);
return DetailHelper.pickItems(score, BACKGROUND_ITEMS);
}
/// @dev Get item score based on his probability
function itemScoreProba(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) {
uint256 raw = ((item == 1 ? MAX : ITEMS[item - 2]) - ITEMS[item - 1]);
return ((raw >= 1000) ? raw * 6 : raw) / 1000;
}
/// @dev Get item score based on his index
function itemScorePosition(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) {
uint256 raw = ITEMS[item - 1];
return ((raw >= 1000) ? raw * 6 : raw) / 1000;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "./IOniiChain.sol";
/// @title Describes Onii via URI
interface IOniiChainDescriptor {
/// @notice Produces the URI describing a particular Onii (token id)
/// @dev Note this URI may be a data: URI with the JSON contents directly inlined
/// @param oniiChain The OniiChain contract
/// @param tokenId The ID of the token for which to produce a description
/// @return The URI of the ERC721-compliant metadata
function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view returns (string memory);
/// @notice Generate randomly an ID for the hair item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the hair item id
function generateHairId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the eye item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the eye item id
function generateEyeId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the eyebrow item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the eyebrow item id
function generateEyebrowId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the nose item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the nose item id
function generateNoseId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the mouth item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the mouth item id
function generateMouthId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the mark item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the mark item id
function generateMarkId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the earrings item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the earrings item id
function generateEarringsId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the accessory item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the accessory item id
function generateAccessoryId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly an ID for the mask item
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the mask item id
function generateMaskId(uint256 tokenId, uint256 seed) external view returns (uint8);
/// @notice Generate randomly the skin colors
/// @param tokenId the current tokenId
/// @param seed Used for the initialization of the number generator.
/// @return the skin item id
function generateSkinId(uint256 tokenId, uint256 seed) external view returns (uint8);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
/// @title OniiChain NFTs Interface
interface IOniiChain {
/// @notice Details about the Onii
struct Detail {
uint8 hair;
uint8 eye;
uint8 eyebrow;
uint8 nose;
uint8 mouth;
uint8 mark;
uint8 earrings;
uint8 accessory;
uint8 mask;
uint8 skin;
bool original;
uint256 timestamp;
address creator;
}
/// @notice Returns the details associated with a given token ID.
/// @dev Throws if the token ID is not valid.
/// @param tokenId The ID of the token that represents the Onii
/// @return detail memory
function details(uint256 tokenId) external view returns (Detail memory detail);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "./details/BackgroundDetail.sol";
import "./details/BodyDetail.sol";
import "./details/HairDetail.sol";
import "./details/MouthDetail.sol";
import "./details/NoseDetail.sol";
import "./details/EyesDetail.sol";
import "./details/EyebrowDetail.sol";
import "./details/MarkDetail.sol";
import "./details/AccessoryDetail.sol";
import "./details/EarringsDetail.sol";
import "./details/MaskDetail.sol";
import "./DetailHelper.sol";
import "@openzeppelin/contracts/utils/Strings.sol";
/// @notice Helper to generate SVGs
library NFTDescriptor {
struct SVGParams {
uint8 hair;
uint8 eye;
uint8 eyebrow;
uint8 nose;
uint8 mouth;
uint8 mark;
uint8 earring;
uint8 accessory;
uint8 mask;
uint8 background;
uint8 skin;
bool original;
uint256 timestamp;
address creator;
}
/// @dev Combine all the SVGs to generate the final image
function generateSVGImage(SVGParams memory params) internal view returns (string memory) {
return
string(
abi.encodePacked(
generateSVGHead(),
DetailHelper.getDetailSVG(address(BackgroundDetail), params.background),
generateSVGFace(params),
DetailHelper.getDetailSVG(address(EarringsDetail), params.earring),
DetailHelper.getDetailSVG(address(HairDetail), params.hair),
DetailHelper.getDetailSVG(address(MaskDetail), params.mask),
DetailHelper.getDetailSVG(address(AccessoryDetail), params.accessory),
generateCopy(params.original),
"</svg>"
)
);
}
/// @dev Combine face items
function generateSVGFace(SVGParams memory params) private view returns (string memory) {
return
string(
abi.encodePacked(
DetailHelper.getDetailSVG(address(BodyDetail), params.skin),
DetailHelper.getDetailSVG(address(MarkDetail), params.mark),
DetailHelper.getDetailSVG(address(MouthDetail), params.mouth),
DetailHelper.getDetailSVG(address(NoseDetail), params.nose),
DetailHelper.getDetailSVG(address(EyesDetail), params.eye),
DetailHelper.getDetailSVG(address(EyebrowDetail), params.eyebrow)
)
);
}
/// @dev generate Json Metadata name
function generateName(SVGParams memory params, uint256 tokenId) internal pure returns (string memory) {
return
string(
abi.encodePacked(
BackgroundDetail.getItemNameById(params.background),
" Onii ",
Strings.toString(tokenId)
)
);
}
/// @dev generate Json Metadata description
function generateDescription(SVGParams memory params) internal pure returns (string memory) {
return
string(
abi.encodePacked(
"Generated by ",
Strings.toHexString(uint256(uint160(params.creator))),
" at ",
Strings.toString(params.timestamp)
)
);
}
/// @dev generate SVG header
function generateSVGHead() private pure returns (string memory) {
return
string(
abi.encodePacked(
'<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"',
' viewBox="0 0 420 420" style="enable-background:new 0 0 420 420;" xml:space="preserve">'
)
);
}
/// @dev generate the "Copy" SVG if the onii is not the original
function generateCopy(bool original) private pure returns (string memory) {
return
!original
? string(
abi.encodePacked(
'<g id="Copy">',
'<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M239.5,300.6c-4.9,1.8-5.9,8.1,1.3,4.1"/>',
'<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M242.9,299.5c-2.6,0.8-1.8,4.3,0.8,4.2 C246.3,303.1,245.6,298.7,242.9,299.5"/>',
'<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M247.5,302.9c0.2-1.6-1.4-4-0.8-5.4 c0.4-1.2,2.5-1.4,3.2-0.3c0.1,1.5-0.9,2.7-2.3,2.5"/>',
'<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M250.6,295.4c1.1-0.1,2.2,0,3.3,0.1 c0.5-0.8,0.7-1.7,0.5-2.7"/>',
'<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M252.5,299.1c0.5-1.2,1.2-2.3,1.4-3.5"/>',
"</g>"
)
)
: "";
}
/// @dev generate Json Metadata attributes
function generateAttributes(SVGParams memory params) internal pure returns (string memory) {
return
string(
abi.encodePacked(
"[",
getJsonAttribute("Body", BodyDetail.getItemNameById(params.skin), false),
getJsonAttribute("Hair", HairDetail.getItemNameById(params.hair), false),
getJsonAttribute("Mouth", MouthDetail.getItemNameById(params.mouth), false),
getJsonAttribute("Nose", NoseDetail.getItemNameById(params.nose), false),
getJsonAttribute("Eyes", EyesDetail.getItemNameById(params.eye), false),
getJsonAttribute("Eyebrow", EyebrowDetail.getItemNameById(params.eyebrow), false),
abi.encodePacked(
getJsonAttribute("Mark", MarkDetail.getItemNameById(params.mark), false),
getJsonAttribute("Accessory", AccessoryDetail.getItemNameById(params.accessory), false),
getJsonAttribute("Earrings", EarringsDetail.getItemNameById(params.earring), false),
getJsonAttribute("Mask", MaskDetail.getItemNameById(params.mask), false),
getJsonAttribute("Background", BackgroundDetail.getItemNameById(params.background), false),
getJsonAttribute("Original", params.original ? "true" : "false", true),
"]"
)
)
);
}
/// @dev Get the json attribute as
/// {
/// "trait_type": "Skin",
/// "value": "Human"
/// }
function getJsonAttribute(
string memory trait,
string memory value,
bool end
) private pure returns (string memory json) {
return string(abi.encodePacked('{ "trait_type" : "', trait, '", "value" : "', value, '" }', end ? "" : ","));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "@openzeppelin/contracts/utils/Strings.sol";
import "@openzeppelin/contracts/utils/math/SafeCast.sol";
/// @title Helper for details generation
library DetailHelper {
/// @notice Call the library item function
/// @param lib The library address
/// @param id The item ID
function getDetailSVG(address lib, uint8 id) internal view returns (string memory) {
(bool success, bytes memory data) = lib.staticcall(
abi.encodeWithSignature(string(abi.encodePacked("item_", Strings.toString(id), "()")))
);
require(success);
return abi.decode(data, (string));
}
/// @notice Generate a random number and return the index from the
/// corresponding interval.
/// @param max The maximum value to generate
/// @param seed Used for the initialization of the number generator
/// @param intervals the intervals
/// @param selector Caller selector
/// @param tokenId the current tokenId
function generate(
uint256 max,
uint256 seed,
uint256[] memory intervals,
bytes4 selector,
uint256 tokenId
) internal view returns (uint8) {
uint256 generated = generateRandom(max, seed, tokenId, selector);
return pickItems(generated, intervals);
}
/// @notice Generate random number between 1 and max
/// @param max Maximum value of the random number
/// @param seed Used for the initialization of the number generator
/// @param tokenId Current tokenId used as seed
/// @param selector Caller selector used as seed
function generateRandom(
uint256 max,
uint256 seed,
uint256 tokenId,
bytes4 selector
) private view returns (uint256) {
return
(uint256(
keccak256(
abi.encodePacked(block.difficulty, block.number, tx.origin, tx.gasprice, selector, seed, tokenId)
)
) % (max + 1)) + 1;
}
/// @notice Pick an item for the given random value
/// @param val The random value
/// @param intervals The intervals for the corresponding items
/// @return the item ID where : intervals[] index + 1 = item ID
function pickItems(uint256 val, uint256[] memory intervals) internal pure returns (uint8) {
for (uint256 i; i < intervals.length; i++) {
if (val > intervals[i]) {
return SafeCast.toUint8(i + 1);
}
}
revert("DetailHelper::pickItems: No item");
}
}
// SPDX-License-Identifier: MIT
/// @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;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Background SVG generator
library BackgroundDetail {
/// @dev background N°1 => Ordinary
function item_1() public pure returns (string memory) {
return base("636363", "CFCFCF", "ABABAB");
}
/// @dev background N°2 => Unusual
function item_2() public pure returns (string memory) {
return base("004A06", "61E89B", "12B55F");
}
/// @dev background N°3 => Surprising
function item_3() public pure returns (string memory) {
return base("1A4685", "6BF0E3", "00ADC7");
}
/// @dev background N°4 => Impressive
function item_4() public pure returns (string memory) {
return base("380113", "D87AE6", "8A07BA");
}
/// @dev background N°5 => Extraordinary
function item_5() public pure returns (string memory) {
return base("A33900", "FAF299", "FF9121");
}
/// @dev background N°6 => Phenomenal
function item_6() public pure returns (string memory) {
return base("000000", "C000E8", "DED52C");
}
/// @dev background N°7 => Artistic
function item_7() public pure returns (string memory) {
return base("FF00E3", "E8E18B", "00C4AD");
}
/// @dev background N°8 => Unreal
function item_8() public pure returns (string memory) {
return base("CCCC75", "54054D", "001E2E");
}
/// @notice Return the background name of the given id
/// @param id The background Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Ordinary";
} else if (id == 2) {
name = "Unusual";
} else if (id == 3) {
name = "Surprising";
} else if (id == 4) {
name = "Impressive";
} else if (id == 5) {
name = "Extraordinary";
} else if (id == 6) {
name = "Phenomenal";
} else if (id == 7) {
name = "Artistic";
} else if (id == 8) {
name = "Unreal";
}
}
/// @dev The base SVG for the backgrounds
function base(
string memory stop1,
string memory stop2,
string memory stop3
) private pure returns (string memory) {
return
string(
abi.encodePacked(
'<g id="Background">',
'<radialGradient id="gradient" cx="210" cy="-134.05" r="210.025" gradientTransform="matrix(1 0 0 -1 0 76)" gradientUnits="userSpaceOnUse">',
"<style>",
".color-anim {animation: col 6s infinite;animation-timing-function: ease-in-out;}",
"@keyframes col {0%,51% {stop-color:none} 52% {stop-color:#FFBAF7} 53%,100% {stop-color:none}}",
"</style>",
"<stop offset='0' class='color-anim' style='stop-color:#",
stop1,
"'/>",
"<stop offset='0.66' style='stop-color:#",
stop2,
"'><animate attributeName='offset' dur='18s' values='0.54;0.8;0.54' repeatCount='indefinite' keyTimes='0;.4;1'/></stop>",
"<stop offset='1' style='stop-color:#",
stop3,
"'><animate attributeName='offset' dur='18s' values='0.86;1;0.86' repeatCount='indefinite'/></stop>",
abi.encodePacked(
"</radialGradient>",
'<path fill="url(#gradient)" d="M390,420H30c-16.6,0-30-13.4-30-30V30C0,13.4,13.4,0,30,0h360c16.6,0,30,13.4,30,30v360C420,406.6,406.6,420,390,420z"/>',
'<path id="Border" opacity="0.4" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-miterlimit="10" d="M383.4,410H36.6C21.9,410,10,398.1,10,383.4V36.6C10,21.9,21.9,10,36.6,10h346.8c14.7,0,26.6,11.9,26.6,26.6v346.8 C410,398.1,398.1,410,383.4,410z"/>',
'<path id="Mask" opacity="0.1" fill="#48005E" d="M381.4,410H38.6C22.8,410,10,397.2,10,381.4V38.6 C10,22.8,22.8,10,38.6,10h342.9c15.8,0,28.6,12.8,28.6,28.6v342.9C410,397.2,397.2,410,381.4,410z"/>',
"</g>"
)
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Body SVG generator
library BodyDetail {
/// @dev Body N°1 => Human
function item_1() public pure returns (string memory) {
return base("FFEBB4", "FFBE94");
}
/// @dev Body N°2 => Shadow
function item_2() public pure returns (string memory) {
return base("2d2d2d", "000000");
}
/// @dev Body N°3 => Light
function item_3() public pure returns (string memory) {
return base("ffffff", "696969");
}
/// @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 = "Human";
} else if (id == 2) {
name = "Shadow";
} else if (id == 3) {
name = "Light";
}
}
/// @dev The base SVG for the body
function base(string memory skin, string memory shadow) private pure returns (string memory) {
string memory pathBase = "<path fill-rule='evenodd' clip-rule='evenodd' fill='#";
string memory strokeBase = "' stroke='#000000' stroke-linecap='round' stroke-miterlimit='10'";
return
string(
abi.encodePacked(
'<g id="Body">',
pathBase,
skin,
strokeBase,
" d='M177.1,287.1c0.8,9.6,0.3,19.3-1.5,29.2c-0.5,2.5-2.1,4.7-4.5,6c-15.7,8.5-41.1,16.4-68.8,24.2c-7.8,2.2-9.1,11.9-2,15.7c69,37,140.4,40.9,215.4,6.7c6.9-3.2,7-12.2,0.1-15.4c-21.4-9.9-42.1-19.7-53.1-26.2c-2.5-1.5-4-3.9-4.3-6.5c-0.7-7.4-0.9-16.1-0.3-25.5c0.7-10.8,2.5-20.3,4.4-28.2'/>",
abi.encodePacked(
pathBase,
shadow,
"' d='M177.1,289c0,0,23.2,33.7,39.3,29.5s40.9-20.5,40.9-20.5c1.2-8.7,2.4-17.5,3.5-26.2c-4.6,4.7-10.9,10.2-19,15.3c-10.8,6.8-21,10.4-28.5,12.4L177.1,289z'/>",
pathBase,
skin,
strokeBase,
" d='M301.3,193.6c2.5-4.6,10.7-68.1-19.8-99.1c-29.5-29.9-96-34-128.1-0.3s-23.7,105.6-23.7,105.6s12.4,59.8,24.2,72c0,0,32.3,24.8,40.7,29.5c8.4,4.8,16.4,2.2,16.4,2.2c15.4-5.7,25.1-10.9,33.3-17.4'/>",
pathBase
),
skin,
strokeBase,
" d='M141.8,247.2c0.1,1.1-11.6,7.4-12.9-7.1c-1.3-14.5-3.9-18.2-9.3-34.5s9.1-8.4,9.1-8.4'/>",
abi.encodePacked(
pathBase,
skin,
strokeBase,
" d='M254.8,278.1c7-8.6,13.9-17.2,20.9-25.8c1.2-1.4,2.9-2.1,4.6-1.7c3.9,0.8,11.2,1.2,12.8-6.7c2.3-11,6.5-23.5,12.3-33.6c3.2-5.7,0.7-11.4-2.2-15.3c-2.1-2.8-6.1-2.7-7.9,0.2c-2.6,4-5,7.9-7.6,11.9'/>",
"<polygon fill-rule='evenodd' clip-rule='evenodd' fill='#",
skin,
"' points='272,237.4 251.4,270.4 260.9,268.6 276.9,232.4'/>",
"<path d='M193.3,196.4c0.8,5.1,1,10.2,1,15.4c0,2.6-0.1,5.2-0.4,7.7c-0.3,2.6-0.7,5.1-1.3,7.6h-0.1c0.1-2.6,0.3-5.1,0.4-7.7c0.2-2.5,0.4-5.1,0.6-7.6c0.1-2.6,0.2-5.1,0.1-7.7C193.5,201.5,193.4,198.9,193.3,196.4L193.3,196.4z'/>",
"<path fill='#",
shadow
),
"' d='M197.8,242.8l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198.1,242.9,197.9,242.9,197.8,242.8z'/>",
"</g>"
)
);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
import "./constants/Colors.sol";
/// @title Hair SVG generator
library HairDetail {
/// @dev Hair N°1 => Classic Brown
function item_1() public pure returns (string memory) {
return base(classicHairs(Colors.BROWN));
}
/// @dev Hair N°2 => Classic Black
function item_2() public pure returns (string memory) {
return base(classicHairs(Colors.BLACK));
}
/// @dev Hair N°3 => Classic Gray
function item_3() public pure returns (string memory) {
return base(classicHairs(Colors.GRAY));
}
/// @dev Hair N°4 => Classic White
function item_4() public pure returns (string memory) {
return base(classicHairs(Colors.WHITE));
}
/// @dev Hair N°5 => Classic Blue
function item_5() public pure returns (string memory) {
return base(classicHairs(Colors.BLUE));
}
/// @dev Hair N°6 => Classic Yellow
function item_6() public pure returns (string memory) {
return base(classicHairs(Colors.YELLOW));
}
/// @dev Hair N°7 => Classic Pink
function item_7() public pure returns (string memory) {
return base(classicHairs(Colors.PINK));
}
/// @dev Hair N°8 => Classic Red
function item_8() public pure returns (string memory) {
return base(classicHairs(Colors.RED));
}
/// @dev Hair N°9 => Classic Purple
function item_9() public pure returns (string memory) {
return base(classicHairs(Colors.PURPLE));
}
/// @dev Hair N°10 => Classic Green
function item_10() public pure returns (string memory) {
return base(classicHairs(Colors.GREEN));
}
/// @dev Hair N°11 => Classic Saiki
function item_11() public pure returns (string memory) {
return base(classicHairs(Colors.SAIKI));
}
/// @dev Hair N°12 => Classic 2 Brown
function item_12() public pure returns (string memory) {
return base(classicTwoHairs(Colors.BROWN));
}
/// @dev Hair N°13 => Classic 2 Black
function item_13() public pure returns (string memory) {
return base(classicTwoHairs(Colors.BLACK));
}
/// @dev Hair N°14 => Classic 2 Gray
function item_14() public pure returns (string memory) {
return base(classicTwoHairs(Colors.GRAY));
}
/// @dev Hair N°15 => Classic 2 White
function item_15() public pure returns (string memory) {
return base(classicTwoHairs(Colors.WHITE));
}
/// @dev Hair N°16 => Classic 2 Blue
function item_16() public pure returns (string memory) {
return base(classicTwoHairs(Colors.BLUE));
}
/// @dev Hair N°17 => Classic 2 Yellow
function item_17() public pure returns (string memory) {
return base(classicTwoHairs(Colors.YELLOW));
}
/// @dev Hair N°18 => Classic 2 Pink
function item_18() public pure returns (string memory) {
return base(classicTwoHairs(Colors.PINK));
}
/// @dev Hair N°19 => Classic 2 Red
function item_19() public pure returns (string memory) {
return base(classicTwoHairs(Colors.RED));
}
/// @dev Hair N°20 => Classic 2 Purple
function item_20() public pure returns (string memory) {
return base(classicTwoHairs(Colors.PURPLE));
}
/// @dev Hair N°21 => Classic 2 Green
function item_21() public pure returns (string memory) {
return base(classicTwoHairs(Colors.GREEN));
}
/// @dev Hair N°22 => Classic 2 Saiki
function item_22() public pure returns (string memory) {
return base(classicTwoHairs(Colors.SAIKI));
}
/// @dev Hair N°23 => Short Black
function item_23() public pure returns (string memory) {
return base(shortHairs(Colors.BLACK));
}
/// @dev Hair N°24 => Short Blue
function item_24() public pure returns (string memory) {
return base(shortHairs(Colors.BLUE));
}
/// @dev Hair N°25 => Short Pink
function item_25() public pure returns (string memory) {
return base(shortHairs(Colors.PINK));
}
/// @dev Hair N°26 => Short White
function item_26() public pure returns (string memory) {
return base(shortHairs(Colors.WHITE));
}
/// @dev Hair N°27 => Spike Black
function item_27() public pure returns (string memory) {
return base(spike(Colors.BLACK));
}
/// @dev Hair N°28 => Spike Blue
function item_28() public pure returns (string memory) {
return base(spike(Colors.BLUE));
}
/// @dev Hair N°29 => Spike Pink
function item_29() public pure returns (string memory) {
return base(spike(Colors.PINK));
}
/// @dev Hair N°30 => Spike White
function item_30() public pure returns (string memory) {
return base(spike(Colors.WHITE));
}
/// @dev Hair N°31 => Monk
function item_31() public pure returns (string memory) {
return base(monk());
}
/// @dev Hair N°32 => Nihon
function item_32() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
monk(),
'<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d=" M287.5,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6 c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3 S111,72.1,216.8,70.4c108.4-1.7,87.1,121.7,85.1,122.4C295.4,190.1,293.9,197.7,287.5,206.8z"/>',
'<g opacity="0.33">',
'<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.367 227.089)" fill="#FFFFFF" cx="274.3" cy="113.1" rx="1.4" ry="5.3"/>',
'<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.4151 255.0608)" fill="#FFFFFF" cx="254.1" cy="97.3" rx="4.2" ry="16.3"/>',
"</g>",
'<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M136.2,125.1c0,0,72,9.9,162.2,0c0,0,4.4,14.9,4.8,26.6 c0,0-125.4,20.9-172.6-0.3C129.5,151.3,132.9,130.3,136.2,125.1z"/>',
'<polygon fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" points="306.2,138 324.2,168.1 330,160"/>',
'<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M298.4,125.1l34.2,54.6l-18,15.5l-10.7-43.5 C302.3,142.2,299.9,128.8,298.4,125.1z"/>',
'<ellipse opacity="0.87" fill="#FF0039" cx="198.2" cy="144.1" rx="9.9" ry="10.8"/>'
)
)
);
}
/// @dev Hair N°33 => Bald
function item_33() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1733 226.5807)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>',
'<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.1174 254.4671)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>'
)
)
);
}
/// @dev Generate classic hairs with the given color
function classicHairs(string memory hairsColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<path fill='#",
hairsColor,
"' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M252.4,71.8c0,0-15.1-13.6-42.6-12.3l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9c0,0-2.9,15.4-1.1,29.6c0,0,6.8-23.5,16.9-36.8c0,0-4.6,15.6-2.7,31.9c0,0,9.4-26.2,10.4-28.2l-2.7,9.2c0,0,4.1,21.6,3.8,25.3c0,0,8.4-10.3,21.2-52l-2.9,12c0,0,9.8,20.3,10.3,22.2s-1.3-13.9-1.3-13.9s12.4,21.7,13.5,26c0,0,5.5-20.8,3.4-35.7l1.1,9.6c0,0,15,20.3,16.4,30.1s-0.1-23.4-0.1-23.4s13.8,30.6,17,39.4c0,0,1.9-17,1.4-19.4s8.5,34.6,4.4,46c0,0,11.7-16.4,11.5-21.4c1.4,0.8-1.3,22.6-4,26.3c0,0,3.2-0.3,8.4-9.3c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2C286.5,78.8,271.5,66.7,252.4,71.8z'/>",
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286,210c0,0,8.5-10.8,8.6-18.7"/>',
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M132.5,190.4c0,0-1.3-11.3,0.3-16.9"/>',
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M141.5,170c0,0-1-6.5,1.6-20.4"/>',
'<path opacity="0.2" d="M267.7,151.7l-0.3,30.9c0,0,1.9-18.8,1.8-19.3s8.6,43.5,3.9,47.2c0,0,11.9-18.8,12.1-21.5s0,22-3.9,25c0,0,6-4.4,8.6-10.1c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1c0,0-6.8-22.7-11.4-26.5c0,0,0.7,17.4-3.6,23.2C284.5,183.3,280.8,169.9,267.7,151.7z"/>',
'<path opacity="0.2" d="M234.3,137.1c0,0,17.1,23.2,16.7,30.2s-0.2-13.3-0.2-13.3s-11.7-22-17.6-26.2L234.3,137.1z"/>',
'<polygon opacity="0.2" points="250.7,143.3 267.5,162.9 267.3,181.9"/>',
'<path opacity="0.2" d="M207.4,129.2l9.7,20.7l-1-13.7c0,0,11.6,21,13.5,25.4l1.4-5l-17.6-27.4l1,7.5l-6-12.6L207.4,129.2z"/>',
'<path opacity="0.2" d="M209.2,118c0,0-13.7,36.6-18.5,40.9c-1.7-7.2-1.9-7.9-4.2-20.3c0,0-0.1,2.7-1.4,5.3c0.7,8.2,4.1,24.4,4,24.5S206.4,136.6,209.2,118z"/>',
'<path opacity="0.2" d="M187.6,134.7c0,0-9.6,25.5-10,26.9l-0.4-3.6C177.1,158.1,186.8,135.8,187.6,134.7z"/>',
'<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.7,129.6c0,0-16.7,22.3-17.7,24.2s0,12.4,0.3,12.8S165.9,153,180.7,129.6z"/>',
'<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.4,130.6c0,0-0.2,20.5-0.6,21.5c-0.4,0.9-2.6,5.8-2.6,5.8S176.1,147.1,180.4,130.6z"/>',
abi.encodePacked(
'<path opacity="0.2" d="M163.9,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L163.9,138z"/>',
'<path fill="#FFFFFF" d="M204,82.3c0,0-10.3,24.4-11.5,30.4c0,0,11.1-20.6,12.6-20.8c0,0,11.4,20.4,12,22.2C217.2,114.1,208.2,88.2,204,82.3z"/>',
'<path fill="#FFFFFF" d="M185.6,83.5c0,0-1,29.2,0,39.2c0,0-4-21.4-3.6-25.5c0.4-4-13.5,19.6-16,23.9c0,0,7.5-20.6,10.5-25.8c0,0-14.4,9.4-22,21.3C154.6,116.7,170.1,93.4,185.6,83.5z"/>',
'<path fill="#FFFFFF" d="M158.6,96.2c0,0-12,15.3-14.7,23.2"/>',
'<path fill="#FFFFFF" d="M125.8,125.9c0,0,9.5-20.6,23.5-27.7"/>',
'<path fill="#FFFFFF" d="M296.5,121.6c0,0-9.5-20.6-23.5-27.7"/>',
'<path fill="#FFFFFF" d="M216.1,88.5c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>',
'<path fill="#FFFFFF" d="M227,92c0,0,21.1,25.4,22,27.4s-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9C246.3,113,233.1,94.1,227,92z"/>',
'<path fill="#FFFFFF" d="M263.1,119.5c0,0-9.5-26.8-10.6-28.3s15.5,14.1,16.2,22.5c0,0-11.1-16.1-11.8-16.9C256.1,96,264.3,114.1,263.1,119.5z"/>'
)
)
);
}
/// @dev Generate classic 2 hairs with the given color
function classicTwoHairs(string memory hairsColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<polygon fill='#",
hairsColor,
"' points='188.2,124.6 198.3,128.1 211.2,124.3 197.8,113.2'/>",
'<polygon opacity="0.5" points="188.4,124.7 198.3,128.1 211.7,124.2 197.7,113.6"/>',
"<path fill='#",
hairsColor,
"' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M274,209.6c1,0.9,10.1-12.8,10.5-18.3 c1.1,3.2-0.2,16.8-2.9,20.5c0,0,3.7-0.7,8.3-6.5c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6 c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8 c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2c-0.1-0.1-15.1-12.2-34.2-7.1c0,0-15.1-13.6-42.6-12.3 l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2 c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2 c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9 c0,0-2.9,15.4-1.1,29.6c0,0,7.2-26.8,17.3-40.1c0,0,0.8,0.1,17.6-7.6c6.3,3.1,8,1.4,17.9,7.7c4.1,5.3,13.8,31.9,15.6,41.5 c3.4-7.3,5.6-19,5.2-29.5c2.7,3.7,8.9,19.9,9.6,34.3c0,0,7.9-15.9,5.9-29c0-0.2,0.2,14.5,0.3,14.3c0,0,12.1,19.9,14.9,19.7 c0-0.8-1.7-12.9-1.7-12.8c1.3,5.8,2.8,23.3,3.1,27.1l5-9.5C276.2,184,276.8,204.9,274,209.6z'/>",
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286.7,210c0,0,8.5-10.8,8.6-18.7"/>',
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M133.2,190.4 c0,0-1.3-11.3,0.3-16.9"/>',
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M142.2,170 c0,0-1-6.5,1.6-20.4"/>',
'<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.6,128.2 c0,0-15.9,23.7-16.9,25.6s0,12.4,0.3,12.8S165.8,151.6,180.6,128.2z"/>',
'<path opacity="0.2" d="M164.6,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17 c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7 c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L164.6,138z"/>',
'<path opacity="0.16" d="M253.3,155.9c0.8,4.4,8.1,12.1,13.1,11.7l1.6,11c0,0-5.2-3.9-14.7-19.9 V155.9z"/>',
'<path opacity="0.16" d="M237.6,139.4c0,0,4.4,3,13.9,21.7c0,0-4.3,12-4.6,12.4 C246.6,173.9,248.5,162.8,237.6,139.4z"/>',
'<path opacity="0.17" d="M221,136.7c0,0,5.2,4,14.4,23c0,0-1.2,4.6-3.1,8.9 C227.7,152.4,227.1,149.9,221,136.7z"/>',
'<path opacity="0.2" d="M272.1,152.6c-2.4,8.1-3.6,13.8-4.9,17.9c0,0,1.3,12.8,2.1,22.2 c4.7-8.4,5.4-8.8,5.4-9c-0.1-0.5,3.6,11.2-0.7,25.9c1.6,1,13.3-16.9,11.9-20.6c-1-2.5-0.4,19.8-4.3,22.8c0,0,6.4-2.2,9-7.9 c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1 c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1 c0,0-6.8-22.7-11.4-26.5c0,0-1.8,15.7-5,22.9C283.7,183,280.5,166.7,272.1,152.6z"/>'
),
abi.encodePacked(
'<path opacity="0.14" d="M198.2,115.2c-0.9-3.9,3.2-35.1,34.7-36C227.6,78.5,198.9,99.8,198.2,115.2z"/>',
'<g opacity="0.76">',
'<path fill="#FFFFFF" d="M153,105.9c0,0-12,15.3-14.7,23.2"/>',
'<path fill="#FFFFFF" d="M126.5,125.9c0,0,9.5-20.6,23.5-27.7"/>',
'<path fill="#FFFFFF" d="M297.2,121.6c0,0-9.5-20.6-23.5-27.7"/>',
'<path fill="#FFFFFF" d="M241.9,109.4c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>',
'<path fill="#FFFFFF" d="M155.1,117.3c0,0-10.9,19.9-11.6,23.6s-3.7-5.5,10.6-23.6"/>',
'<path fill="#FFFFFF" d="M256.1,101.5c0,0,21.1,25.4,22,27.4c0.9,2-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9 C275.4,122.5,262.2,103.6,256.1,101.5z"/>',
'<path fill="#FFFFFF" d="M230,138.5c0,0-12.9-24.9-14.1-26.4c-1.2-1.4,18.2,11.9,19.3,20.2c0,0-11.9-13-12.7-13.7 C221.8,117.9,230.9,133,230,138.5z"/>',
'<path fill="#FFFFFF" d="M167,136.6c0,0,15.5-24.5,17-25.8c1.5-1.2-19.1,10.6-21.6,18.8c0,0,15-13.5,15.8-14.2 C179.2,114.8,166.8,130.9,167,136.6z"/>',
"</g>"
)
)
);
}
/// @dev Generate mohawk with the given color
function spike(string memory hairsColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<path fill='#",
hairsColor,
"' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>",
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M196,124.6c0,0-30.3-37.5-20.6-77.7c0,0,0.7,18,12,25.1c0,0-8.6-13.4-0.3-33.4c0,0,2.7,15.8,10.7,23.4c0,0-2.7-18.4,2.2-29.6c0,0,9.7,23.2,13.9,26.3c0,0-6.5-17.2,5.4-27.7c0,0-0.8,18.6,9.8,25.4c0,0-2.7-11,4-18.9c0,0,1.2,25.1,6.6,29.4c0,0-2.7-12,2.1-20c0,0,6,24,8.6,28.5c-9.1-2.6-17.9-3.2-26.6-3C223.7,72.3,198,80.8,196,124.6z"/>',
crop()
)
);
}
function shortHairs(string memory hairsColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<path fill='#",
hairsColor,
"' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>",
'<path fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M134.9,129.3c1-8.7,2.8-19.9,2.6-24.1 c1.1,2,4.4,6.1,4.7,6.9c2-15.1,3.9-18.6,6.6-28.2c0.1,5.2,0.4,6.1,4.6,11.9c0.1-7,4.5-17.6,8.8-24.3c0.6,3,4,8.2,5.8,10.7 c2.4-7,8.6-13.4,14.5-17.9c-0.3,3.4-0.1,6.8,0.7,10.1c4.9-5.1,7.1-8.7,15.6-15.4c-0.2,4.5,1.8,9,5.1,12c4.1-3.7,7.7-8,10.6-12.7 c0.6,3.7,1.4,7.3,2.5,10.8c2.6-4.6,7.9-8.4,12.4-11.3c1.5,3.5,1.3,11,5.9,11.7c7.1,1.1,10-3.3,11.4-10.1 c2.2,6.6,4.8,12.5,9.4,17.7c4.2,0.5,5.7-5.6,4.2-9c4.2,5.8,8.4,11.6,12.5,17.4c0.7-2.9,0.9-5.9,0.6-8.8 c3.4,7.6,9.1,16.7,13.6,23.6c0-1.9,1.8-8.5,1.8-10.4c2.6,7.3,7.7,17.9,10.3,36.6c0.2,1.1-23.8,7.5-28.8,10.1 c-1.2-2.3-2.2-4.3-6.2-8c-12.1-5.7-35.6-7.9-54.5-2.2c-16.3,4.8-21.5-2.3-31.3-3.1c-11.8-1.8-31.1-1.7-36.2,10.7 C139.6,133.6,137.9,132.2,134.9,129.3z"/>',
'<polygon fill="#212121" points="270.7,138.4 300.2,129 300.7,131.1 271.3,139.9"/>',
'<polygon fill="#212121" points="141.1,137 134,131.7 133.8,132.9 140.8,137.7 "/>',
crop()
)
);
}
/// @dev Generate crop SVG
function crop() private pure returns (string memory) {
return
string(
abi.encodePacked(
'<g id="Light" opacity="0.14">',
'<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>',
'<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>',
"</g>",
'<path opacity="0.05" fill-rule="evenodd" clip-rule="evenodd" d="M276.4,163.7c0,0,0.2-1.9,0.2,14.1c0,0,6.5,7.5,8.5,11s2.6,17.8,2.6,17.8l7-11.2c0,0,1.8-3.2,6.6-2.6c0,0,5.6-13.1,2.2-42.2C303.5,150.6,294.2,162.1,276.4,163.7z"/>',
'<path opacity="0.1" fill-rule="evenodd" clip-rule="evenodd" d="M129.2,194.4c0,0-0.7-8.9,6.8-20.3c0,0-0.2-21.2,1.3-22.9c-3.7,0-6.7-0.5-7.7-2.4C129.6,148.8,125.8,181.5,129.2,194.4z"/>'
)
);
}
/// @dev Generate monk SVG
function monk() private pure returns (string memory) {
return
string(
abi.encodePacked(
'<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d="M286.8,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3S110.3,72.1,216.1,70.4c108.4-1.7,87.1,121.7,85.1,122.4C294.7,190.1,293.2,197.7,286.8,206.8z"/>',
'<g id="Bald" opacity="0.33">',
'<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>',
'<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>',
"</g>"
)
);
}
/// @notice Return the hair cut name of the given id
/// @param id The hair Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Classic Brown";
} else if (id == 2) {
name = "Classic Black";
} else if (id == 3) {
name = "Classic Gray";
} else if (id == 4) {
name = "Classic White";
} else if (id == 5) {
name = "Classic Blue";
} else if (id == 6) {
name = "Classic Yellow";
} else if (id == 7) {
name = "Classic Pink";
} else if (id == 8) {
name = "Classic Red";
} else if (id == 9) {
name = "Classic Purple";
} else if (id == 10) {
name = "Classic Green";
} else if (id == 11) {
name = "Classic Saiki";
} else if (id == 12) {
name = "Classic Brown";
} else if (id == 13) {
name = "Classic 2 Black";
} else if (id == 14) {
name = "Classic 2 Gray";
} else if (id == 15) {
name = "Classic 2 White";
} else if (id == 16) {
name = "Classic 2 Blue";
} else if (id == 17) {
name = "Classic 2 Yellow";
} else if (id == 18) {
name = "Classic 2 Pink";
} else if (id == 19) {
name = "Classic 2 Red";
} else if (id == 20) {
name = "Classic 2 Purple";
} else if (id == 21) {
name = "Classic 2 Green";
} else if (id == 22) {
name = "Classic 2 Saiki";
} else if (id == 23) {
name = "Short Black";
} else if (id == 24) {
name = "Short Blue";
} else if (id == 25) {
name = "Short Pink";
} else if (id == 26) {
name = "Short White";
} else if (id == 27) {
name = "Spike Black";
} else if (id == 28) {
name = "Spike Blue";
} else if (id == 29) {
name = "Spike Pink";
} else if (id == 30) {
name = "Spike White";
} else if (id == 31) {
name = "Monk";
} else if (id == 32) {
name = "Nihon";
} else if (id == 33) {
name = "Bald";
}
}
/// @dev The base SVG for the hair
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Hair">', children, "</g>"));
}
}
// 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(
string(
abi.encodePacked(
'<path d="M178.3,262.7c3.3-0.2,6.6-0.1,9.9,0c3.3,0.1,6.6,0.3,9.8,0.8c-3.3,0.3-6.6,0.3-9.9,0.2C184.8,263.6,181.5,263.3,178.3,262.7z"/>',
'<path d="M201.9,263.4c1.2-0.1,2.3-0.1,3.5-0.2l3.5-0.2l6.9-0.3c2.3-0.1,4.6-0.2,6.9-0.4c1.2-0.1,2.3-0.2,3.5-0.3l1.7-0.2c0.6-0.1,1.1-0.2,1.7-0.2c-2.2,0.8-4.5,1.1-6.8,1.4s-4.6,0.5-7,0.6c-2.3,0.1-4.6,0.2-7,0.1C206.6,263.7,204.3,263.6,201.9,263.4z"/>',
'<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>'
)
)
);
}
/// @dev Mouth N°2 => Smile
function item_2() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M178.2,259.6c1.6,0.5,3.3,0.9,4.9,1.3c1.6,0.4,3.3,0.8,4.9,1.1c1.6,0.4,3.3,0.6,4.9,0.9c1.7,0.3,3.3,0.4,5,0.6c-1.7,0.2-3.4,0.3-5.1,0.2c-1.7-0.1-3.4-0.3-5.1-0.7C184.5,262.3,181.2,261.2,178.2,259.6z"/>',
'<path d="M201.9,263.4l7-0.6c2.3-0.2,4.7-0.4,7-0.7c2.3-0.2,4.6-0.6,6.9-1c0.6-0.1,1.2-0.2,1.7-0.3l1.7-0.4l1.7-0.5l1.6-0.7c-0.5,0.3-1,0.7-1.5,0.9l-1.6,0.8c-1.1,0.4-2.2,0.8-3.4,1.1c-2.3,0.6-4.6,1-7,1.3s-4.7,0.4-7.1,0.5C206.7,263.6,204.3,263.6,201.9,263.4z"/>',
'<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>'
)
)
);
}
/// @dev Mouth N°3 => Sulk
function item_3() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M179.2,263.2c0,0,24.5,3.1,43.3-0.6"/>',
'<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M176.7,256.8c0,0,6.7,6.8-0.6,11"/>',
'<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M225.6,256.9c0,0-6.5,7,1,11"/>'
)
)
);
}
/// @dev Mouth N°4 => Poker
function item_4() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line id="Poker" fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="180" y1="263" x2="226" y2="263"/>'
)
)
);
}
/// @dev Mouth N°5 => Angry
function item_5() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M207.5,257.1c-7,1.4-17.3,0.3-21-0.9c-4-1.2-7.7,3.1-8.6,7.2c-0.5,2.5-1.2,7.4,3.4,10.1c5.9,2.4,5.6,0.1,9.2-1.9c3.4-2,10-1.1,15.3,1.9c5.4,3,13.4,2.2,17.9-0.4c2.9-1.7,3.3-7.6-4.2-14.1C217.3,257.2,215.5,255.5,207.5,257.1"/>',
'<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M205.9,265.5l4.1-2.2c0,0,3.7,2.9,5,3s4.9-3.2,4.9-3.2l3.9,1.4"/>',
'<polyline fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="177.8,265.3 180.2,263.4 183.3,265.5 186,265.4"/>'
)
)
);
}
/// @dev Mouth N°6 => Big Smile
function item_6() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M238.1,255.9c-26.1,4-68.5,0.3-68.5,0.3C170.7,256.3,199.6,296.4,238.1,255.9"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M176.4,262.7c0,0,7.1,2.2,12,2.1"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M230.6,262.8c0,0-10.4,2.1-17.7,1.8"/>'
)
)
);
}
/// @dev Mouth N°7 => Evil
function item_7() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M174.7,261.7c0,0,16.1-1.1,17.5-1.5s34.5,6.3,36.5,5.5s4.6-1.9,4.6-1.9s-14.1,8-43.6,7.9c0,0-3.9-0.7-4.7-1.8S177.1,262.1,174.7,261.7z"/>',
'<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="181.6,266.7 185.5,265.3 189.1,266.5 190.3,265.9"/>',
'<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="198.2,267 206.3,266.2 209.6,267.7 213.9,266.3 216.9,267.5 225.3,267"/>'
)
)
);
}
/// @dev Mouth N°8 => Tongue
function item_8() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FF155D" d="M206.5,263.1c0,0,4,11.2,12.5,9.8c11.3-1.8,6.3-11.8,6.3-11.8L206.5,263.1z"/>',
'<line fill="none" stroke="#73093E" stroke-miterlimit="10" x1="216.7" y1="262.5" x2="218.5" y2="267.3"/>',
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M201.9,263.4c0,0,20.7,0.1,27.7-4.3"/>',
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M178.2,259.6c0,0,9.9,4.2,19.8,3.9"/>'
)
)
);
}
/// @dev Mouth N°9 => Drool
function item_9() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FEBCA6" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M190.4,257.5c2.5,0.6,5.1,0.8,7.7,0.5l17-2.1c0,0,13.3-1.8,12,3.6c-1.3,5.4-2.4,9.3-5.3,9.8c0,0,3.2,9.7-2.9,9c-3.7-0.4-2.4-7.7-2.4-7.7s-15.4,4.6-33.1-1.7c-1.8-0.6-3.6-2.6-4.4-3.9c-5.1-7.7-2-9.5-2-9.5S175.9,253.8,190.4,257.5z"/>'
)
)
);
}
/// @dev Mouth N°10 => O
function item_10() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<ellipse transform="matrix(0.9952 -9.745440e-02 9.745440e-02 0.9952 -24.6525 20.6528)" opacity="0.84" fill-rule="evenodd" clip-rule="evenodd" cx="199.1" cy="262.7" rx="3.2" ry="4.6"/>'
)
)
);
}
/// @dev Mouth N°11 => Dubu
function item_11() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-miterlimit="10" d="M204.2,262c-8.9-7-25.1-3.5-4.6,6.6c-22-3.8-3.2,11.9,4.8,6"/>'
)
)
);
}
/// @dev Mouth N°12 => Stitch
function item_12() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<g opacity="0.84" fill-rule="evenodd" clip-rule="evenodd">',
'<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8992 6.2667)" cx="179.6" cy="264.5" rx="2.3" ry="4.3"/>',
'<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.485 5.0442)" cx="172.2" cy="263.6" rx="1.5" ry="2.9"/>',
'<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.4594 6.6264)" cx="227.4" cy="263.5" rx="1.5" ry="2.9"/>',
'<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8828 7.6318)" cx="219.7" cy="264.7" rx="2.5" ry="4.7"/>',
'<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9179 6.57)" cx="188.5" cy="265.2" rx="2.9" ry="5.4"/>',
'<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9153 7.3225)" cx="210.6" cy="265.5" rx="2.9" ry="5.4"/>',
'<ellipse transform="matrix(0.9992 -3.983298e-02 3.983298e-02 0.9992 -10.4094 8.1532)" cx="199.4" cy="265.3" rx="4" ry="7.2"/>',
"</g>"
)
)
);
}
/// @dev Mouth N°13 => Uwu
function item_13() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<polyline fill="#FFFFFF" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" points="212.7,262.9 216,266.5 217.5,261.7"/>',
'<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M176.4,256c0,0,5.7,13.4,23.1,4.2"/>',
'<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M224.7,254.8c0,0-9.5,15-25.2,5.4"/>'
)
)
);
}
/// @dev Mouth N°14 => Monster
function item_14() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M161.4,255c0,0,0.5,0.1,1.3,0.3 c4.2,1,39.6,8.5,84.8-0.7C247.6,254.7,198.9,306.9,161.4,255z"/>',
'<polyline fill="none" stroke="#000000" stroke-width="0.75" stroke-linejoin="round" stroke-miterlimit="10" points="165.1,258.9 167,256.3 170.3,264.6 175.4,257.7 179.2,271.9 187,259.1 190.8,276.5 197,259.7 202.1,277.5 207.8,259.1 213.8,275.4 217.9,258.7 224.1,271.2 226.5,257.9 232.7,266.2 235.1,256.8 238.6,262.1 241.3,255.8 243.8,257.6"/>'
)
)
);
}
/// @notice Return the mouth name of the given id
/// @param id The mouth Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Neutral";
} else if (id == 2) {
name = "Smile";
} else if (id == 3) {
name = "Sulk";
} else if (id == 4) {
name = "Poker";
} else if (id == 5) {
name = "Angry";
} else if (id == 6) {
name = "Big Smile";
} else if (id == 7) {
name = "Evil";
} else if (id == 8) {
name = "Tongue";
} else if (id == 9) {
name = "Drool";
} else if (id == 10) {
name = "O";
} else if (id == 11) {
name = "Dubu";
} else if (id == 12) {
name = "Stitch";
} else if (id == 13) {
name = "Uwu";
} else if (id == 14) {
name = "Monster";
}
}
/// @dev The base SVG for the mouth
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Mouth">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Nose SVG generator
library NoseDetail {
/// @dev Nose N°1 => Classic
function item_1() public pure returns (string memory) {
return "";
}
/// @dev Nose N°2 => Bleeding
function item_2() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#E90000" d="M205.8,254.1C205.8,254.1,205.9,254.1,205.8,254.1c0.1,0,0.1,0.1,0.1,0.1c0,0.2,0,0.5-0.2,0.7c-0.1,0.1-0.3,0.1-0.4,0.1c-0.4,0-0.8,0.1-1.2,0.1c-0.2,0-0.7,0.2-0.8,0s0.1-0.4,0.2-0.5c0.3-0.2,0.7-0.2,1-0.3C204.9,254.3,205.4,254.1,205.8,254.1z"/>',
'<path fill="#E90000" d="M204.3,252.8c0.3-0.1,0.6-0.2,0.9-0.1c0.1,0.2,0.1,0.4,0.2,0.6c0,0.1,0,0.1,0,0.2c0,0.1-0.1,0.1-0.2,0.1c-0.7,0.2-1.4,0.3-2.1,0.5c-0.2,0-0.3,0.1-0.4-0.1c0-0.1-0.1-0.2,0-0.3c0.1-0.2,0.4-0.3,0.6-0.4C203.6,253.1,203.9,252.9,204.3,252.8z"/>',
'<path fill="#FF0000" d="M204.7,240.2c0.3,1.1,0.1,2.3-0.1,3.5c-0.3,2-0.5,4.1,0,6.1c0.1,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-1.1,1.3-2,1.6c-0.1,0-0.2,0.1-0.4,0.1c-0.3-0.1-0.4-0.5-0.4-0.8c-0.1-1.9,0.5-3.9,0.8-5.8c0.3-1.7,0.3-3.2-0.1-4.8c-0.1-0.5-0.3-0.9,0.1-1.3C203.4,239.7,204.6,239.4,204.7,240.2z"/>'
)
)
);
}
/// @notice Return the nose name of the given id
/// @param id The nose Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Classic";
} else if (id == 2) {
name = "Bleeding";
}
}
/// @dev The base SVG for the Nose
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Nose bonus">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
import "./constants/Colors.sol";
/// @title Eyes SVG generator
library EyesDetail {
/// @dev Eyes N°1 => Color White/Brown
function item_1() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BROWN);
}
/// @dev Eyes N°2 => Color White/Gray
function item_2() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GRAY);
}
/// @dev Eyes N°3 => Color White/Blue
function item_3() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLUE);
}
/// @dev Eyes N°4 => Color White/Green
function item_4() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GREEN);
}
/// @dev Eyes N°5 => Color White/Black
function item_5() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLACK_DEEP);
}
/// @dev Eyes N°6 => Color White/Yellow
function item_6() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.YELLOW);
}
/// @dev Eyes N°7 => Color White/Red
function item_7() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.RED);
}
/// @dev Eyes N°8 => Color White/Purple
function item_8() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PURPLE);
}
/// @dev Eyes N°9 => Color White/Pink
function item_9() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PINK);
}
/// @dev Eyes N°10 => Color White/White
function item_10() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.WHITE, Colors.WHITE);
}
/// @dev Eyes N°11 => Color Black/Blue
function item_11() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.BLACK, Colors.BLUE);
}
/// @dev Eyes N°12 => Color Black/Yellow
function item_12() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.BLACK, Colors.YELLOW);
}
/// @dev Eyes N°13 => Color Black/White
function item_13() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.BLACK, Colors.WHITE);
}
/// @dev Eyes N°14 => Color Black/Red
function item_14() public pure returns (string memory) {
return eyesNoFillAndColorPupils(Colors.BLACK, Colors.RED);
}
/// @dev Eyes N°15 => Blank White/White
function item_15() public pure returns (string memory) {
return eyesNoFillAndBlankPupils(Colors.WHITE, Colors.WHITE);
}
/// @dev Eyes N°16 => Blank Black/White
function item_16() public pure returns (string memory) {
return eyesNoFillAndBlankPupils(Colors.BLACK_DEEP, Colors.WHITE);
}
/// @dev Eyes N°17 => Shine (no-fill)
function item_17() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
eyesNoFill(Colors.WHITE),
'<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M161.4,195.1c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C160,202.4,159.9,202.5,161.4,195.1z"/>',
'<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M236.1,194.9c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C234.8,202.3,234.7,202.3,236.1,194.9z"/>'
)
)
);
}
/// @dev Eyes N°18 => Stun (no-fill)
function item_18() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
eyesNoFill(Colors.WHITE),
'<path d="M233.6,205.2c0.2-0.8,0.6-1.7,1.3-2.3c0.4-0.3,0.9-0.5,1.3-0.4c0.5,0.1,0.9,0.4,1.2,0.8c0.5,0.8,0.6,1.8,0.6,2.7c0,0.9-0.4,1.9-1.1,2.6c-0.7,0.7-1.7,1.1-2.7,1c-1-0.1-1.8-0.7-2.5-1.2c-0.7-0.5-1.4-1.2-1.9-2c-0.5-0.8-0.8-1.8-0.7-2.8c0.1-1,0.5-1.9,1.1-2.6c0.6-0.7,1.4-1.3,2.2-1.7c1.7-0.8,3.6-1,5.3-0.6c0.9,0.2,1.8,0.5,2.5,1.1c0.7,0.6,1.2,1.5,1.3,2.4c0.3,1.8-0.3,3.7-1.4,4.9c1-1.4,1.4-3.2,1-4.8c-0.2-0.8-0.6-1.5-1.3-2c-0.6-0.5-1.4-0.8-2.2-0.9c-1.6-0.2-3.4,0-4.8,0.7c-1.4,0.7-2.7,2-2.8,3.5c-0.2,1.5,0.9,3,2.2,4c0.7,0.5,1.3,1,2.1,1.1c0.7,0.1,1.5-0.2,2.1-0.7c0.6-0.5,0.9-1.3,1-2.1c0.1-0.8,0-1.7-0.4-2.3c-0.2-0.3-0.5-0.6-0.8-0.7c-0.4-0.1-0.8,0-1.1,0.2C234.4,203.6,233.9,204.4,233.6,205.2z"/>',
'<path d="M160.2,204.8c0.7-0.4,1.6-0.8,2.5-0.7c0.4,0,0.9,0.3,1.2,0.7c0.3,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-0.8,1.7-1.5,2.3c-0.7,0.6-1.6,1.1-2.6,1c-1,0-2-0.4-2.6-1.2c-0.7-0.8-0.8-1.8-1-2.6c-0.1-0.9-0.1-1.8,0.1-2.8c0.2-0.9,0.7-1.8,1.5-2.4c0.8-0.6,1.7-1,2.7-1c0.9-0.1,1.9,0.1,2.7,0.4c1.7,0.6,3.2,1.8,4.2,3.3c0.5,0.7,0.9,1.6,1,2.6c0.1,0.9-0.2,1.9-0.8,2.6c-1.1,1.5-2.8,2.4-4.5,2.5c1.7-0.3,3.3-1.3,4.1-2.7c0.4-0.7,0.6-1.5,0.5-2.3c-0.1-0.8-0.5-1.5-1-2.2c-1-1.3-2.4-2.4-3.9-2.9c-1.5-0.5-3.3-0.5-4.5,0.5c-1.2,1-1.5,2.7-1.3,4.3c0.1,0.8,0.2,1.6,0.7,2.2c0.4,0.6,1.2,0.9,1.9,1c0.8,0,1.5-0.2,2.2-0.8c0.6-0.5,1.2-1.2,1.4-1.9c0.1-0.4,0.1-0.8-0.1-1.1c-0.2-0.3-0.5-0.6-0.9-0.6C161.9,204.2,161,204.4,160.2,204.8z"/>'
)
)
);
}
/// @dev Eyes N°19 => Squint (no-fill)
function item_19() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
eyesNoFill(Colors.WHITE),
'<path d="M167.3,203.7c0.1,7.7-12,7.7-11.9,0C155.3,196,167.4,196,167.3,203.7z"/>',
'<path d="M244.8,205.6c-1.3,7.8-13.5,5.6-12-2.2C234.2,195.6,246.4,197.9,244.8,205.6z"/>'
)
)
);
}
/// @dev Eyes N°20 => Shock (no-fill)
function item_20() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
eyesNoFill(Colors.WHITE),
'<path fill-rule="evenodd" clip-rule="evenodd" d="M163.9,204c0,2.7-4.2,2.7-4.1,0C159.7,201.3,163.9,201.3,163.9,204z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" d="M236.7,204c0,2.7-4.2,2.7-4.1,0C232.5,201.3,236.7,201.3,236.7,204z"/>'
)
)
);
}
/// @dev Eyes N°21 => Cat (no-fill)
function item_21() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
eyesNoFill(Colors.WHITE),
'<path d="M238.4,204.2c0.1,13.1-4.5,13.1-4.5,0C233.8,191.2,238.4,191.2,238.4,204.2z"/>',
'<path d="M164.8,204.2c0.1,13-4.5,13-4.5,0C160.2,191.2,164.8,191.2,164.8,204.2z"/>'
)
)
);
}
/// @dev Eyes N°22 => Ether (no-fill)
function item_22() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
eyesNoFill(Colors.WHITE),
'<path d="M161.7,206.4l-4.6-2.2l4.6,8l4.6-8L161.7,206.4z"/>',
'<path d="M165.8,202.6l-4.1-7.1l-4.1,7.1l4.1-1.9L165.8,202.6z"/>',
'<path d="M157.9,203.5l3.7,1.8l3.8-1.8l-3.8-1.8L157.9,203.5z"/>',
'<path d="M236.1,206.6l-4.6-2.2l4.6,8l4.6-8L236.1,206.6z"/>',
'<path d="M240.2,202.8l-4.1-7.1l-4.1,7.1l4.1-1.9L240.2,202.8z"/>',
'<path d="M232.4,203.7l3.7,1.8l3.8-1.8l-3.8-1.8L232.4,203.7z"/>'
)
)
);
}
/// @dev Eyes N°23 => Feels
function item_23() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M251.1,201.4c0.7,0.6,1,2.2,1,2.7c-0.1-0.4-1.4-1.1-2.2-1.7c-0.2,0.1-0.4,0.4-0.6,0.5c0.5,0.7,0.7,2,0.7,2.5c-0.1-0.4-1.3-1.1-2.1-1.6c-2.7,1.7-6.4,3.2-11.5,3.7c-8.1,0.7-16.3-1.7-20.9-6.4c5.9,3.1,13.4,4.5,20.9,3.8c6.6-0.6,12.7-2.9,17-6.3C253.4,198.9,252.6,200.1,251.1,201.4z"/>',
'<path d="M250,205.6L250,205.6C250.1,205.9,250.1,205.8,250,205.6z"/>',
'<path d="M252.1,204.2L252.1,204.2C252.2,204.5,252.2,204.4,252.1,204.2z"/>',
'<path d="M162.9,207.9c-4.1-0.4-8-1.4-11.2-2.9c-0.7,0.3-3.1,1.4-3.3,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.2-0.1,0.3-0.1c-0.2-0.1-0.5-0.3-0.7-0.4c-0.8,0.4-3,1.3-3.2,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.3-0.1,0.5-0.1c-0.9-0.7-1.7-1.6-2.4-2.4c1.5,1.1,6.9,4.2,17.4,5.3c11.9,1.2,18.3-4,19.8-4.7C177.7,205.3,171.4,208.8,162.9,207.9z"/>',
'<path d="M148.5,207L148.5,207C148.5,207.1,148.5,207.2,148.5,207z"/>',
'<path d="M146.2,205.6L146.2,205.6C146.2,205.7,146.2,205.7,146.2,205.6z"/>'
)
)
);
}
/// @dev Eyes N°24 => Happy
function item_24() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M251.5,203.5c0.7-0.7,0.9-2.5,0.9-3.2c-0.1,0.5-1.3,1.4-2.2,1.9c-0.2-0.2-0.4-0.4-0.6-0.6c0.5-0.8,0.7-2.4,0.7-3 c-0.1,0.5-1.2,1.4-2.1,1.9c-2.6-1.9-6.2-3.8-11-4.3c-7.8-0.8-15.7,2-20.1,7.5c5.7-3.6,12.9-5.3,20.1-4.5 c6.4,0.8,12.4,2.9,16.5,6.9C253.3,205.1,252.3,204,251.5,203.5z"/>',
'<path d="M250.3,198.6L250.3,198.6C250.4,198.2,250.4,198.3,250.3,198.6z"/>',
'<path d="M252.4,200.3L252.4,200.3C252.5,199.9,252.5,200,252.4,200.3z"/>',
'<path d="M228.2,192.6c1.1-0.3,2.3-0.5,3.5-0.6c1.1-0.1,2.4-0.1,3.5,0s2.4,0.3,3.5,0.5s2.3,0.6,3.3,1.1l0,0 c-1.1-0.3-2.3-0.6-3.4-0.8c-1.1-0.3-2.3-0.4-3.4-0.5c-1.1-0.1-2.4-0.2-3.5-0.1C230.5,192.3,229.4,192.4,228.2,192.6L228.2,192.6z"/>',
'<path d="M224.5,193.8c-0.9,0.6-2,1.1-3,1.7c-0.9,0.6-2,1.2-3,1.7c0.4-0.4,0.8-0.8,1.2-1.1s0.9-0.7,1.4-0.9c0.5-0.3,1-0.6,1.5-0.8C223.3,194.2,223.9,193.9,224.5,193.8z"/>',
'<path d="M161.3,195.8c-3.7,0.4-7.2,1.6-10.1,3.5c-0.6-0.3-2.8-1.6-3-2.3c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.2,0.2,0.3,0.2 c-0.2,0.2-0.4,0.3-0.6,0.5c-0.7-0.4-2.7-1.5-2.9-2.2c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.3,0.2,0.4,0.2c-0.8,0.8-1.6,1.9-2.2,2.9 c1.3-1.4,6.3-5,15.8-6.3c10.9-1.4,16.7,4.7,18,5.5C174.8,198.9,169.1,194.8,161.3,195.8z"/>',
'<path d="M148.2,196.9L148.2,196.9C148.2,196.8,148.2,196.7,148.2,196.9z"/>',
'<path d="M146.1,198.6L146.1,198.6C146.1,198.5,146.1,198.4,146.1,198.6z"/>',
'<path d="M167.5,192.2c-1.1-0.2-2.3-0.3-3.5-0.3c-1.1,0-2.4,0-3.5,0.2c-1.1,0.1-2.3,0.3-3.4,0.5c-1.1,0.3-2.3,0.5-3.4,0.8 c2.1-0.9,4.3-1.5,6.7-1.7c1.1-0.1,2.4-0.1,3.5-0.1C165.3,191.7,166.4,191.9,167.5,192.2z"/>',
'<path d="M171.4,193.4c0.6,0.2,1.1,0.3,1.7,0.6c0.5,0.3,1,0.5,1.6,0.8c0.5,0.3,1,0.6,1.4,0.9c0.5,0.3,0.9,0.7,1.3,1 c-1-0.5-2.1-1.1-3-1.6C173.3,194.5,172.3,193.9,171.4,193.4z"/>'
)
)
);
}
/// @dev Eyes N°25 => Arrow
function item_25() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M251.4,192.5l-30.8,8 c10.9,1.9,20.7,5,29.5,9.1"/>',
'<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M149.4,192.5l30.8,8 c-10.9,1.9-20.7,5-29.5,9.1"/>'
)
)
);
}
/// @dev Eyes N°26 => Closed
function item_26() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="216.3" y1="200.2" x2="259" y2="198.3"/>',
'<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="179.4" y1="200.2" x2="143.4" y2="198.3"/>'
)
)
);
}
/// @dev Eyes N°27 => Suspicious
function item_27() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path opacity="0.81" fill="#FFFFFF" d="M220.3,202.5c-0.6,4.6,0.1,5.8,1.6,8.3 c0.9,1.5,1,2.5,8.2-1.2c6.1,0.4,8.2-1.6,16,2.5c3,0,4-3.8,5.1-7.7c0.6-2.2-0.2-4.6-2-5.9c-3.4-2.5-9-6-13.4-5.3 c-3.9,0.7-7.7,1.9-11.3,3.6C222.3,197.9,221,197.3,220.3,202.5z"/>',
'<path d="M251.6,200c0.7-0.8,0.9-2.9,0.9-3.7c-0.1,0.6-1.3,1.5-2,2.2c-0.2-0.2-0.4-0.5-0.6-0.7c0.5-1,0.7-2.7,0.7-3.4 c-0.1,0.6-1.2,1.5-1.9,2.1c-2.4-2.2-5.8-4.4-10.4-4.9c-7.4-1-14.7,2.3-18.9,8.6c5.3-4.2,12.1-6,18.9-5.1c6,0.9,11.5,4,15.4,8.5 C253.6,203.4,252.9,201.9,251.6,200z"/>',
'<path d="M250.5,194.4L250.5,194.4C250.6,194,250.6,194.1,250.5,194.4z"/>',
'<path d="M252.4,196.3L252.4,196.3C252.5,195.9,252.5,196,252.4,196.3z"/>',
'<path d="M229.6,187.6c1.1-0.3,2.1-0.6,3.3-0.7c1.1-0.1,2.2-0.1,3.3,0s2.2,0.3,3.3,0.6s2.1,0.7,3.1,1.3l0,0 c-1.1-0.3-2.1-0.7-3.2-0.9c-1.1-0.3-2.1-0.5-3.2-0.6c-1.1-0.1-2.2-0.2-3.3-0.1C231.9,187.2,230.8,187.3,229.6,187.6L229.6,187.6 z"/>',
'<path d="M226.1,189c-0.9,0.7-1.8,1.3-2.8,1.9c-0.9,0.7-1.8,1.4-2.8,1.9c0.4-0.5,0.8-0.9,1.2-1.3c0.4-0.4,0.9-0.8,1.4-1.1 s1-0.7,1.5-0.9C225.1,189.4,225.7,189.1,226.1,189z"/>',
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M222,212.8c0,0,9.8-7.3,26.9,0"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M229,195.2c0,0-4.6,8.5,0.7,14.4 c0,0,8.8-1.5,11.6,0.4c0,0,4.7-5.7,1.5-12.5S229,195.2,229,195.2z"/>',
'<path opacity="0.81" fill="#FFFFFF" d="M177.1,202.5c0.6,4.6-0.1,5.8-1.6,8.3 c-0.9,1.5-1,2.5-8.2-1.2c-6.1,0.4-8.2-1.6-16,2.5c-3,0-4-3.8-5.1-7.7c-0.6-2.2,0.2-4.6,2-5.9c3.4-2.5,9-6,13.4-5.3 c3.9,0.7,7.7,1.9,11.3,3.6C175.2,197.9,176.4,197.3,177.1,202.5z"/>',
'<path d="M145.9,200c-0.7-0.8-0.9-2.9-0.9-3.7c0.1,0.6,1.3,1.5,2,2.2c0.2-0.2,0.4-0.5,0.6-0.7c-0.5-1-0.7-2.7-0.7-3.4 c0.1,0.6,1.2,1.5,1.9,2.1c2.4-2.2,5.8-4.4,10.4-4.9c7.4-1,14.7,2.3,18.9,8.6c-5.3-4.2-12.1-6-18.9-5.1c-6,0.9-11.5,4-15.4,8.5 C143.8,203.4,144.5,201.9,145.9,200z"/>',
'<path d="M146.9,194.4L146.9,194.4C146.9,194,146.9,194.1,146.9,194.4z"/>',
abi.encodePacked(
'<path d="M145,196.3L145,196.3C144.9,195.9,144.9,196,145,196.3z"/>',
'<path d="M167.8,187.6c-1.1-0.3-2.1-0.6-3.3-0.7c-1.1-0.1-2.2-0.1-3.3,0s-2.2,0.3-3.3,0.6s-2.1,0.7-3.1,1.3l0,0 c1.1-0.3,2.1-0.7,3.2-0.9c1.1-0.3,2.1-0.5,3.2-0.6c1.1-0.1,2.2-0.2,3.3-0.1C165.6,187.2,166.6,187.3,167.8,187.6L167.8,187.6z"/>',
'<path d="M171.3,189c0.9,0.7,1.8,1.3,2.8,1.9c0.9,0.7,1.8,1.4,2.8,1.9c-0.4-0.5-0.8-0.9-1.2-1.3c-0.4-0.4-0.9-0.8-1.4-1.1 s-1-0.7-1.5-0.9C172.4,189.4,171.8,189.1,171.3,189z"/>',
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M175.4,212.8c0,0-9.8-7.3-26.9,0"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M168.5,195.2c0,0,4.6,8.5-0.7,14.4 c0,0-8.8-1.5-11.6,0.4c0,0-4.7-5.7-1.5-12.5S168.5,195.2,168.5,195.2z"/>'
)
)
)
);
}
/// @dev Eyes N°28 => Annoyed 1
function item_28() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>',
'<path stroke="#000000" stroke-miterlimit="10" d="M234,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>',
'<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>',
'<path stroke="#000000" stroke-miterlimit="10" d="M158.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>'
)
)
);
}
/// @dev Eyes N°29 => Annoyed 2
function item_29() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>',
'<path stroke="#000000" stroke-miterlimit="10" d="M228,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>',
'<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>',
'<path stroke="#000000" stroke-miterlimit="10" d="M152.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>'
)
)
);
}
/// @dev Eyes N°30 => RIP
function item_30() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="190.8" x2="242.7" y2="207.8"/>',
'<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="207.8" x2="243.1" y2="190.8"/>',
'<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="190.8" x2="169.8" y2="207.8"/>',
'<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="207.8" x2="170.3" y2="190.8"/>'
)
)
);
}
/// @dev Eyes N°31 => Heart
function item_31() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M161.1,218.1c0.2,0.2,0.4,0.3,0.7,0.3s0.5-0.1,0.7-0.3l12.8-14.1 c5.3-5.9,1.5-16-6-16c-4.6,0-6.7,3.6-7.5,4.3c-0.8-0.7-2.9-4.3-7.5-4.3c-7.6,0-11.4,10.1-6,16L161.1,218.1z"/>',
'<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M235.3,218.1c0.2,0.2,0.5,0.3,0.8,0.3s0.6-0.1,0.8-0.3l13.9-14.1 c5.8-5.9,1.7-16-6.6-16c-4.9,0-7.2,3.6-8.1,4.3c-0.9-0.7-3.1-4.3-8.1-4.3c-8.2,0-12.4,10.1-6.6,16L235.3,218.1z"/>'
)
)
);
}
/// @dev Eyes N°32 => Scribble
function item_32() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="222.5,195.2 252.2,195.2 222.5,199.4 250.5,199.4 223.9,202.8 247.4,202.8"/>',
'<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="148.2,195.2 177.9,195.2 148.2,199.4 176.2,199.4 149.6,202.8 173.1,202.8"/>'
)
)
);
}
/// @dev Eyes N°33 => Wide
function item_33() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="236.7" cy="200.1" rx="12.6" ry="14.9"/>',
'<path d="M249.4,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C248.4,192.9,249.4,196.5,249.4,200.1z M249.3,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C248,207.3,249.3,203.7,249.3,200.1z"/>',
'<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="163" cy="200.1" rx="12.6" ry="14.9"/>',
'<path d="M175.6,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C174.6,192.9,175.6,196.5,175.6,200.1z M175.5,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C174.3,207.3,175.5,203.7,175.5,200.1z"/>'
)
)
);
}
/// @dev Eyes N°34 => Dubu
function item_34() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M241.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>',
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M167.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>'
)
)
);
}
/// @dev Right and left eyes (color pupils + eyes)
function eyesNoFillAndColorPupils(string memory scleraColor, string memory pupilsColor)
private
pure
returns (string memory)
{
return base(string(abi.encodePacked(eyesNoFill(scleraColor), colorPupils(pupilsColor))));
}
/// @dev Right and left eyes (blank pupils + eyes)
function eyesNoFillAndBlankPupils(string memory scleraColor, string memory pupilsColor)
private
pure
returns (string memory)
{
return base(string(abi.encodePacked(eyesNoFill(scleraColor), blankPupils(pupilsColor))));
}
/// @dev Right and left eyes
function eyesNoFill(string memory scleraColor) private pure returns (string memory) {
return string(abi.encodePacked(eyeLeftNoFill(scleraColor), eyeRightNoFill(scleraColor)));
}
/// @dev Eye right and no fill
function eyeRightNoFill(string memory scleraColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<path fill='#",
scleraColor,
"' d='M220.9,203.6c0.5,3.1,1.7,9.6,7.1,10.1 c7,1.1,21,4.3,23.2-9.3c1.3-7.1-9.8-11.4-15.4-11.2C230.7,194.7,220.5,194.7,220.9,203.6z'/>",
'<path d="M250.4,198.6c-0.2-0.2-0.4-0.5-0.6-0.7"/>',
'<path d="M248.6,196.6c-7.6-7.9-23.4-6.2-29.3,3.7c10-8.2,26.2-6.7,34.4,3.4c0-0.3-0.7-1.8-2-3.7"/>',
'<path d="M229.6,187.6c4.2-1.3,9.1-1,13,1.2C238.4,187.4,234,186.6,229.6,187.6L229.6,187.6z"/>',
'<path d="M226.1,189c-1.8,1.3-3.7,2.7-5.6,3.9C221.9,191.1,224,189.6,226.1,189z"/>',
'<path d="M224.5,212.4c5.2,2.5,19.7,3.5,24-0.9C244.2,216.8,229.6,215.8,224.5,212.4z"/>'
)
);
}
/// @dev Eye right and no fill
function eyeLeftNoFill(string memory scleraColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<path fill='#",
scleraColor,
"' d='M175.7,199.4c2.4,7.1-0.6,13.3-4.1,13.9 c-5,0.8-15.8,1-18.8,0c-5-1.7-6.1-12.4-6.1-12.4C156.6,191.4,165,189.5,175.7,199.4z'/>",
'<path d="M147.5,198.7c-0.8,1-1.5,2.1-2,3.3c7.5-8.5,24.7-10.3,31.7-0.9c-5.8-10.3-17.5-13-26.4-5.8"/>',
'<path d="M149.4,196.6c-0.2,0.2-0.4,0.4-0.6,0.6"/>',
'<path d="M166.2,187.1c-4.3-0.8-8.8,0.1-13,1.4C157,186.4,162,185.8,166.2,187.1z"/>',
'<path d="M169.8,188.5c2.2,0.8,4.1,2.2,5.6,3.8C173.5,191.1,171.6,189.7,169.8,188.5z"/>',
'<path d="M174.4,211.8c-0.2,0.5-0.8,0.8-1.2,1c-0.5,0.2-1,0.4-1.5,0.6c-1,0.3-2.1,0.5-3.1,0.7c-2.1,0.4-4.2,0.5-6.3,0.7 c-2.1,0.1-4.3,0.1-6.4-0.3c-1.1-0.2-2.1-0.5-3.1-0.9c-0.9-0.5-2-1.1-2.4-2.1c0.6,0.9,1.6,1.4,2.5,1.7c1,0.3,2,0.6,3,0.7 c2.1,0.3,4.2,0.3,6.2,0.2c2.1-0.1,4.2-0.2,6.3-0.5c1-0.1,2.1-0.3,3.1-0.5c0.5-0.1,1-0.2,1.5-0.4c0.2-0.1,0.5-0.2,0.7-0.3 C174.1,212.2,174.3,212.1,174.4,211.8z"/>'
)
);
}
/// @dev Generate color pupils
function colorPupils(string memory pupilsColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
"<path fill='#",
pupilsColor,
"' d='M235,194.9c10.6-0.2,10.6,19,0,18.8C224.4,213.9,224.4,194.7,235,194.9z'/>",
'<path d="M235,199.5c3.9-0.1,3.9,9.6,0,9.5C231.1,209.1,231.1,199.4,235,199.5z"/>',
'<path fill="#FFFFFF" d="M239.1,200.9c3.4,0,3.4,2.5,0,2.5C235.7,203.4,235.7,200.8,239.1,200.9z"/>',
"<path fill='#",
pupilsColor,
"' d='M161.9,194.6c10.5-0.4,11,18.9,0.4,18.9C151.7,213.9,151.3,194.6,161.9,194.6z'/>",
'<path d="M162,199.2c3.9-0.2,4.1,9.5,0.2,9.5C158.2,208.9,158.1,199.2,162,199.2z"/>',
'<path fill="#FFFFFF" d="M157.9,200.7c3.4-0.1,3.4,2.5,0,2.5C154.6,203.3,154.5,200.7,157.9,200.7z"/>'
)
);
}
/// @dev Generate blank pupils
function blankPupils(string memory pupilsColor) private pure returns (string memory) {
return
string(
abi.encodePacked(
abi.encodePacked(
"<path fill='#",
pupilsColor,
"' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M169.2,204.2c0.1,11.3-14.1,11.3-13.9,0C155.1,192.9,169.3,192.9,169.2,204.2z'/>",
"<path fill='#",
pupilsColor,
"' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M243.1,204.3c0.1,11.3-14.1,11.3-13.9,0C229,193,243.2,193,243.1,204.3z'/>"
)
)
);
}
/// @notice Return the eyes name of the given id
/// @param id The eyes Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Color White/Brown";
} else if (id == 2) {
name = "Color White/Gray";
} else if (id == 3) {
name = "Color White/Blue";
} else if (id == 4) {
name = "Color White/Green";
} else if (id == 5) {
name = "Color White/Black";
} else if (id == 6) {
name = "Color White/Yellow";
} else if (id == 7) {
name = "Color White/Red";
} else if (id == 8) {
name = "Color White/Purple";
} else if (id == 9) {
name = "Color White/Pink";
} else if (id == 10) {
name = "Color White/White";
} else if (id == 11) {
name = "Color Black/Blue";
} else if (id == 12) {
name = "Color Black/Yellow";
} else if (id == 13) {
name = "Color Black/White";
} else if (id == 14) {
name = "Color Black/Red";
} else if (id == 15) {
name = "Blank White/White";
} else if (id == 16) {
name = "Blank Black/White";
} else if (id == 17) {
name = "Shine";
} else if (id == 18) {
name = "Stunt";
} else if (id == 19) {
name = "Squint";
} else if (id == 20) {
name = "Shock";
} else if (id == 21) {
name = "Cat";
} else if (id == 22) {
name = "Ether";
} else if (id == 23) {
name = "Feels";
} else if (id == 24) {
name = "Happy";
} else if (id == 25) {
name = "Arrow";
} else if (id == 26) {
name = "Closed";
} else if (id == 27) {
name = "Suspicious";
} else if (id == 28) {
name = "Annoyed 1";
} else if (id == 29) {
name = "Annoyed 2";
} else if (id == 30) {
name = "RIP";
} else if (id == 31) {
name = "Heart";
} else if (id == 32) {
name = "Scribble";
} else if (id == 33) {
name = "Wide";
} else if (id == 34) {
name = "Dubu";
}
}
/// @dev The base SVG for the eyes
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Eyes">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Eyebrow SVG generator
library EyebrowDetail {
/// @dev Eyebrow N°1 => Classic
function item_1() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#150000" d="M213.9,183.1c13.9-5.6,28.6-3,42.7-0.2C244,175,225.8,172.6,213.9,183.1z"/>',
'<path fill="#150000" d="M179.8,183.1c-10.7-10.5-27-8.5-38.3-0.5C154.1,179.7,167.6,177.5,179.8,183.1z"/>'
)
)
);
}
/// @dev Eyebrow N°2 => Thick
function item_2() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M211.3,177.6c0,0,28.6-6.6,36.2-6.2c7.7,0.4,13,3,16.7,6.4c0,0-26.9,5.3-38.9,5.9C213.3,184.3,212.9,183.8,211.3,177.6z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M188.2,177.6c0,0-27.9-6.7-35.4-6.3c-7.5,0.4-12.7,2.9-16.2,6.3c0,0,26.3,5.3,38,6C186.2,184.3,186.7,183.7,188.2,177.6z"/>'
)
)
);
}
/// @dev Eyebrow N°3 => Punk
function item_3() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M258.6,179.1l-2-2.3 c3.1,0.4,5.6,1,7.6,1.7C264.2,178.6,262,178.8,258.6,179.1z M249.7,176.3c-0.7,0-1.5,0-2.3,0c-7.6,0-36.1,3.2-36.1,3.2 c-0.4,2.9-3.8,3.5,8.1,3c6.6-0.3,23.6-2,32.3-2.8L249.7,176.3z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M140.2,179.1l1.9-2.3 c-3,0.4-5.4,1-7.3,1.7C134.8,178.6,136.9,178.8,140.2,179.1z M148.8,176.3c0.7,0,1.4,0,2.2,0c7.3,0,34.7,3.2,34.7,3.2 c0.4,2.9,3.6,3.5-7.8,3c-6.3-0.3-22.7-2-31-2.8L148.8,176.3z"/>'
)
)
);
}
/// @dev Eyebrow N°4 => Small
function item_4() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill-rule="evenodd" clip-rule="evenodd" d="M236.3,177c-11.3-5.1-18-3.1-20.3-2.1c-0.1,0-0.2,0.1-0.3,0.2c-0.3,0.1-0.5,0.3-0.6,0.3l0,0l0,0l0,0c-1,0.7-1.7,1.7-1.9,3c-0.5,2.6,1.2,5,3.8,5.5s5-1.2,5.5-3.8c0.1-0.3,0.1-0.6,0.1-1C227.4,175.6,236.3,177,236.3,177z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" d="M160.2,176.3c10.8-4.6,17.1-2.5,19.2-1.3c0.1,0,0.2,0.1,0.3,0.2c0.3,0.1,0.4,0.3,0.5,0.3l0,0l0,0l0,0c0.9,0.7,1.6,1.8,1.8,3.1c0.4,2.6-1.2,5-3.7,5.4s-4.7-1.4-5.1-4c-0.1-0.3-0.1-0.6-0.1-1C168.6,175.2,160.2,176.3,160.2,176.3z"/>'
)
)
);
}
/// @dev Eyebrow N°5 => Shaved
function item_5() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<g opacity="0.06">',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M214.5,178 c0,0,20.6-3.5,26.1-3.3s9.4,1.6,12,3.4c0,0-19.4,2.8-28,3.1C215.9,181.6,215.6,181.3,214.5,178z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M180.8,178 c0,0-20.1-3.6-25.5-3.4c-5.4,0.2-9.1,1.5-11.7,3.4c0,0,18.9,2.8,27.4,3.2C179.4,181.6,179.8,181.3,180.8,178z"/>',
"</g>"
)
)
);
}
/// @dev Eyebrow N°6 => Elektric
function item_6() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill-rule="evenodd" clip-rule="evenodd" d="M208.9,177.6c14.6-1.5,47.8-6.5,51.6-6.6l-14.4,4.1l19.7,3.2 c-20.2-0.4-40.9-0.1-59.2,2.6C206.6,179.9,207.6,178.5,208.9,177.6z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" d="M185.1,177.7c-13.3-1.5-43.3-6.7-46.7-6.9l13.1,4.2l-17.8,3.1 c18.2-0.3,37,0.1,53.6,2.9C187.2,180,186.2,178.6,185.1,177.7z"/>'
)
)
);
}
/// @notice Return the eyebrow name of the given id
/// @param id The eyebrow Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Classic";
} else if (id == 2) {
name = "Thick";
} else if (id == 3) {
name = "Punk";
} else if (id == 4) {
name = "Small";
} else if (id == 5) {
name = "Shaved";
} else if (id == 6) {
name = "Elektric";
}
}
/// @dev The base SVG for the Eyebrow
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Eyebrow">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Mark SVG generator
library MarkDetail {
/// @dev Mark N°1 => Classic
function item_1() public pure returns (string memory) {
return "";
}
/// @dev Mark N°2 => Blush Cheeks
function item_2() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<g opacity="0.71">',
'<ellipse fill="#FF7478" cx="257.6" cy="221.2" rx="11.6" ry="3.6"/>',
'<ellipse fill="#FF7478" cx="146.9" cy="221.5" rx="9.6" ry="3.6"/>',
"</g>"
)
)
);
}
/// @dev Mark N°3 => Dark Circle
function item_3() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M160.1,223.2c4.4,0.2,8.7-1.3,12.7-3.2C169.3,222.7,164.4,223.9,160.1,223.2z"/>',
'<path d="M156.4,222.4c-2.2-0.4-4.3-1.6-6.1-3C152.3,220.3,154.4,221.4,156.4,222.4z"/>',
'<path d="M234.5,222.7c4.9,0.1,9.7-1.4,14.1-3.4C244.7,222.1,239.3,223.4,234.5,222.7z"/>',
'<path d="M230.3,221.9c-2.5-0.4-4.8-1.5-6.7-2.9C225.9,219.9,228.2,221,230.3,221.9z"/>'
)
)
);
}
/// @dev Mark N°4 => Chin scar
function item_4() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#E83342" d="M195.5,285.7l17,8.9C212.5,294.6,206.1,288.4,195.5,285.7z"/>',
'<path fill="#E83342" d="M211.2,285.7l-17,8.9C194.1,294.6,200.6,288.4,211.2,285.7z"/>'
)
)
);
}
/// @dev Mark N°5 => Blush
function item_5() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<ellipse opacity="0.52" fill-rule="evenodd" clip-rule="evenodd" fill="#FF7F83" cx="196.8" cy="222" rx="32.8" ry="1.9"/>'
)
)
);
}
/// @dev Mark N°6 => Chin
function item_6() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M201.3,291.9c0.2-0.6,0.4-1.3,1-1.8c0.3-0.2,0.7-0.4,1.1-0.3c0.4,0.1,0.7,0.4,0.9,0.7c0.4,0.6,0.5,1.4,0.5,2.1 c0,0.7-0.3,1.5-0.8,2c-0.5,0.6-1.3,0.9-2.1,0.8c-0.8-0.1-1.5-0.5-2-0.9c-0.6-0.4-1.1-1-1.5-1.6c-0.4-0.6-0.6-1.4-0.6-2.2 c0.2-1.6,1.4-2.8,2.7-3.4c1.3-0.6,2.8-0.8,4.2-0.5c0.7,0.1,1.4,0.4,2,0.9c0.6,0.5,0.9,1.2,1,1.9c0.2,1.4-0.2,2.9-1.2,3.9 c0.7-1.1,1-2.5,0.7-3.8c-0.2-0.6-0.5-1.2-1-1.5c-0.5-0.4-1.1-0.6-1.7-0.6c-1.3-0.1-2.6,0-3.7,0.6c-1.1,0.5-2,1.5-2.1,2.6 c-0.1,1.1,0.7,2.2,1.6,3c0.5,0.4,1,0.8,1.5,0.8c0.5,0.1,1.1-0.1,1.5-0.5c0.4-0.4,0.7-0.9,0.7-1.6c0.1-0.6,0-1.3-0.3-1.8 c-0.1-0.3-0.4-0.5-0.6-0.6c-0.3-0.1-0.6,0-0.8,0.1C201.9,290.7,201.5,291.3,201.3,291.9z"/>'
)
)
);
}
/// @dev Mark N°7 => Yinyang
function item_7() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path opacity="0.86" d="M211.5,161.1c0-8.2-6.7-14.9-14.9-14.9c-0.2,0-0.3,0-0.5,0l0,0 H196c-0.1,0-0.2,0-0.2,0c-0.2,0-0.4,0-0.5,0c-7.5,0.7-13.5,7.1-13.5,14.8c0,8.2,6.7,14.9,14.9,14.9 C204.8,176,211.5,169.3,211.5,161.1z M198.4,154.2c0,1-0.8,1.9-1.9,1.9c-1,0-1.9-0.8-1.9-1.9c0-1,0.8-1.9,1.9-1.9 C197.6,152.3,198.4,153.1,198.4,154.2z M202.9,168.2c0,3.6-3.1,6.6-6.9,6.6l0,0c-7.3-0.3-13.2-6.3-13.2-13.7c0-6,3.9-11.2,9.3-13 c-2,1.3-3.4,3.6-3.4,6.2c0,4,3.3,7.3,7.3,7.3l0,0C199.8,161.6,202.9,164.5,202.9,168.2z M196.6,170.3c-1,0-1.9-0.8-1.9-1.9 c0-1,0.8-1.9,1.9-1.9c1,0,1.9,0.8,1.9,1.9C198.4,169.5,197.6,170.3,196.6,170.3z"/>'
)
)
);
}
/// @dev Mark N°8 => Scar
function item_8() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path id="Scar" fill="#FF7478" d="M236.2,148.7c0,0-7.9,48.9-1.2,97.3C235,246,243.8,201.5,236.2,148.7z"/>'
)
)
);
}
/// @dev Mark N°9 => Sun
function item_9() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<circle fill="#7F0068" cx="195.8" cy="161.5" r="11.5"/>',
'<polygon fill="#7F0068" points="195.9,142.4 192.4,147.8 199.3,147.8"/>',
'<polygon fill="#7F0068" points="209.6,158.1 209.6,164.9 214.9,161.5"/>',
'<polygon fill="#7F0068" points="195.9,180.6 199.3,175.2 192.4,175.2"/>',
'<polygon fill="#7F0068" points="182.1,158.1 176.8,161.5 182.1,164.9"/>',
'<polygon fill="#7F0068" points="209.3,148 203.1,149.4 208,154.2"/>',
'<polygon fill="#7F0068" points="209.3,175 208,168.8 203.1,173.6"/>',
'<polygon fill="#7F0068" points="183.7,168.8 182.4,175 188.6,173.6"/>',
'<polygon fill="#7F0068" points="188.6,149.4 182.4,148 183.7,154.2"/>'
)
)
);
}
/// @dev Mark N°10 => Moon
function item_10() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#7F0068" d="M197.2,142.1c-5.8,0-10.9,2.9-13.9,7.3c2.3-2.3,5.4-3.7,8.9-3.7c7.1,0,12.9,5.9,12.9,13.3 s-5.8,13.3-12.9,13.3c-3.4,0-6.6-1.4-8.9-3.7c3.1,4.4,8.2,7.3,13.9,7.3c9.3,0,16.9-7.6,16.9-16.9S206.6,142.1,197.2,142.1z"/>'
)
)
);
}
/// @dev Mark N°11 => Third Eye
function item_11() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path opacity="0.81" fill="#FFFFFF" d="M184.4,159.3c0.7,3.5,0.8,8.5,6.3,8.8 c5.5,1.6,23.2,4.2,23.8-7.6c1.2-6.1-10-9.5-15.5-9.3C193.8,152.6,184.1,153.5,184.4,159.3z"/>',
'<path d="M213.6,155.6c-0.2-0.2-0.4-0.4-0.6-0.6"/>',
'<path d="M211.8,154c-7.7-6.6-23.5-4.9-29.2,3.6c9.9-7.1,26.1-6.1,34.4,2.4c0-0.3-0.7-1.5-2-3.1"/>',
'<path d="M197.3,146.8c4.3-0.6,9.1,0.3,12.7,2.7C206,147.7,201.8,146.5,197.3,146.8L197.3,146.8z M193.6,147.5 c-2,0.9-4.1,1.8-6.1,2.6C189.2,148.8,191.5,147.8,193.6,147.5z"/>',
'<path d="M187.6,167.2c5.2,2,18.5,3.2,23.3,0.1C206.3,171.3,192.7,170,187.6,167.2z"/>',
'<path fill="#0B1F26" d="M199.6,151c11.1-0.2,11.1,17.4,0,17.3C188.5,168.4,188.5,150.8,199.6,151z"/>'
)
)
);
}
/// @dev Mark N°12 => Tori
function item_12() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="231.2" y1="221.5" x2="231.2" y2="228.4"/>',
'<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M228.6,221.2c0,0,3.2,0.4,5.5,0.2"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M237.3,221.5c0,0-3.5,3.1,0,6.3C240.8,231,242.2,221.5,237.3,221.5z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M243.2,227.8l-1.2-6.4c0,0,8.7-2,1,2.8l3.2,3"/>',
'<line fill-rule="evenodd" clip-rule="evenodd" fill="#FFEBB4" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="248.5" y1="221" x2="248.5" y2="227.5"/>',
'<path d="M254.2,226c0,0,0.1,0,0.1,0c0,0,0.1,0,0.1-0.1l1.3-2.2c0.5-0.9-0.2-2.2-1.2-2c-0.6,0.1-0.8,0.7-0.9,0.8 c-0.1-0.1-0.5-0.5-1.1-0.4c-1,0.2-1.3,1.7-0.4,2.3L254.2,226z"/>'
)
)
);
}
/// @dev Mark N°13 => Ether
function item_13() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M196.5,159.9l-12.4-5.9l12.4,21.6l12.4-21.6L196.5,159.9z"/>',
'<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M207.5,149.6l-11-19.1l-11,19.2l11-5.2L207.5,149.6z"/>',
'<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M186.5,152.2l10.1,4.8l10.1-4.8l-10.1-4.8L186.5,152.2z"/>'
)
)
);
}
/// @notice Return the mark name of the given id
/// @param id The mark Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Classic";
} else if (id == 2) {
name = "Blush Cheeks";
} else if (id == 3) {
name = "Dark Circle";
} else if (id == 4) {
name = "Chin Scar";
} else if (id == 5) {
name = "Blush";
} else if (id == 6) {
name = "Chin";
} else if (id == 7) {
name = "Yinyang";
} else if (id == 8) {
name = "Scar";
} else if (id == 9) {
name = "Sun";
} else if (id == 10) {
name = "Moon";
} else if (id == 11) {
name = "Third Eye";
} else if (id == 12) {
name = "Tori";
} else if (id == 13) {
name = "Ether";
}
}
/// @dev The base SVG for the hair
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Mark">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
import "./constants/Colors.sol";
/// @title Accessory SVG generator
library AccessoryDetail {
/// @dev Accessory N°1 => Classic
function item_1() public pure returns (string memory) {
return "";
}
/// @dev Accessory N°2 => Glasses
function item_2() public pure returns (string memory) {
return base(glasses("D1F5FF", "000000", "0.31"));
}
/// @dev Accessory N°3 => Bow Tie
function item_3() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-width="7" stroke-miterlimit="10" d="M176.2,312.5 c3.8,0.3,26.6,7.2,81.4-0.4"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M211.3,322.1 c-2.5-0.3-5-0.5-7.4,0c-1.1,0-1.9-1.4-1.9-3.1v-4.5c0-1.7,0.9-3.1,1.9-3.1c2.3,0.6,4.8,0.5,7.4,0c1.1,0,1.9,1.4,1.9,3.1v4.5 C213.2,320.6,212.3,322.1,211.3,322.1z"/>',
'<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M202.4,321.5c0,0-14,5.6-17.7,5.3c-1.1-0.1-2.5-4.6-1.2-10.5 c0,0-1-2.2-0.3-9.5c0.4-3.4,19.2,5.1,19.2,5.1S201,316.9,202.4,321.5z"/>',
'<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M212.6,321.5c0,0,14,5.6,17.7,5.3c1.1-0.1,2.5-4.6,1.2-10.5 c0,0,1-2.2,0.3-9.5c-0.4-3.4-19.2,5.1-19.2,5.1S213.9,316.9,212.6,321.5z"/>',
'<path opacity="0.41" d="M213.6,315.9l6.4-1.1l-3.6,1.9l4.1,1.1l-7-0.6L213.6,315.9z M201.4,316.2l-6.4-1.1l3.6,1.9l-4.1,1.1l7-0.6L201.4,316.2z"/>'
)
)
);
}
/// @dev Accessory N°4 => Monk Beads Classic
function item_4() public pure returns (string memory) {
return base(monkBeads("63205A"));
}
/// @dev Accessory N°5 => Monk Beads Silver
function item_5() public pure returns (string memory) {
return base(monkBeads("C7D2D4"));
}
/// @dev Accessory N°6 => Power Pole
function item_6() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FF6F4F" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M272.3,331.9l55.2-74.4c0,0,3,4.3,8.7,7.5l-54,72.3"/>',
'<polygon fill="#BA513A" points="335.9,265.3 334.2,264.1 279.9,336.1 281.8,337.1"/>',
'<ellipse transform="matrix(0.6516 -0.7586 0.7586 0.6516 -82.3719 342.7996)" fill="#B54E36" stroke="#000000" stroke-width="0.25" stroke-miterlimit="10" cx="332" cy="261.1" rx="1.2" ry="6.1"/>',
'<path fill="none" stroke="#B09E00" stroke-miterlimit="10" d="M276.9,335.3c-52.7,31.1-119.3,49.4-120.7,49"/>'
)
)
);
}
/// @dev Accessory N°7 => Vintage Glasses
function item_7() public pure returns (string memory) {
return base(glasses("FC55FF", "DFA500", "0.31"));
}
/// @dev Accessory N°8 => Monk Beads Gold
function item_8() public pure returns (string memory) {
return base(monkBeads("FFDD00"));
}
/// @dev Accessory N°9 => Eye Patch
function item_9() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#FCFEFF" stroke="#4A6362" stroke-miterlimit="10" d="M253.6,222.7H219c-4.7,0-8.5-3.8-8.5-8.5v-20.8 c0-4.7,3.8-8.5,8.5-8.5h34.6c4.7,0,8.5,3.8,8.5,8.5v20.8C262.1,218.9,258.3,222.7,253.6,222.7z"/>',
'<path fill="none" stroke="#4A6362" stroke-width="0.75" stroke-miterlimit="10" d="M250.1,218.9h-27.6c-3.8,0-6.8-3.1-6.8-6.8 v-16.3c0-3.8,3.1-6.8,6.8-6.8h27.6c3.8,0,6.8,3.1,6.8,6.8V212C257,215.8,253.9,218.9,250.1,218.9z"/>',
'<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.9" y1="188.4" x2="131.8" y2="183.1"/>',
'<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.9" y1="188.1" x2="293.4" y2="196.7"/>',
'<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.2" y1="220.6" x2="277.5" y2="251.6"/>',
'<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.4" y1="219.1" x2="140.5" y2="242"/>',
'<g fill-rule="evenodd" clip-rule="evenodd" fill="#636363" stroke="#4A6362" stroke-width="0.25" stroke-miterlimit="10"><ellipse cx="250.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="215" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="193.8" rx="0.8" ry="1.1"/></g>'
)
)
);
}
/// @dev Accessory N°10 => Sun Glasses
function item_10() public pure returns (string memory) {
return base(glasses(Colors.BLACK, Colors.BLACK_DEEP, "1"));
}
/// @dev Accessory N°11 => Monk Beads Diamond
function item_11() public pure returns (string memory) {
return base(monkBeads("AAFFFD"));
}
/// @dev Accessory N°12 => Horns
function item_12() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M257.7,96.3c0,0,35-18.3,46.3-42.9c0,0-0.9,37.6-23.2,67.6C269.8,115.6,261.8,107.3,257.7,96.3z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M162,96.7c0,0-33-17.3-43.7-40.5c0,0,0.9,35.5,21.8,63.8C150.6,114.9,158.1,107.1,162,96.7z"/>'
)
)
);
}
/// @dev Accessory N°13 => Halo
function item_13() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#F6FF99" stroke="#000000" stroke-miterlimit="10" d="M136,67.3c0,14.6,34.5,26.4,77,26.4s77-11.8,77-26.4s-34.5-26.4-77-26.4S136,52.7,136,67.3L136,67.3z M213,79.7c-31.4,0-56.9-6.4-56.9-14.2s25.5-14.2,56.9-14.2s56.9,6.4,56.9,14.2S244.4,79.7,213,79.7z"/>'
)
)
);
}
/// @dev Accessory N°14 => Saiki Power
function item_14() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="270.5" y1="105.7" x2="281.7" y2="91.7"/>',
'<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="285.7" cy="85.2" r="9.2"/>',
'<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="155.8" y1="105.7" x2="144.5" y2="91.7"/>',
'<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="138.7" cy="85.2" r="9.2"/>',
'<path opacity="0.17" d="M287.3,76.6c0,0,10.2,8.2,0,17.1c0,0,7.8-0.7,7.4-9.5 C293,75.9,287.3,76.6,287.3,76.6z"/>',
'<path opacity="0.17" d="M137,76.4c0,0-10.2,8.2,0,17.1c0,0-7.8-0.7-7.4-9.5 C131.4,75.8,137,76.4,137,76.4z"/>',
'<ellipse transform="matrix(0.4588 -0.8885 0.8885 0.4588 80.0823 294.4391)" fill="#FFFFFF" cx="281.8" cy="81.5" rx="2.1" ry="1.5"/>',
'<ellipse transform="matrix(0.8885 -0.4588 0.4588 0.8885 -21.756 74.6221)" fill="#FFFFFF" cx="142.7" cy="82.1" rx="1.5" ry="2.1"/>',
'<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M159.6,101.4c0,0-1.1,4.4-7.4,7.2"/>',
'<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M267.2,101.4c0,0,1.1,4.4,7.4,7.2"/>',
abi.encodePacked(
'<polygon opacity="0.68" fill="#7FFF35" points="126,189.5 185.7,191.8 188.6,199.6 184.6,207.4 157.3,217.9 128.6,203.7"/>',
'<polygon opacity="0.68" fill="#7FFF35" points="265.7,189.5 206.7,191.8 203.8,199.6 207.7,207.4 234.8,217.9 263.2,203.7"/>',
'<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.5,195.7 191.8,195.4 187,190.9 184.8,192.3 188.5,198.9 183,206.8 187.6,208.3 193.1,201.2 196.5,201.2"/>',
'<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.4,195.7 201.1,195.4 205.9,190.9 208.1,192.3 204.4,198.9 209.9,206.8 205.3,208.3 199.8,201.2 196.4,201.2"/>',
'<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="123.8,189.5 126.3,203 129.2,204.4 127.5,189.5"/>',
'<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="265.8,189.4 263.3,203.7 284.3,200.6 285.3,189.4"/>'
)
)
)
);
}
/// @dev Accessory N°15 => No Face
function item_15() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path fill="#F5F4F3" stroke="#000000" stroke-miterlimit="10" d="M285.5,177.9c0,68.3-19.6,127.3-77.9,128.2 c-58.4,0.9-74.4-57.1-74.4-125.4s14.4-103.5,72.7-103.5C266.7,77.2,285.5,109.6,285.5,177.9z"/>',
'<path opacity="0.08" d="M285.4,176.9c0,68.3-19.4,127.6-78,129.3 c27.2-17.6,28.3-49.1,28.3-117.3s23.8-86-30-111.6C266.4,77.3,285.4,108.7,285.4,176.9z"/>',
'<ellipse cx="243.2" cy="180.7" rx="16.9" ry="6.1"/>',
'<path d="M231.4,273.6c0.3-7.2-12.1-6.1-27.2-6.1s-27.4-1.4-27.2,6.1c0.1,3.4,12.1,6.1,27.2,6.1S231.3,277,231.4,273.6z"/>',
'<ellipse cx="162" cy="180.5" rx="16.3" ry="6"/>',
'<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M149.7,191.4c0,0,6.7,5.8,20.5,0.6"/>',
'<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M232.9,191.3c0,0,6.6,5.7,20.4,0.6"/>',
'<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M192.7,285.1c0,0,9.2,3.5,21.6,0"/>',
'<path fill="#996DAD" d="M150.8,200.5c1.5-3.6,17.2-3.4,18.8-0.4c1.8,3.2-4.8,45.7-6.6,46C159.8,246.8,148.1,211.1,150.8,200.5z"/>',
'<path fill="#996DAD" d="M233.9,199.8c1.5-3.6,18-2.7,19.7,0.3c3.7,6.4-6.5,45.5-9.3,45.4C241,245.2,231.1,210.4,233.9,199.8z"/>',
'<path fill="#996DAD" d="M231.3,160.6c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C236.9,132.2,229,154.1,231.3,160.6z"/>',
'<path fill="#996DAD" d="M152.9,163.2c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C158.6,134.8,150.6,156.6,152.9,163.2z"/>'
)
)
);
}
/// @dev Generate glasses with the given color and opacity
function glasses(
string memory color,
string memory stroke,
string memory opacity
) private pure returns (string memory) {
return
string(
abi.encodePacked(
'<circle fill="none" stroke="#',
stroke,
'" stroke-miterlimit="10" cx="161.5" cy="201.7" r="23.9"/>',
'<circle fill="none" stroke="#',
stroke,
'" stroke-miterlimit="10" cx="232.9" cy="201.7" r="23.9"/>',
'<circle opacity="',
opacity,
'" fill="#',
color,
'" cx="161.5" cy="201.7" r="23.9"/>',
abi.encodePacked(
'<circle opacity="',
opacity,
'" fill="#',
color,
'" cx="232.9" cy="201.7" r="23.9"/>',
'<path fill="none" stroke="#',
stroke,
'" stroke-miterlimit="10" d="M256.8,201.7l35.8-3.2 M185.5,201.7 c0,0,14.7-3.1,23.5,0 M137.6,201.7l-8.4-3.2"/>'
)
)
);
}
/// @dev Generate Monk Beads SVG with the given color
function monkBeads(string memory color) private pure returns (string memory) {
return
string(
abi.encodePacked(
'<g fill="#',
color,
'" stroke="#2B232B" stroke-miterlimit="10" stroke-width="0.75">',
'<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.3439 3.0256)" cx="176.4" cy="317.8" rx="7.9" ry="8"/>',
'<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.458 3.2596)" cx="190.2" cy="324.6" rx="7.9" ry="8"/>',
'<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5085 3.5351)" cx="206.4" cy="327.8" rx="7.9" ry="8"/>',
'<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.4607 4.0856)" cx="239.1" cy="325.2" rx="7.9" ry="8"/>',
'<ellipse transform="matrix(0.9999 -1.693338e-02 1.693338e-02 0.9999 -5.386 4.3606)" cx="254.8" cy="320.2" rx="7.9" ry="8"/>',
'<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5015 3.8124)" cx="222.9" cy="327.5" rx="7.9" ry="8"/>',
"</g>",
'<path opacity="0.14" d="M182,318.4 c0.7,1.3-0.4,3.4-2.5,4.6c-2.1,1.2-4.5,1-5.2-0.3c-0.7-1.3,0.4-3.4,2.5-4.6C178.9,316.9,181.3,317,182,318.4z M190.5,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3s3.2-3.2,2.5-4.6C195,324.6,192.7,324.5,190.5,325.7z M206.7,328.6 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C211.1,327.6,208.8,327.5,206.7,328.6z M223.2,328.4 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6S225.3,327.3,223.2,328.4z M239.8,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C244.3,324.7,242,324.5,239.8,325.7z M255.7,320.9 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C260.1,319.9,257.8,319.7,255.7,320.9z"/>',
abi.encodePacked(
'<g fill="#FFFFFF" stroke="#FFFFFF" stroke-miterlimit="10">',
'<path d="M250.4,318.9c0.6,0.6,0.5-0.9,1.3-2c0.8-1,2.4-1.2,1.8-1.8 c-0.6-0.6-1.9-0.2-2.8,0.9C250,317,249.8,318.3,250.4,318.9z"/>',
'<path d="M234.4,323.6c0.7,0.6,0.5-0.9,1.4-1.9c1-1,2.5-1.1,1.9-1.7 c-0.7-0.6-1.9-0.3-2.8,0.7C234.1,321.7,233.8,323,234.4,323.6z"/>',
'<path d="M218.2,325.8c0.6,0.6,0.6-0.9,1.4-1.8c1-1,2.5-1,1.9-1.6 c-0.6-0.6-1.9-0.4-2.8,0.6C217.8,323.9,217.6,325.2,218.2,325.8z"/>',
'<path d="M202.1,325.5c0.6,0.6,0.6-0.9,1.7-1.7s2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.4C202,323.5,201.5,324.8,202.1,325.5z"/>',
'<path d="M186.2,322c0.6,0.6,0.6-0.9,1.7-1.7c1-0.8,2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.3C186,320.1,185.7,321.4,186.2,322z"/>',
'<path d="M171.7,315.4c0.6,0.6,0.6-0.9,1.5-1.8s2.5-0.9,1.9-1.6 s-1.9-0.4-2.8,0.5C171.5,313.5,171.1,314.9,171.7,315.4z"/>',
"</g>"
)
)
);
}
/// @notice Return the accessory name of the given id
/// @param id The accessory Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Classic";
} else if (id == 2) {
name = "Glasses";
} else if (id == 3) {
name = "Bow Tie";
} else if (id == 4) {
name = "Monk Beads Classic";
} else if (id == 5) {
name = "Monk Beads Silver";
} else if (id == 6) {
name = "Power Pole";
} else if (id == 7) {
name = "Vintage Glasses";
} else if (id == 8) {
name = "Monk Beads Gold";
} else if (id == 9) {
name = "Eye Patch";
} else if (id == 10) {
name = "Sun Glasses";
} else if (id == 11) {
name = "Monk Beads Diamond";
} else if (id == 12) {
name = "Horns";
} else if (id == 13) {
name = "Halo";
} else if (id == 14) {
name = "Saiki Power";
} else if (id == 15) {
name = "No Face";
}
}
/// @dev The base SVG for the accessory
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Accessory">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
/// @title Earrings SVG generator
library EarringsDetail {
/// @dev Earrings N°1 => Classic
function item_1() public pure returns (string memory) {
return "";
}
/// @dev Earrings N°2 => Circle
function item_2() public pure returns (string memory) {
return base(circle("000000"));
}
/// @dev Earrings N°3 => Circle Silver
function item_3() public pure returns (string memory) {
return base(circle("C7D2D4"));
}
/// @dev Earrings N°4 => Ring
function item_4() public pure returns (string memory) {
return base(ring("000000"));
}
/// @dev Earrings N°5 => Circle Gold
function item_5() public pure returns (string memory) {
return base(circle("FFDD00"));
}
/// @dev Earrings N°6 => Ring Gold
function item_6() public pure returns (string memory) {
return base(ring("FFDD00"));
}
/// @dev Earrings N°7 => Heart
function item_7() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M284.3,247.9c0.1,0.1,0.1,0.1,0.2,0.1s0.2,0,0.2-0.1l3.7-3.8c1.5-1.6,0.4-4.3-1.8-4.3c-1.3,0-1.9,1-2.2,1.2c-0.2-0.2-0.8-1.2-2.2-1.2c-2.2,0-3.3,2.7-1.8,4.3L284.3,247.9z"/>',
'<path d="M135,246.6c0,0,0.1,0.1,0.2,0.1s0.1,0,0.2-0.1l3.1-3.1c1.3-1.3,0.4-3.6-1.5-3.6c-1.1,0-1.6,0.8-1.8,1c-0.2-0.2-0.7-1-1.8-1c-1.8,0-2.8,2.3-1.5,3.6L135,246.6z"/>'
)
)
);
}
/// @dev Earrings N°8 => Gold
function item_8() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M298.7,228.1l-4.7-1.6c0,0-0.1,0-0.1-0.1v-0.1c2.8-2.7,7.1-17.2,7.2-17.4c0-0.1,0.1-0.1,0.1-0.1l0,0c5.3,1.1,5.6,2.2,5.7,2.4c-3.1,5.4-8,16.7-8.1,16.8C298.9,228,298.8,228.1,298.7,228.1C298.8,228.1,298.8,228.1,298.7,228.1z" style="fill: #fff700;stroke: #000;stroke-miterlimit: 10;stroke-width: 0.75px"/>'
)
)
);
}
/// @dev Earrings N°9 => Circle Diamond
function item_9() public pure returns (string memory) {
return base(circle("AAFFFD"));
}
/// @dev Earrings N°10 => Drop Heart
function item_10() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
drop(true),
'<path fill="#F44336" d="M285.4,282.6c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L285.4,282.6z"/>',
drop(false),
'<path fill="#F44336" d="M134.7,282.5c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L134.7,282.5z"/>'
)
)
);
}
/// @dev Earrings N11 => Ether
function item_11() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<path d="M285.7,242.7l-4.6-2.2l4.6,8l4.6-8L285.7,242.7z"/>',
'<path d="M289.8,238.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,238.9z"/>',
'<path d="M282,239.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,239.9z"/>',
'<path d="M134.5,241.8l-3.4-1.9l3.7,7.3l2.8-7.7L134.5,241.8z"/>',
'<path d="M137.3,238l-3.3-6.5l-2.5,6.9l2.8-2L137.3,238z"/>',
'<path d="M131.7,239.2l2.8,1.5l2.6-1.8l-2.8-1.5L131.7,239.2z"/>'
)
)
);
}
/// @dev Earrings N°12 => Drop Ether
function item_12() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
drop(true),
'<path d="M285.7,279.7l-4.6-2.2l4.6,8l4.6-8L285.7,279.7z"/>',
'<path d="M289.8,275.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,275.9z"/>',
'<path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/><path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/>',
drop(false),
'<path d="M135.1,279.7l-4-2.2l4,8l4-8L135.1,279.7z"/>',
'<path d="M138.7,275.9l-3.6-7.1l-3.6,7.1l3.6-1.9L138.7,275.9z"/>',
'<path d="M131.8,276.9l3.3,1.8l3.3-1.8l-3.3-1.8L131.8,276.9z"/>'
)
)
);
}
/// @dev earring drop
function drop(bool right) private pure returns (string memory) {
return
string(
right
? abi.encodePacked(
'<circle cx="285.7" cy="243.2" r="3.4"/>',
'<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="285.7" y1="243.2" x2="285.7" y2="270.2"/>'
)
: abi.encodePacked(
'<ellipse cx="135.1" cy="243.2" rx="3" ry="3.4"/>',
'<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="135.1" y1="243.2" x2="135.1" y2="270.2"/>'
)
);
}
/// @dev Generate circle SVG with the given color
function circle(string memory color) private pure returns (string memory) {
return
string(
abi.encodePacked(
'<ellipse fill="#',
color,
'" stroke="#000000" cx="135.1" cy="243.2" rx="3" ry="3.4"/>',
'<ellipse fill="#',
color,
'" stroke="#000000" cx="286.1" cy="243.2" rx="3.3" ry="3.4"/>'
)
);
}
/// @dev Generate ring SVG with the given color
function ring(string memory color) private pure returns (string memory) {
return
string(
abi.encodePacked(
'<path fill="none" stroke="#',
color,
'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M283.5,246c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5s3.1-0.9,3-5"/>',
'<path fill="none" stroke="#',
color,
'" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M134.3,244.7c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5c0.3-0.1,3.1-0.9,3-5"/>'
)
);
}
/// @notice Return the earring name of the given id
/// @param id The earring Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Classic";
} else if (id == 2) {
name = "Circle";
} else if (id == 3) {
name = "Circle Silver";
} else if (id == 4) {
name = "Ring";
} else if (id == 5) {
name = "Circle Gold";
} else if (id == 6) {
name = "Ring Gold";
} else if (id == 7) {
name = "Heart";
} else if (id == 8) {
name = "Gold";
} else if (id == 9) {
name = "Circle Diamond";
} else if (id == 10) {
name = "Drop Heart";
} else if (id == 11) {
name = "Ether";
} else if (id == 12) {
name = "Drop Ether";
}
}
/// @dev The base SVG for the earrings
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Earrings">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import "base64-sol/base64.sol";
import "./constants/Colors.sol";
/// @title Masks SVG generator
library MaskDetail {
/// @dev Mask N°1 => Maskless
function item_1() public pure returns (string memory) {
return "";
}
/// @dev Mask N°2 => Classic
function item_2() public pure returns (string memory) {
return base(classicMask("575673"));
}
/// @dev Mask N°3 => Blue
function item_3() public pure returns (string memory) {
return base(classicMask(Colors.BLUE));
}
/// @dev Mask N°4 => Pink
function item_4() public pure returns (string memory) {
return base(classicMask(Colors.PINK));
}
/// @dev Mask N°5 => Black
function item_5() public pure returns (string memory) {
return base(classicMask(Colors.BLACK));
}
/// @dev Mask N°6 => Bandage White
function item_6() public pure returns (string memory) {
return base(string(abi.encodePacked(classicMask("F5F5F5"), bandage())));
}
/// @dev Mask N°7 => Bandage Classic
function item_7() public pure returns (string memory) {
return base(string(abi.encodePacked(classicMask("575673"), bandage())));
}
/// @dev Mask N°8 => Nihon
function item_8() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
classicMask("F5F5F5"),
'<ellipse opacity="0.87" fill="#FF0039" cx="236.1" cy="259.8" rx="13.4" ry="14.5"/>'
)
)
);
}
/// @dev Generate classic mask SVG with the given color
function classicMask(string memory color) public pure returns (string memory) {
return
string(
abi.encodePacked(
'<path fill="#',
color,
'" stroke="#000000" stroke-miterlimit="10" d=" M175.7,317.7c0,0,20,15.1,82.2,0c0,0-1.2-16.2,3.7-46.8l14-18.7c0,0-41.6-27.8-77.6-37.1c-1.1-0.3-3-0.7-4-0.2 c-19.1,8.1-51.5,33-51.5,33s7.5,20.9,9.9,22.9s24.8,19.4,24.8,19.4s0,0,0,0.1C177.3,291.2,178,298.3,175.7,317.7z"/>',
'<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M177.1,290.1 c0,0,18.3,14.7,26.3,15s15.1-3.8,15.9-4.3c0.9-0.4,11.6-4.5,25.2-14.1"/>',
'<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="266.6" y1="264.4" x2="254.5" y2="278.7"/>',
'<path opacity="0.21" d="M197.7,243.5l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3 c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198,243.6,197.8,243.6,197.7,243.5z"/>',
'<path opacity="0.24" fill-rule="evenodd" clip-rule="evenodd" d="M177.2,291.1 c0,0,23,32.3,39.1,28.1s41.9-20.9,41.9-20.9c1.2-8.7,2.1-18.9,3.2-27.6c-4.6,4.7-12.8,13.2-20.9,18.3c-5,3.1-21.2,14.5-34.9,16 C198.3,305.8,177.2,291.1,177.2,291.1z"/>'
)
);
}
/// @dev Generate bandage SVG
function bandage() public pure returns (string memory) {
return
string(
abi.encodePacked(
'<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M142.9,247.9c34.3-21.9,59.3-27.4,92.4-18.5 M266.1,264.1c-21-16.2-60.8-36.4-73.9-29.1c-12.8,7.1-36.4,15.6-45.8,22.7 M230.9,242.8c-32.4,2.5-54.9,0.1-81.3,22.7 M259.8,272.3c-19.7-13.9-46.1-24.1-70.3-25.9 M211.6,250.1c-18.5,1.9-41.8,11.2-56.7,22 M256.7,276.1c-46-11.9-50.4-25.6-94,2.7 M229,267.5c-19.9,0.3-42,9.7-60.6,15.9 M238.4,290.6c-11-3.9-39.3-14.6-51.2-14 M214.5,282.5c-10.3-2.8-23,7.6-30.7,12.6 M221.6,299.8c-3.8-5.5-22.1-7.1-27-11.4 M176.2,312.4c8.2,7.3,65.1,6.4,81.2-2.6 M177.3,305.3c11.1,3.6,15.5,4.2,34.6,2.9 c14.5-1,33.2-2.7,46.2-9.2 M224.4,298.4c9,0,25.6-3.3,34.1-6 M249,285.8c3.6-0.2,7.1-1,10.5-2.3 M215.1,225.7 c-6-1.3-11.9-2.3-17.9-3.6c-4.8-1-9.8-2.1-14.7-1.3"/>'
)
);
}
/// @notice Return the mask name of the given id
/// @param id The mask Id
function getItemNameById(uint8 id) public pure returns (string memory name) {
name = "";
if (id == 1) {
name = "Maskless";
} else if (id == 2) {
name = "Classic";
} else if (id == 3) {
name = "Blue";
} else if (id == 4) {
name = "Pink";
} else if (id == 5) {
name = "Black";
} else if (id == 6) {
name = "Bandage White";
} else if (id == 7) {
name = "Bandage Classic";
} else if (id == 8) {
name = "Nihon";
}
}
/// @dev The base SVG for the eyes
function base(string memory children) private pure returns (string memory) {
return string(abi.encodePacked('<g id="Mask">', children, "</g>"));
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
/// @title Color constants
library Colors {
string internal constant BLACK = "33333D";
string internal constant BLACK_DEEP = "000000";
string internal constant BLUE = "7FBCFF";
string internal constant BROWN = "735742";
string internal constant GRAY = "7F8B8C";
string internal constant GREEN = "2FC47A";
string internal constant PINK = "FF78A9";
string internal constant PURPLE = "A839A4";
string internal constant RED = "D9005E";
string internal constant SAIKI = "F02AB6";
string internal constant WHITE = "F7F7F7";
string internal constant YELLOW = "EFED8F";
}
// 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);
}
}
|
Eyebrow N°5 => Shaved
|
function item_5() public pure returns (string memory) {
return
base(
string(
abi.encodePacked(
'<g opacity="0.06">',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M214.5,178 c0,0,20.6-3.5,26.1-3.3s9.4,1.6,12,3.4c0,0-19.4,2.8-28,3.1C215.9,181.6,215.6,181.3,214.5,178z"/>',
'<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M180.8,178 c0,0-20.1-3.6-25.5-3.4c-5.4,0.2-9.1,1.5-11.7,3.4c0,0,18.9,2.8,27.4,3.2C179.4,181.6,179.8,181.3,180.8,178z"/>',
"</g>"
)
)
);
}
| 5,890,307 |
/**
*Submitted for verification at Etherscan.io on 2021-11-01
*/
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.2 <0.8.0;
/**
* @dev Collection of functions related to the address type
*/
library AddressUpgradeable {
/**
* @dev Returns true if `account` is a contract.
*
* [////IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* ////IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: value }(data);
return _verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.staticcall(data);
return _verifyCallResult(success, returndata, errorMessage);
}
function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JAdminTools.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
////import "../utils/AddressUpgradeable.sol";
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
return !AddressUpgradeable.isContract(address(this));
}
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JAdminTools.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity >=0.6.0 <0.8.0;
////import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JAdminTools.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity >=0.6.0 <0.8.0;
////import "../utils/ContextUpgradeable.sol";
////import "../proxy/Initializable.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
function __Ownable_init() internal initializer {
__Context_init_unchained();
__Ownable_init_unchained();
}
function __Ownable_init_unchained() internal initializer {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
uint256[49] private __gap;
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JAdminTools.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
/**
* Created on 2021-05-16
* @summary: Admin Tools storage
* @author: Jibrel Team
*/
pragma solidity 0.6.12;
////import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";
contract JAdminToolsStorage is OwnableUpgradeable {
/* WARNING: NEVER RE-ORDER VARIABLES! Always double-check that new variables are added APPEND-ONLY. Re-ordering variables can permanently BREAK the deployed proxy contract.*/
uint256 public contractVersion;
uint256 public adminCounter;
// mapping for Tranches administrators
mapping (address => bool) public _Admins;
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JAdminTools.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
/**
* Created on 2021-05-16
* @summary: Admin Tools Interface
* @author: Jibrel Team
*/
pragma solidity 0.6.12;
interface IJAdminTools {
function isAdmin(address account) external view returns (bool);
function addAdmin(address account) external;
function removeAdmin(address account) external;
function renounceAdmin() external;
event AdminAdded(address account);
event AdminRemoved(address account);
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JAdminTools.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) {
uint256 c = a + b;
if (c < a) return (false, 0);
return (true, c);
}
/**
* @dev Returns the substraction of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b > a) return (false, 0);
return (true, a - b);
}
/**
* @dev Returns the multiplication of two unsigned integers, with an overflow flag.
*
* _Available since v3.4._
*/
function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) return (true, 0);
uint256 c = a * b;
if (c / a != b) return (false, 0);
return (true, c);
}
/**
* @dev Returns the division of two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a / b);
}
/**
* @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag.
*
* _Available since v3.4._
*/
function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) {
if (b == 0) return (false, 0);
return (true, a % b);
}
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
require(b <= a, "SafeMath: subtraction overflow");
return a - b;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) return 0;
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: division by zero");
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
require(b > 0, "SafeMath: modulo by zero");
return a % b;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {trySub}.
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
return a - b;
}
/**
* @dev Returns the integer division of two unsigned integers, reverting with custom message on
* division by zero. The result is rounded towards zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryDiv}.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* reverting with custom message when dividing by zero.
*
* CAUTION: This function is deprecated because it requires allocating memory for the error
* message unnecessarily. For custom revert reasons use {tryMod}.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
return a % b;
}
}
/**
* SourceUnit: /home/fabio/Jibrel/tranche-compound-protocol/contracts/JAdminTools.sol
*/
////// SPDX-License-Identifier-FLATTEN-SUPPRESS-WARNING: MIT
/**
* Created on 2021-05-16
* @summary: Jibrel Admin Tools
* @author: Jibrel Team
*/
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
////import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol";
////import "./interfaces/IJAdminTools.sol";
////import "./JAdminToolsStorage.sol";
contract JAdminTools is OwnableUpgradeable, JAdminToolsStorage, IJAdminTools {
using SafeMathUpgradeable for uint256;
/**
* @dev contract initializer
*/
function initialize() external initializer() {
OwnableUpgradeable.__Ownable_init();
_addAdmin(msg.sender);
contractVersion = 1;
}
/**
* @dev admins modifiers
*/
modifier onlyAdmins() {
require(isAdmin(msg.sender), "!Admin");
_;
}
/* Admins Roles Mngmt */
/**
* @dev add an address as an admin
* @param account address to check
*/
function _addAdmin(address account) internal {
adminCounter = adminCounter.add(1);
_Admins[account] = true;
emit AdminAdded(account);
}
/**
* @dev remove an address from admin
* @param account address to remove
*/
function _removeAdmin(address account) internal {
require(adminCounter > 1, "Cannot remove last admin");
adminCounter = adminCounter.sub(1);
_Admins[account] = false;
emit AdminRemoved(account);
}
/**
* @dev check if an address is an admin
* @param account address to check
* @return true or false
*/
function isAdmin(address account) public override view returns (bool) {
return _Admins[account];
}
/**
* @dev add an address as an admin
* @param account address to add
*/
function addAdmin(address account) external override onlyAdmins {
require(account != address(0), "Not a valid address!");
require(!isAdmin(account), " Address already Administrator");
_addAdmin(account);
}
/**
* @dev remove an address from admin
* @param account address to remove
*/
function removeAdmin(address account) external override onlyAdmins {
_removeAdmin(account);
}
/**
* @dev an address renounce to be an admin
*/
function renounceAdmin() external override onlyAdmins {
_removeAdmin(msg.sender);
}
/**
* @dev update contract version
* @param _ver new version
*/
function updateVersion(uint256 _ver) external onlyAdmins {
require(_ver > contractVersion, "!NewVersion");
contractVersion = _ver;
}
}
|
remove an address from admin account address to remove/
|
function removeAdmin(address account) external override onlyAdmins {
_removeAdmin(account);
}
| 10,745,841 |
pragma solidity ^0.4.21;
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a * b;
assert(a == 0 || c / a == b);
return c;
}
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
assert(c >= a);
return c;
}
}
contract ERC20 {
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);
}
contract MultiOwnable {
mapping (address => bool) public isOwner;
address[] public ownerHistory;
event OwnerAddedEvent(address indexed _newOwner);
event OwnerRemovedEvent(address indexed _oldOwner);
constructor() {
// Add default owner
address owner = msg.sender;
ownerHistory.push(owner);
isOwner[owner] = true;
}
modifier onlyOwner() {
require(isOwner[msg.sender]);
_;
}
function ownerHistoryCount() public view returns (uint) {
return ownerHistory.length;
}
/** Add extra owner. */
function addOwner(address owner) onlyOwner public {
require(owner != address(0));
require(!isOwner[owner]);
ownerHistory.push(owner);
isOwner[owner] = true;
emit OwnerAddedEvent(owner);
}
/** Remove extra owner. */
function removeOwner(address owner) onlyOwner public {
require(isOwner[owner]);
isOwner[owner] = false;
emit OwnerRemovedEvent(owner);
}
}
contract Pausable is MultiOwnable {
bool public paused;
modifier ifNotPaused {
require(!paused);
_;
}
modifier ifPaused {
require(paused);
_;
}
// Called by the owner on emergency, triggers paused state
function pause() external onlyOwner ifNotPaused {
paused = true;
}
// Called by the owner on end of emergency, returns to normal state
function resume() external onlyOwner ifPaused {
paused = false;
}
}
contract StandardToken is ERC20 {
using SafeMath for uint;
mapping(address => uint256) balances;
mapping(address => mapping(address => uint256)) allowed;
function balanceOf(address _owner) public view returns (uint256 balance) {
return balances[_owner];
}
function transfer(address _to, uint256 _value) public 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 Allows allowed third party to transfer tokens from one address to another. Returns success.
/// @param _from Address from where tokens are withdrawn.
/// @param _to Address to where tokens are sent.
/// @param _value Number of tokens to transfer.
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/// @dev Sets approved amount of tokens for spender. Returns success.
/// @param _spender Address of allowed account.
/// @param _value Number of approved tokens.
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/// @dev Returns number of allowed tokens for given address.
/// @param _owner Address of token owner.
/// @param _spender Address of token spender.
function allowance(address _owner, address _spender) public view returns (uint256 remaining) {
return allowed[_owner][_spender];
}
}
contract CommonToken is StandardToken, MultiOwnable {
string public constant name = 'TMSY';
string public constant symbol = 'TMSY';
uint8 public constant decimals = 18;
uint256 public saleLimit; // 85% of tokens for sale.
uint256 public teamTokens; // 7% of tokens goes to the team and will be locked for 1 year.
uint256 public partnersTokens;
uint256 public advisorsTokens;
uint256 public reservaTokens;
// 7% of team tokens will be locked at this address for 1 year.
address public teamWallet; // Team address.
address public partnersWallet; // bountry address.
address public advisorsWallet; // Team address.
address public reservaWallet;
uint public unlockTeamTokensTime = now + 365 days;
// The main account that holds all tokens at the beginning and during tokensale.
address public seller; // Seller address (main holder of tokens)
uint256 public tokensSold; // (e18) Number of tokens sold through all tiers or tokensales.
uint256 public totalSales; // Total number of sales (including external sales) made through all tiers or tokensales.
// Lock the transfer functions during tokensales to prevent price speculations.
bool public locked = true;
mapping (address => bool) public walletsNotLocked;
event SellEvent(address indexed _seller, address indexed _buyer, uint256 _value);
event ChangeSellerEvent(address indexed _oldSeller, address indexed _newSeller);
event Burn(address indexed _burner, uint256 _value);
event Unlock();
constructor (
address _seller,
address _teamWallet,
address _partnersWallet,
address _advisorsWallet,
address _reservaWallet
) MultiOwnable() public {
totalSupply = 600000000 ether;
saleLimit = 390000000 ether;
teamTokens = 120000000 ether;
partnersTokens = 30000000 ether;
reservaTokens = 30000000 ether;
advisorsTokens = 30000000 ether;
seller = _seller;
teamWallet = _teamWallet;
partnersWallet = _partnersWallet;
advisorsWallet = _advisorsWallet;
reservaWallet = _reservaWallet;
uint sellerTokens = totalSupply - teamTokens - partnersTokens - advisorsTokens - reservaTokens;
balances[seller] = sellerTokens;
emit Transfer(0x0, seller, sellerTokens);
balances[teamWallet] = teamTokens;
emit Transfer(0x0, teamWallet, teamTokens);
balances[partnersWallet] = partnersTokens;
emit Transfer(0x0, partnersWallet, partnersTokens);
balances[reservaWallet] = reservaTokens;
emit Transfer(0x0, reservaWallet, reservaTokens);
balances[advisorsWallet] = advisorsTokens;
emit Transfer(0x0, advisorsWallet, advisorsTokens);
}
modifier ifUnlocked(address _from, address _to) {
//TODO: lockup excepto para direcciones concretas... pago de servicio, conversion fase 2
//TODO: Hacer funcion que añada direcciones de excepcion
//TODO: Para el team hacer las exceptions
require(walletsNotLocked[_to]);
require(!locked);
// If requested a transfer from the team wallet:
// TODO: fecha cada 6 meses 25% de desbloqueo
/*if (_from == teamWallet) {
require(now >= unlockTeamTokensTime);
}*/
// Advisors: 25% cada 3 meses
// Reserva: 25% cada 6 meses
// Partners: El bloqueo de todos... no pueden hacer nada
_;
}
/** Can be called once by super owner. */
function unlock() onlyOwner public {
require(locked);
locked = false;
emit Unlock();
}
function walletLocked(address _wallet) onlyOwner public {
walletsNotLocked[_wallet] = false;
}
function walletNotLocked(address _wallet) onlyOwner public {
walletsNotLocked[_wallet] = true;
}
/**
* An address can become a new seller only in case it has no tokens.
* This is required to prevent stealing of tokens from newSeller via
* 2 calls of this function.
*/
function changeSeller(address newSeller) onlyOwner public returns (bool) {
require(newSeller != address(0));
require(seller != newSeller);
// To prevent stealing of tokens from newSeller via 2 calls of changeSeller:
require(balances[newSeller] == 0);
address oldSeller = seller;
uint256 unsoldTokens = balances[oldSeller];
balances[oldSeller] = 0;
balances[newSeller] = unsoldTokens;
emit Transfer(oldSeller, newSeller, unsoldTokens);
seller = newSeller;
emit ChangeSellerEvent(oldSeller, newSeller);
return true;
}
/**
* User-friendly alternative to sell() function.
*/
function sellNoDecimals(address _to, uint256 _value) public returns (bool) {
return sell(_to, _value * 1e18);
}
function sell(address _to, uint256 _value) public returns (bool) {
// Check that we are not out of limit and still can sell tokens:
// Cambiar a hardcap en usd
//require(tokensSold.add(_value) <= saleLimit);
require(msg.sender == seller, "User not authorized");
require(_to != address(0));
require(_value > 0);
require(_value <= balances[seller]);
balances[seller] = balances[seller].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(seller, _to, _value);
totalSales++;
tokensSold = tokensSold.add(_value);
emit SellEvent(seller, _to, _value);
return true;
}
/**
* Until all tokens are sold, tokens can be transfered to/from owner's accounts.
*/
function transfer(address _to, uint256 _value) ifUnlocked(msg.sender, _to) public returns (bool) {
return super.transfer(_to, _value);
}
/**
* Until all tokens are sold, tokens can be transfered to/from owner's accounts.
*/
function transferFrom(address _from, address _to, uint256 _value) ifUnlocked(_from, _to) public returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function burn(uint256 _value) public returns (bool) {
require(_value > 0, 'Value is zero');
balances[msg.sender] = balances[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
emit Transfer(msg.sender, 0x0, _value);
emit Burn(msg.sender, _value);
return true;
}
}
contract CommonTokensale is MultiOwnable, Pausable {
using SafeMath for uint;
address public beneficiary;
uint public refundDeadlineTime;
// Balances of beneficiaries:
uint public balance;
uint public balanceComision;
uint public balanceComisionHold;
uint public balanceComisionDone;
// Token contract reference.
CommonToken public token;
uint public minPaymentUSD = 250;
uint public minCapWei;
uint public maxCapWei;
uint public minCapUSD;
uint public maxCapUSD;
uint public startTime;
uint public endTime;
// Stats for current tokensale:
uint public totalTokensSold; // Total amount of tokens sold during this tokensale.
uint public totalWeiReceived; // Total amount of wei received during this tokensale.
uint public totalUSDReceived; // Total amount of wei received during this tokensale.
// This mapping stores info on how many ETH (wei) have been sent to this tokensale from specific address.
mapping (address => uint256) public buyerToSentWei;
mapping (address => uint256) public sponsorToComisionDone;
mapping (address => uint256) public sponsorToComision;
mapping (address => uint256) public sponsorToComisionHold;
mapping (address => uint256) public sponsorToComisionFromInversor;
mapping (address => bool) public kicInversor;
mapping (address => bool) public validateKYC;
mapping (address => bool) public comisionInTokens;
address[] public sponsorToComisionList;
// TODO: realizar opcion de que el inversor quiera cobrar en ETH o TMSY
event ReceiveEthEvent(address indexed _buyer, uint256 _amountWei);
event NewInverstEvent(address indexed _child, address indexed _sponsor);
event ComisionEvent(address indexed _sponsor, address indexed _child, uint256 _value, uint256 _comision);
event ComisionPayEvent(address indexed _sponsor, uint256 _value, uint256 _comision);
event ComisionInversorInTokensEvent(address indexed _sponsor, bool status);
event ChangeEndTimeEvent(address _sender, uint _date);
event verifyKycEvent(address _sender, uint _date, bool _status);
event payComisionSponsorTMSY(address _sponsor, uint _date, uint _value);
event payComisionSponsorETH(address _sponsor, uint _date, uint _value);
event withdrawEvent(address _sender, address _to, uint value, uint _date);
// ratio USD-ETH
uint public rateUSDETH;
bool public isSoftCapComplete = false;
// Array para almacenar los inversores
mapping(address => bool) public inversors;
address[] public inversorsList;
// Array para almacenar los sponsors para hacer reparto de comisiones
mapping(address => address) public inversorToSponsor;
constructor (
address _token,
address _beneficiary,
uint _startTime,
uint _endTime
) MultiOwnable() public {
require(_token != address(0));
token = CommonToken(_token);
beneficiary = _beneficiary;
startTime = _startTime;
endTime = _endTime;
minCapUSD = 400000;
maxCapUSD = 4000000;
}
function setRatio(uint _rate) onlyOwner public returns (bool) {
rateUSDETH = _rate;
return true;
}
//TODO: validateKYC
//En el momento que validan el KYC se les entregan los tokens
function burn(uint _value) onlyOwner public returns (bool) {
return token.burn(_value);
}
function newInversor(address _newInversor, address _sponsor) onlyOwner public returns (bool) {
inversors[_newInversor] = true;
inversorsList.push(_newInversor);
inversorToSponsor[_newInversor] = _sponsor;
emit NewInverstEvent(_newInversor,_sponsor);
return inversors[_newInversor];
}
function setComisionInvesorInTokens(address _inversor, bool _inTokens) onlyOwner public returns (bool) {
comisionInTokens[_inversor] = _inTokens;
emit ComisionInversorInTokensEvent(_inversor, _inTokens);
return true;
}
function setComisionInTokens() public returns (bool) {
comisionInTokens[msg.sender] = true;
emit ComisionInversorInTokensEvent(msg.sender, true);
return true;
}
function setComisionInETH() public returns (bool) {
comisionInTokens[msg.sender] = false;
emit ComisionInversorInTokensEvent(msg.sender, false);
return true;
}
function inversorIsKyc(address who) public returns (bool) {
return validateKYC[who];
}
function unVerifyKyc(address _inversor) onlyOwner public returns (bool) {
require(!isSoftCapComplete);
validateKYC[_inversor] = false;
address sponsor = inversorToSponsor[_inversor];
uint balanceHold = sponsorToComisionFromInversor[_inversor];
//Actualizamos contadores globales
balanceComision = balanceComision.sub(balanceHold);
balanceComisionHold = balanceComisionHold.add(balanceHold);
//Actualizamos contadores del sponsor
sponsorToComision[sponsor] = sponsorToComision[sponsor].sub(balanceHold);
sponsorToComisionHold[sponsor] = sponsorToComisionHold[sponsor].add(balanceHold);
//Actualizamos contador comision por inversor
// sponsorToComisionFromInversor[_inversor] = sponsorToComisionFromInversor[_inversor].sub(balanceHold);
emit verifyKycEvent(_inversor, now, false);
}
function verifyKyc(address _inversor) onlyOwner public returns (bool) {
validateKYC[_inversor] = true;
address sponsor = inversorToSponsor[_inversor];
uint balanceHold = sponsorToComisionFromInversor[_inversor];
//Actualizamos contadores globales
balanceComision = balanceComision.add(balanceHold);
balanceComisionHold = balanceComisionHold.sub(balanceHold);
//Actualizamos contadores del sponsor
sponsorToComision[sponsor] = sponsorToComision[sponsor].add(balanceHold);
sponsorToComisionHold[sponsor] = sponsorToComisionHold[sponsor].sub(balanceHold);
//Actualizamos contador comision por inversor
//sponsorToComisionFromInversor[_inversor] = sponsorToComisionFromInversor[_inversor].sub(balanceHold);
emit verifyKycEvent(_inversor, now, true);
//Enviamos comisiones en caso de tener
/*uint256 value = sponsorToComision[_inversor];
sponsorToComision[_inversor] = sponsorToComision[_inversor].sub(value);
_inversor.transfer(value);*/
return true;
}
function buyerToSentWeiOf(address who) public view returns (uint256) {
return buyerToSentWei[who];
}
function balanceOf(address who) public view returns (uint256) {
return token.balanceOf(who);
}
function balanceOfComision(address who) public view returns (uint256) {
return sponsorToComision[who];
}
function balanceOfComisionHold(address who) public view returns (uint256) {
return sponsorToComisionHold[who];
}
function balanceOfComisionDone(address who) public view returns (uint256) {
return sponsorToComisionDone[who];
}
function isInversor(address who) public view returns (bool) {
return inversors[who];
}
function payComisionSponsor(address _inversor) private {
//comprobamos que el inversor quiera cobrar en tokens...
//si es así le pagamos directo y añadimos los tokens a su cuenta
if(comisionInTokens[_inversor]) {
uint256 val = 0;
uint256 valueHold = sponsorToComisionHold[_inversor];
uint256 valueReady = sponsorToComision[_inversor];
val = valueReady.add(valueHold);
//comprobamos que tenga comisiones a cobrar
if(val > 0) {
require(balanceComision >= valueReady);
require(balanceComisionHold >= valueHold);
uint256 comisionTokens = weiToTokens(val);
sponsorToComision[_inversor] = 0;
sponsorToComisionHold[_inversor] = 0;
balanceComision = balanceComision.sub(valueReady);
balanceComisionDone = balanceComisionDone.add(val);
balanceComisionHold = balanceComisionHold.sub(valueHold);
balance = balance.add(val);
token.sell(_inversor, comisionTokens);
emit payComisionSponsorTMSY(_inversor, now, val); //TYPO TMSY
}
} else {
uint256 value = sponsorToComision[_inversor];
//comprobamos que tenga comisiones a cobrar
if(value > 0) {
require(balanceComision >= value);
//Si lo quiere en ETH
//comprobamos que hayamos alcanzado el softCap
assert(isSoftCapComplete);
//Comprobamos que el KYC esté validado
assert(validateKYC[_inversor]);
sponsorToComision[_inversor] = sponsorToComision[_inversor].sub(value);
balanceComision = balanceComision.sub(value);
balanceComisionDone = balanceComisionDone.add(value);
_inversor.transfer(value);
emit payComisionSponsorETH(_inversor, now, value); //TYPO TMSY
}
}
}
function payComision() public {
address _inversor = msg.sender;
payComisionSponsor(_inversor);
}
//Enviamos las comisiones que se han congelado o por no tener kyc o por ser en softcap
/*function sendHoldComisions() onlyOwner public returns (bool) {
//repartimos todas las comisiones congeladas hasta ahora
uint arrayLength = sponsorToComisionList.length;
for (uint i=0; i<arrayLength; i++) {
// do something
address sponsor = sponsorToComisionList[i];
if(validateKYC[sponsor]) {
uint256 value = sponsorToComision[sponsor];
sponsorToComision[sponsor] = sponsorToComision[sponsor].sub(value);
sponsor.transfer(value);
}
}
return true;
}*/
function isSoftCapCompleted() public view returns (bool) {
return isSoftCapComplete;
}
function softCapCompleted() public {
uint totalBalanceUSD = weiToUSD(balance.div(1e18));
if(totalBalanceUSD >= minCapUSD) isSoftCapComplete = true;
}
function balanceComisionOf(address who) public view returns (uint256) {
return sponsorToComision[who];
}
/** The fallback function corresponds to a donation in ETH. */
function() public payable {
//sellTokensForEth(msg.sender, msg.value);
uint256 _amountWei = msg.value;
address _buyer = msg.sender;
uint valueUSD = weiToUSD(_amountWei);
//require(startTime <= now && now <= endTime);
require(inversors[_buyer] != false);
require(valueUSD >= minPaymentUSD);
//require(totalUSDReceived.add(valueUSD) <= maxCapUSD);
uint tokensE18SinBono = weiToTokens(msg.value);
uint tokensE18Bono = weiToTokensBono(msg.value);
uint tokensE18 = tokensE18SinBono.add(tokensE18Bono);
//Ejecutamos la transferencia de tokens y paramos si ha fallado
require(token.sell(_buyer, tokensE18SinBono), "Falla la venta");
if(tokensE18Bono > 0)
assert(token.sell(_buyer, tokensE18Bono));
//repartimos al sponsor su parte 10%
uint256 _amountSponsor = (_amountWei * 10) / 100;
uint256 _amountBeneficiary = (_amountWei * 90) / 100;
totalTokensSold = totalTokensSold.add(tokensE18);
totalWeiReceived = totalWeiReceived.add(_amountWei);
buyerToSentWei[_buyer] = buyerToSentWei[_buyer].add(_amountWei);
emit ReceiveEthEvent(_buyer, _amountWei);
//por cada compra miramos cual es la cantidad actual de USD... si hemos llegado al softcap lo activamos
if(!isSoftCapComplete) {
uint256 totalBalanceUSD = weiToUSD(balance);
if(totalBalanceUSD >= minCapUSD) {
softCapCompleted();
}
}
address sponsor = inversorToSponsor[_buyer];
sponsorToComisionList.push(sponsor);
if(validateKYC[_buyer]) {
//Añadimos el saldo al sponsor
balanceComision = balanceComision.add(_amountSponsor);
sponsorToComision[sponsor] = sponsorToComision[sponsor].add(_amountSponsor);
} else {
//Añadimos el saldo al sponsor
balanceComisionHold = balanceComisionHold.add(_amountSponsor);
sponsorToComisionHold[sponsor] = sponsorToComisionHold[sponsor].add(_amountSponsor);
sponsorToComisionFromInversor[_buyer] = sponsorToComisionFromInversor[_buyer].add(_amountSponsor);
}
payComisionSponsor(sponsor);
// si hemos alcanzado el softcap repartimos comisiones
/* if(isSoftCapComplete) {
// si el sponsor ha realizado inversión se le da la comision en caso contratio se le asigna al beneficiario
if(balanceOf(sponsor) > 0)
if(validateKYC[sponsor])
sponsor.transfer(_amountSponsor);
else {
sponsorToComisionList.push(sponsor);
sponsorToComision[sponsor] = sponsorToComision[sponsor].add(_amountSponsor);
}
else
_amountBeneficiary = _amountSponsor + _amountBeneficiary;
} else { //en caso contrario no repartimos y lo almacenamos para enviarlo una vez alcanzado el softcap
if(balanceOf(sponsor) > 0) {
sponsorToComisionList.push(sponsor);
sponsorToComision[sponsor] = sponsorToComision[sponsor].add(_amountSponsor);
}
else
_amountBeneficiary = _amountSponsor + _amountBeneficiary;
}*/
balance = balance.add(_amountBeneficiary);
}
function weiToUSD(uint _amountWei) public view returns (uint256) {
uint256 ethers = _amountWei;
uint256 valueUSD = rateUSDETH.mul(ethers);
return valueUSD;
}
function weiToTokensBono(uint _amountWei) public view returns (uint256) {
uint bono = 0;
uint256 valueUSD = weiToUSD(_amountWei);
// Calculamos bono
//Tablas de bonos
if(valueUSD >= uint(500 * 1e18)) bono = 10;
if(valueUSD >= uint(1000 * 1e18)) bono = 20;
if(valueUSD >= uint(2500 * 1e18)) bono = 30;
if(valueUSD >= uint(5000 * 1e18)) bono = 40;
if(valueUSD >= uint(10000 * 1e18)) bono = 50;
uint256 bonoUsd = valueUSD.mul(bono).div(100);
uint256 tokens = bonoUsd.mul(tokensPerUSD());
return tokens;
}
/** Calc how much tokens you can buy at current time. */
function weiToTokens(uint _amountWei) public view returns (uint256) {
uint256 valueUSD = weiToUSD(_amountWei);
uint256 tokens = valueUSD.mul(tokensPerUSD());
return tokens;
}
function tokensPerUSD() public pure returns (uint256) {
return 65; // Default token price with no bonuses.
}
function canWithdraw() public view returns (bool);
function withdraw(address _to, uint value) public returns (uint) {
require(canWithdraw(), 'No es posible retirar');
require(msg.sender == beneficiary, 'Sólo puede solicitar el beneficiario los fondos');
require(balance > 0, 'Sin fondos');
require(balance >= value, 'No hay suficientes fondos');
require(_to.call.value(value).gas(1)(), 'No se que es');
balance = balance.sub(value);
emit withdrawEvent(msg.sender, _to, value,now);
return balance;
}
//Manage timelimit. For exception
function changeEndTime(uint _date) onlyOwner public returns (bool) {
//TODO; quitar comentarios para el lanzamiento
require(endTime < _date);
endTime = _date;
refundDeadlineTime = endTime + 3 * 30 days;
emit ChangeEndTimeEvent(msg.sender,_date);
return true;
}
}
contract Presale is CommonTokensale {
// In case min (soft) cap is not reached, token buyers will be able to
// refund their contributions during 3 months after presale is finished.
// Total amount of wei refunded if min (soft) cap is not reached.
uint public totalWeiRefunded;
event RefundEthEvent(address indexed _buyer, uint256 _amountWei);
constructor(
address _token,
address _beneficiary,
uint _startTime,
uint _endTime
) CommonTokensale(
_token,
_beneficiary,
_startTime,
_endTime
) public {
refundDeadlineTime = _endTime + 3 * 30 days;
}
/**
* During presale it will be possible to withdraw only in two cases:
* min cap reached OR refund period expired.
*/
function canWithdraw() public view returns (bool) {
return isSoftCapComplete;
}
/**
* It will be possible to refund only if min (soft) cap is not reached and
* refund requested during 3 months after presale finished.
*/
function canRefund() public view returns (bool) {
return !isSoftCapComplete && endTime < now && now <= refundDeadlineTime;
}
function refund() public {
require(canRefund());
address buyer = msg.sender;
uint amount = buyerToSentWei[buyer];
require(amount > 0);
// Redistribute left balance between three beneficiaries.
uint newBal = balance.sub(amount);
balance = newBal;
emit RefundEthEvent(buyer, amount);
buyerToSentWei[buyer] = 0;
totalWeiRefunded = totalWeiRefunded.add(amount);
buyer.transfer(amount);
}
}
|
Manage timelimit. For exceptionTODO; quitar comentarios para el lanzamiento
|
function changeEndTime(uint _date) onlyOwner public returns (bool) {
require(endTime < _date);
endTime = _date;
refundDeadlineTime = endTime + 3 * 30 days;
emit ChangeEndTimeEvent(msg.sender,_date);
return true;
}
| 5,746,934 |
./partial_match/1/0x79019903fb9574cA2EE1475d93984A4148c8e0dB/sources/lib/axiom-v1-contracts/contracts/AxiomV1Query.sol
|
Updates the address of the MMR SNARK verifier contract, governed by a 'timelock'. _mmrVerifierAddress the new address
|
function updateMMRVerifierAddress(address _mmrVerifierAddress) external onlyRole(TIMELOCK_ROLE) {
mmrVerifierAddress = _mmrVerifierAddress;
emit UpdateMMRVerifierAddress(_mmrVerifierAddress);
}
| 15,584,287 |
//SPDX-License-Identifier: MIT
pragma solidity ^0.6.12;
pragma experimental ABIEncoderV2;
import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol";
import "@boringcrypto/boring-solidity/contracts/Domain.sol";
import "@boringcrypto/boring-solidity/contracts/ERC20.sol";
import "@boringcrypto/boring-solidity/contracts/BoringBatchable.sol";
import "./libraries/SignedSafeMath.sol";
import "./interfaces/IRewarder.sol";
// DAO code/operator management/dutch auction, etc by BoringCrypto
// Staking in DictatorDAO inspired by Chef Nomi's SushiBar (heavily modified) - MIT license (originally WTFPL)
// TimeLock functionality Copyright 2020 Compound Labs, Inc. - BSD 3-Clause "New" or "Revised" License
// Token pool code from SushiSwap MasterChef V2, pioneered by Chef Nomi (I think, under WTFPL) and improved by Keno Budde - MIT license
contract DictatorDAO is IERC20, Domain {
using BoringMath for uint256;
using BoringMath128 for uint128;
string public symbol;
string public name;
uint8 public constant decimals = 18;
uint256 public override totalSupply;
DictatorToken public immutable token;
address public operator;
mapping(address => address) public userVote;
mapping(address => uint256) public votes;
constructor(
string memory tokenSymbol,
string memory tokenName,
string memory sharesSymbol,
string memory sharesName,
address initialOperator
) public {
// The DAO is the owner of the DictatorToken
token = new DictatorToken(tokenSymbol, tokenName);
symbol = sharesSymbol;
name = sharesName;
operator = initialOperator;
}
struct User {
uint128 balance;
uint128 lockedUntil;
}
/// @notice owner > balance mapping.
mapping(address => User) public users;
/// @notice owner > spender > allowance mapping.
mapping(address => mapping(address => uint256)) public override allowance;
/// @notice owner > nonce mapping. Used in `permit`.
mapping(address => uint256) public nonces;
event Transfer(address indexed _from, address indexed _to, uint256 _value);
event Approval(address indexed _owner, address indexed _spender, uint256 _value);
function balanceOf(address user) public view override returns (uint256 balance) {
return users[user].balance;
}
function _transfer(
address from,
address to,
uint256 shares
) internal {
User memory fromUser = users[from];
require(block.timestamp >= fromUser.lockedUntil, "Locked");
if (shares != 0) {
require(fromUser.balance >= shares, "Low balance");
if (from != to) {
require(to != address(0), "Zero address"); // Moved down so other failed calls safe some gas
User memory toUser = users[to];
address userVoteTo = userVote[to];
address userVoteFrom = userVote[from];
users[from].balance = fromUser.balance - shares.to128(); // Underflow is checked
users[to].balance = toUser.balance + shares.to128(); // Can't overflow because totalSupply would be greater than 2^256-1
votes[userVoteFrom] -= shares;
votes[userVoteTo] += shares;
}
}
emit Transfer(from, to, shares);
}
function _useAllowance(address from, uint256 shares) internal {
if (msg.sender == from) {
return;
}
uint256 spenderAllowance = allowance[from][msg.sender];
// If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20).
if (spenderAllowance != type(uint256).max) {
require(spenderAllowance >= shares, "Low allowance");
allowance[from][msg.sender] = spenderAllowance - shares; // Underflow is checked
}
}
/// @notice Transfers `shares` tokens from `msg.sender` to `to`.
/// @param to The address to move the tokens.
/// @param shares of the tokens to move.
/// @return (bool) Returns True if succeeded.
function transfer(address to, uint256 shares) public returns (bool) {
_transfer(msg.sender, to, shares);
return true;
}
/// @notice Transfers `shares` tokens from `from` to `to`. Caller needs approval for `from`.
/// @param from Address to draw tokens from.
/// @param to The address to move the tokens.
/// @param shares The token shares to move.
/// @return (bool) Returns True if succeeded.
function transferFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_transfer(from, to, shares);
return true;
}
/// @notice Approves `amount` from sender to be spend by `spender`.
/// @param spender Address of the party that can draw from msg.sender's account.
/// @param amount The maximum collective amount that `spender` can draw.
/// @return (bool) Returns True if approved.
function approve(address spender, uint256 amount) public override returns (bool) {
allowance[msg.sender][spender] = amount;
emit Approval(msg.sender, spender, amount);
return true;
}
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32) {
return _domainSeparator();
}
// keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9;
/// @notice Approves `value` from `owner_` to be spend by `spender`.
/// @param owner_ Address of the owner.
/// @param spender The address of the spender that gets approved to draw from `owner_`.
/// @param value The maximum collective amount that `spender` can draw.
/// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds).
function permit(
address owner_,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external override {
require(owner_ != address(0), "Zero owner");
require(block.timestamp < deadline, "Expired");
require(
ecrecover(_getDigest(keccak256(abi.encode(PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline))), v, r, s) ==
owner_,
"Invalid Sig"
);
allowance[owner_][spender] = value;
emit Approval(owner_, spender, value);
}
// Operator Setting
address public pendingOperator;
uint256 public pendingOperatorTime;
function setOperator(address newOperator) public {
require(newOperator != address(0), "Zero operator");
uint256 netVotes = totalSupply - votes[address(0)];
if (newOperator != pendingOperator) {
require(votes[newOperator] * 2 > netVotes, "Not enough votes");
pendingOperator = newOperator;
pendingOperatorTime = block.timestamp + 7 days;
} else {
if (votes[newOperator] * 2 > netVotes) {
require(block.timestamp >= pendingOperatorTime, "Wait longer");
operator = pendingOperator;
}
// If there aren't enough votes, then the pending operator failed
// to maintain a majority. If there are, then they are now the
// operator. In either situation:
pendingOperator = address(0);
pendingOperatorTime = 0;
}
}
/// math is ok, because amount, totalSupply and shares is always 0 <= amount <= 100.000.000 * 10^18
/// theoretically you can grow the amount/share ratio, but it's not practical and useless
function mint(uint256 amount, address operatorVote) public returns (bool) {
// TODO: Remove?
require(msg.sender != address(0), "Zero address");
User memory user = users[msg.sender];
uint256 totalTokens = token.balanceOf(address(this));
uint256 shares = totalSupply == 0 ? amount : (amount * totalSupply) / totalTokens;
// Did we change our vote? Do this while we know our previous total:
address currentVote = userVote[msg.sender];
uint256 extraVotes = shares;
if (currentVote != operatorVote) {
if (user.balance > 0) {
// Safe, because the user must have added their balance before
votes[currentVote] -= user.balance;
extraVotes += user.balance;
}
userVote[msg.sender] = operatorVote;
}
votes[operatorVote] += extraVotes;
user.balance += shares.to128();
user.lockedUntil = (block.timestamp + 24 hours).to128();
users[msg.sender] = user;
totalSupply += shares;
token.transferFrom(msg.sender, address(this), amount);
emit Transfer(address(0), msg.sender, shares);
return true;
}
// Change your vote. Does not lock tokens.
function vote(address operatorVote) public returns (bool) {
address currentVote = userVote[msg.sender];
if (currentVote != operatorVote) {
User memory user = users[msg.sender];
if (user.balance > 0) {
votes[currentVote] -= user.balance;
votes[operatorVote] += user.balance;
}
userVote[msg.sender] = operatorVote;
}
return true;
}
function _burn(
address from,
address to,
uint256 shares
) internal {
require(to != address(0), "Zero address");
User memory user = users[from];
require(block.timestamp >= user.lockedUntil, "Locked");
uint256 amount = (shares * token.balanceOf(address(this))) / totalSupply;
users[from].balance = user.balance.sub(shares.to128()); // Must check underflow
totalSupply -= shares;
votes[userVote[from]] -= shares;
token.transfer(to, amount);
emit Transfer(from, address(0), shares);
}
function burn(address to, uint256 shares) public returns (bool) {
_burn(msg.sender, to, shares);
return true;
}
function burnFrom(
address from,
address to,
uint256 shares
) public returns (bool) {
_useAllowance(from, shares);
_burn(from, to, shares);
return true;
}
event QueueTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data, uint256 eta);
event CancelTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data);
event ExecuteTransaction(bytes32 indexed txHash, address indexed target, uint256 value, bytes data);
uint256 public constant GRACE_PERIOD = 14 days;
uint256 public constant DELAY = 2 days;
mapping(bytes32 => uint256) public queuedTransactions;
function queueTransaction(
address target,
uint256 value,
bytes memory data
) public returns (bytes32) {
require(msg.sender == operator, "Operator only");
require(votes[operator] * 2 > totalSupply, "Not enough votes");
bytes32 txHash = keccak256(abi.encode(target, value, data));
uint256 eta = block.timestamp + DELAY;
queuedTransactions[txHash] = eta;
emit QueueTransaction(txHash, target, value, data, eta);
return txHash;
}
function cancelTransaction(
address target,
uint256 value,
bytes memory data
) public {
require(msg.sender == operator, "Operator only");
bytes32 txHash = keccak256(abi.encode(target, value, data));
queuedTransactions[txHash] = 0;
emit CancelTransaction(txHash, target, value, data);
}
function executeTransaction(
address target,
uint256 value,
bytes memory data
) public payable returns (bytes memory) {
require(msg.sender == operator, "Operator only");
require(votes[operator] * 2 > totalSupply, "Not enough votes");
bytes32 txHash = keccak256(abi.encode(target, value, data));
uint256 eta = queuedTransactions[txHash];
require(block.timestamp >= eta, "Too early");
require(block.timestamp <= eta + GRACE_PERIOD, "Tx stale");
queuedTransactions[txHash] = 0;
// solium-disable-next-line security/no-call-value
(bool success, bytes memory returnData) = target.call{value: value}(data);
require(success, "Tx reverted :(");
emit ExecuteTransaction(txHash, target, value, data);
return returnData;
}
}
interface IMigratorChef {
// Take the current LP token address and return the new LP token address.
// Migrator should have full access to the caller's LP token.
function migrate(IERC20 token) external returns (IERC20);
}
contract DictatorToken is ERC20, BoringBatchable {
using BoringMath for uint256;
using BoringMath128 for uint128;
using SignedSafeMath for int256;
using BoringERC20 for IERC20;
uint256 constant WEEK = 7 days;
uint256 constant BONUS_DIVISOR = 14 days;
string public symbol;
string public name;
uint8 public constant decimals = 18;
uint256 public constant totalSupply = 100_000_000 * 1e18;
DictatorDAO public immutable DAO;
uint256 public immutable startTime;
uint16 public currentWeek;
mapping(uint16 => uint256) public weekShares;
mapping(address => mapping(uint16 => uint256)) public userWeekShares;
constructor(string memory symbol_, string memory name_) public {
symbol = symbol_;
name = name_;
DAO = DictatorDAO(msg.sender);
// Register founding time
startTime = block.timestamp;
// Mint all tokens and assign to the contract (no need for minting code after this + save some gas)
balanceOf[address(this)] = totalSupply;
emit Transfer(address(0), address(this), totalSupply);
}
modifier onlyDAO() {
require(msg.sender == address(DAO), "Not DAO");
_;
}
function price() public view returns (uint256) {
uint256 weekStart = startTime + currentWeek * WEEK;
uint256 nextWeekStart = weekStart + WEEK;
if (block.timestamp >= nextWeekStart) {
return 0;
}
uint256 timeLeft = block.timestamp < weekStart ? WEEK : nextWeekStart - block.timestamp;
uint256 timeLeftExp = timeLeft**8; // Max is 1.8e46
return timeLeftExp / 1e28;
}
function buy(uint16 week, address to) external payable {
require(week == currentWeek, "Wrong week");
uint256 weekStart = startTime + currentWeek * WEEK;
require(block.timestamp >= weekStart, "Not started");
uint256 currentPrice = price();
require(currentPrice > 0, "Ended");
// The above checks ensure that elapsed < WEEK
uint256 elapsed = block.timestamp - weekStart;
// Shares = value + part of value based on how much of the week has
// passed (starts at 50%, to 0% at the end of the week)
uint256 bonus = ((WEEK - elapsed) * msg.value) / BONUS_DIVISOR;
uint256 shares = msg.value + bonus;
userWeekShares[to][week] += shares;
weekShares[week] += shares;
uint256 tokensPerWeek = tokensPerWeek(currentWeek);
// Price is per "token ETH"; tokensPerWeek is in "token wei".
require(weekShares[week].mul(1e18) <= currentPrice * tokensPerWeek, "Oversold");
}
// Conclude the auction; buyers can now get their best price:
function nextWeek() public {
// TODO: Prove that we don't need to check the multiplication
uint256 tokensPerWeek = tokensPerWeek(currentWeek);
require(weekShares[currentWeek].mul(1e18) >= price() * tokensPerWeek, "Not fully sold");
currentWeek++;
}
function claimPurchase(uint16 week, address to) public {
// TODO: Call nextWeek() as needed?
require(week < currentWeek, "Not finished");
// Given that (check definitions)...
// - price <= WEEK**8 / 1e28 ~= 1.8 ETH,
// - tokensPerWeek <= 1M ~= 1e26 wei,
// - shares <= max_{all time}(price * tokensPerWeek)
// the numerator is at most 1.8e54 < 2 * 2**180:
uint256 tokens = (userWeekShares[to][week] * tokensPerWeek(week)) / weekShares[week];
// By int division and the fact that all tokens have been minted, the
// following will not underflow. TODO: check/enforce
balanceOf[address(this)] -= tokens;
balanceOf[to] += tokens;
emit Transfer(address(this), to, tokens);
}
function tokensPerWeek(uint256 week) public pure returns (uint256) {
return week < 2 ? 1_000_000e18 : week < 50 ? 100_000e18 : week < 100 ? 50_000e18 : week < 150 ? 30_000e18 : week < 200 ? 20_000e18 : 0;
}
function tokensPerBlock() public view returns (uint256) {
uint256 elapsed = (block.timestamp - startTime) / WEEK;
return
elapsed < 2 ? 0 : elapsed < 50 ? 219_780e14 : elapsed < 100 ? 109_890e14 : elapsed < 150 ? 65_934e14 : elapsed < 200 ? 43_956e14 : 0;
}
function retrieveOperatorPayment(address to) public returns (bool success) {
require(msg.sender == DAO.operator(), "Not operator");
(success, ) = to.call{value: address(this).balance}("");
}
event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to);
event Harvest(address indexed user, uint256 indexed pid, uint256 amount);
event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed poolToken, IRewarder indexed rewarder);
event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite);
event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accTokensPerShare);
/// @notice Info of each Distributor user.
/// `amount` LP token amount the user has provided.
/// `rewardDebt` The amount of tokens entitled to the user.
struct UserInfo {
uint256 amount;
int256 rewardDebt;
}
/// @notice Info of each Distributor pool.
/// `allocPoint` The amount of allocation points assigned to the pool.
/// Also known as the amount of tokens to distribute per block.
struct PoolInfo {
uint128 accTokensPerShare;
uint64 lastRewardBlock;
uint64 allocPoint;
}
/// @notice Info of each Distributor pool.
PoolInfo[] public poolInfo;
/// @notice Address of the LP token for each Distributor pool.
IERC20[] public poolToken;
/// @notice Address of each `IRewarder` contract in Distributor.
IRewarder[] public rewarder;
/// @notice Info of each user that stakes LP tokens.
mapping(uint256 => mapping(address => UserInfo)) public userInfo;
/// @dev Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint;
// @notice The migrator contract. It has a lot of power. Can only be set through governance (owner).
IMigratorChef public migrator;
uint256 private constant ACC_TOKENS_PRECISION = 1e12;
/// @notice Returns the number of MCV2 pools.
function poolLength() public view returns (uint256 pools) {
pools = poolInfo.length;
}
/// @notice Add a new LP to the pool. Can only be called by the owner.
/// DO NOT add the same LP token more than once. Rewards will be messed up if you do.
/// @param allocPoint AP of the new pool.
/// @param poolToken_ Address of the LP ERC-20 token.
/// @param _rewarder Address of the rewarder delegate.
function addPool(
uint256 allocPoint,
IERC20 poolToken_,
IRewarder _rewarder
) public onlyDAO {
uint256 lastRewardBlock = block.number;
totalAllocPoint = totalAllocPoint.add(allocPoint);
poolToken.push(poolToken_);
rewarder.push(_rewarder);
poolInfo.push(PoolInfo({allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accTokensPerShare: 0}));
emit LogPoolAddition(poolToken.length.sub(1), allocPoint, poolToken_, _rewarder);
}
/// @notice Update the given pool's tokens allocation point and `IRewarder` contract. Can only be called by the owner.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _allocPoint New AP of the pool.
/// @param _rewarder Address of the rewarder delegate.
/// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored.
function setPool(
uint256 _pid,
uint256 _allocPoint,
IRewarder _rewarder,
bool overwrite
) public onlyDAO {
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint.to64();
if (overwrite) {
rewarder[_pid] = _rewarder;
}
emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite);
}
/// @notice Set the `migrator` contract. Can only be called by the owner.
/// @param _migrator The contract address to set.
function setMigrator(IMigratorChef _migrator) public onlyDAO {
migrator = _migrator;
}
/// @notice Migrate LP token to another LP contract through the `migrator` contract.
/// @param pid The index of the pool. See `poolInfo`.
function migratePool(uint256 pid) public {
require(address(migrator) != address(0), "No migrator");
IERC20 _poolToken = poolToken[pid];
uint256 bal = _poolToken.balanceOf(address(this));
_poolToken.approve(address(migrator), bal);
IERC20 newPoolToken = migrator.migrate(_poolToken);
require(bal == newPoolToken.balanceOf(address(this)), "Migrated balance mismatch");
poolToken[pid] = newPoolToken;
}
/// @notice View function to see pending tokens on frontend.
/// @param _pid The index of the pool. See `poolInfo`.
/// @param _user Address of user.
/// @return pending tokens reward for a given user.
function pendingTokens(uint256 _pid, address _user) external view returns (uint256 pending) {
PoolInfo memory pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accTokensPerShare = pool.accTokensPerShare;
uint256 lpSupply = poolToken[_pid].balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 tokensReward = blocks.mul(tokensPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
accTokensPerShare = accTokensPerShare.add(tokensReward.mul(ACC_TOKENS_PRECISION) / lpSupply);
}
pending = int256(user.amount.mul(accTokensPerShare) / ACC_TOKENS_PRECISION).sub(user.rewardDebt).toUInt256();
}
/// @notice Update reward variables for all pools. Be careful of gas spending!
/// @param pids Pool IDs of all to be updated. Make sure to update all active pools.
function massUpdatePools(uint256[] calldata pids) external {
uint256 len = pids.length;
for (uint256 i = 0; i < len; ++i) {
updatePool(pids[i]);
}
}
/// @notice Update reward variables of the given pool.
/// @param pid The index of the pool. See `poolInfo`.
/// @return pool Returns the pool that was updated.
function updatePool(uint256 pid) public returns (PoolInfo memory pool) {
pool = poolInfo[pid];
if (block.number > pool.lastRewardBlock) {
uint256 lpSupply = poolToken[pid].balanceOf(address(this));
if (lpSupply > 0) {
uint256 blocks = block.number.sub(pool.lastRewardBlock);
uint256 tokensReward = blocks.mul(tokensPerBlock()).mul(pool.allocPoint) / totalAllocPoint;
pool.accTokensPerShare = pool.accTokensPerShare.add((tokensReward.mul(ACC_TOKENS_PRECISION) / lpSupply).to128());
}
pool.lastRewardBlock = block.number.to64();
poolInfo[pid] = pool;
emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accTokensPerShare);
}
}
/// @notice Deposit LP tokens to Dictator DAO for token allocation.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to deposit.
/// @param to The receiver of `amount` deposit benefit.
function deposit(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][to];
// Effects
user.amount = user.amount.add(amount);
user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION));
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, to, to, 0, user.amount);
}
poolToken[pid].safeTransferFrom(msg.sender, address(this), amount);
emit Deposit(msg.sender, pid, amount, to);
}
/// @notice Withdraw LP tokens from MCV2.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens.
function withdraw(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
// Effects
user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, msg.sender, to, 0, user.amount);
}
poolToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
}
/// @notice Harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of tokens rewards.
function harvest(uint256 pid, address to) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedTokens = int256(user.amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION);
uint256 _pendingTokens = accumulatedTokens.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedTokens;
// Interactions
if (_pendingTokens != 0) {
balanceOf[address(this)] = balanceOf[address(this)].sub(_pendingTokens);
balanceOf[to] += _pendingTokens;
emit Transfer(address(this), to, _pendingTokens);
}
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, msg.sender, to, _pendingTokens, user.amount);
}
emit Harvest(msg.sender, pid, _pendingTokens);
}
/// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`.
/// @param pid The index of the pool. See `poolInfo`.
/// @param amount LP token amount to withdraw.
/// @param to Receiver of the LP tokens and tokens rewards.
function withdrawAndHarvest(
uint256 pid,
uint256 amount,
address to
) public {
PoolInfo memory pool = updatePool(pid);
UserInfo storage user = userInfo[pid][msg.sender];
int256 accumulatedTokens = int256(user.amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION);
uint256 _pendingTokens = accumulatedTokens.sub(user.rewardDebt).toUInt256();
// Effects
user.rewardDebt = accumulatedTokens.sub(int256(amount.mul(pool.accTokensPerShare) / ACC_TOKENS_PRECISION));
user.amount = user.amount.sub(amount);
// Interactions
balanceOf[address(this)] = balanceOf[address(this)].sub(_pendingTokens);
balanceOf[to] += _pendingTokens;
emit Transfer(address(this), to, _pendingTokens);
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, msg.sender, to, _pendingTokens, user.amount);
}
poolToken[pid].safeTransfer(to, amount);
emit Withdraw(msg.sender, pid, amount, to);
emit Harvest(msg.sender, pid, _pendingTokens);
}
/// @notice Withdraw without caring about rewards. EMERGENCY ONLY.
/// @param pid The index of the pool. See `poolInfo`.
/// @param to Receiver of the LP tokens.
function emergencyWithdraw(uint256 pid, address to) public {
UserInfo storage user = userInfo[pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
IRewarder _rewarder = rewarder[pid];
if (address(_rewarder) != address(0)) {
_rewarder.onTokensReward(pid, msg.sender, to, 0, 0);
}
// Note: transfer can fail or succeed if `amount` is zero.
poolToken[pid].safeTransfer(to, amount);
emit EmergencyWithdraw(msg.sender, pid, amount, to);
}
}
|
math is ok, because amount, totalSupply and shares is always 0 <= amount <= 100.000.000 10^18 theoretically you can grow the amount/share ratio, but it's not practical and useless TODO: Remove? Did we change our vote? Do this while we know our previous total: Safe, because the user must have added their balance before
|
function mint(uint256 amount, address operatorVote) public returns (bool) {
require(msg.sender != address(0), "Zero address");
User memory user = users[msg.sender];
uint256 totalTokens = token.balanceOf(address(this));
uint256 shares = totalSupply == 0 ? amount : (amount * totalSupply) / totalTokens;
address currentVote = userVote[msg.sender];
uint256 extraVotes = shares;
if (currentVote != operatorVote) {
if (user.balance > 0) {
votes[currentVote] -= user.balance;
extraVotes += user.balance;
}
userVote[msg.sender] = operatorVote;
}
votes[operatorVote] += extraVotes;
user.balance += shares.to128();
user.lockedUntil = (block.timestamp + 24 hours).to128();
users[msg.sender] = user;
totalSupply += shares;
token.transferFrom(msg.sender, address(this), amount);
emit Transfer(address(0), msg.sender, shares);
return true;
}
| 1,006,532 |
/**
*Submitted for verification at Etherscan.io on 2020-05-06
*/
pragma solidity ^0.4.24;
// File: /Users/matthewmcclure/repos/Token-Audit/node_modules/openzeppelin-zos/contracts/token/ERC20/ERC20Basic.sol
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
// File: /Users/matthewmcclure/repos/Token-Audit/node_modules/openzeppelin-zos/contracts/token/ERC20/ERC20.sol
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender) public view returns (uint256);
function transferFrom(address from, address to, uint256 value) public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// File: /Users/matthewmcclure/repos/Token-Audit/node_modules/openzeppelin-zos/contracts/token/ERC20/SafeERC20.sol
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure.
* To use this library you can add a `using SafeERC20 for ERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
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));
}
}
// File: /Users/matthewmcclure/repos/Token-Audit/node_modules/zos-lib/contracts/migrations/Migratable.sol
/**
* @title Migratable
* Helper contract to support intialization and migration schemes between
* different implementations of a contract in the context of upgradeability.
* To use it, replace the constructor with a function that has the
* `isInitializer` modifier starting with `"0"` as `migrationId`.
* When you want to apply some migration code during an upgrade, increase
* the `migrationId`. Or, if the migration code must be applied only after
* another migration has been already applied, use the `isMigration` modifier.
* This helper supports multiple inheritance.
* WARNING: It is the developer's responsibility to ensure that migrations are
* applied in a correct order, or that they are run at all.
* See `Initializable` for a simpler version.
*/
contract Migratable {
/**
* @dev Emitted when the contract applies a migration.
* @param contractName Name of the Contract.
* @param migrationId Identifier of the migration applied.
*/
event Migrated(string contractName, string migrationId);
/**
* @dev Mapping of the already applied migrations.
* (contractName => (migrationId => bool))
*/
mapping (string => mapping (string => bool)) internal migrated;
/**
* @dev Internal migration id used to specify that a contract has already been initialized.
*/
string constant private INITIALIZED_ID = "initialized";
/**
* @dev Modifier to use in the initialization function of a contract.
* @param contractName Name of the contract.
* @param migrationId Identifier of the migration.
*/
modifier isInitializer(string contractName, string migrationId) {
validateMigrationIsPending(contractName, INITIALIZED_ID);
validateMigrationIsPending(contractName, migrationId);
_;
emit Migrated(contractName, migrationId);
migrated[contractName][migrationId] = true;
migrated[contractName][INITIALIZED_ID] = true;
}
/**
* @dev Modifier to use in the migration of a contract.
* @param contractName Name of the contract.
* @param requiredMigrationId Identifier of the previous migration, required
* to apply new one.
* @param newMigrationId Identifier of the new migration to be applied.
*/
modifier isMigration(string contractName, string requiredMigrationId, string newMigrationId) {
require(isMigrated(contractName, requiredMigrationId), "Prerequisite migration ID has not been run yet");
validateMigrationIsPending(contractName, newMigrationId);
_;
emit Migrated(contractName, newMigrationId);
migrated[contractName][newMigrationId] = true;
}
/**
* @dev Returns true if the contract migration was applied.
* @param contractName Name of the contract.
* @param migrationId Identifier of the migration.
* @return true if the contract migration was applied, false otherwise.
*/
function isMigrated(string contractName, string migrationId) public view returns(bool) {
return migrated[contractName][migrationId];
}
/**
* @dev Initializer that marks the contract as initialized.
* It is important to run this if you had deployed a previous version of a Migratable contract.
* For more information see https://github.com/zeppelinos/zos-lib/issues/158.
*/
function initialize() isInitializer("Migratable", "1.2.1") public {
}
/**
* @dev Reverts if the requested migration was already executed.
* @param contractName Name of the contract.
* @param migrationId Identifier of the migration.
*/
function validateMigrationIsPending(string contractName, string migrationId) private {
require(!isMigrated(contractName, migrationId), "Requested target migration ID has already been run");
}
}
// File: /Users/matthewmcclure/repos/Token-Audit/node_modules/openzeppelin-zos/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 is Migratable {
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 initialize(address _sender) public isInitializer("Ownable", "1.9.0") {
owner = _sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: /Users/matthewmcclure/repos/Token-Audit/node_modules/openzeppelin-zos/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: /Users/matthewmcclure/repos/Token-Audit/contracts/Escrow.sol
/**
* @title Escrow
* @dev Escrow contract that works with RNDR token
* This contract holds tokens while render jobs are being completed
* and information on token allottment per job
*/
contract Escrow is Migratable, Ownable {
using SafeERC20 for ERC20;
using SafeMath for uint256;
// This is a mapping of job IDs to the number of tokens allotted to the job
mapping(string => uint256) private jobBalances;
// This is the address of the render token contract
address public renderTokenAddress;
// This is the address with authority to call the disburseJob function
address public disbursalAddress;
// Emit new disbursal address when disbursalAddress has been changed
event DisbursalAddressUpdate(address disbursalAddress);
// Emit the jobId along with the new balance of the job
// Used on job creation, additional funding added to jobs, and job disbursal
// Internal systems for assigning jobs will watch this event to determine balances available
event JobBalanceUpdate(string _jobId, uint256 _balance);
// Emit new contract address when renderTokenAddress has been changed
event RenderTokenAddressUpdate(address renderTokenAddress);
/**
* @dev Modifier to check if the message sender can call the disburseJob function
*/
modifier canDisburse() {
require(msg.sender == disbursalAddress, "message sender not authorized to disburse funds");
_;
}
/**
* @dev Initailization
* @param _owner because this contract uses proxies, owner must be passed in as a param
* @param _renderTokenAddress see renderTokenAddress
*/
function initialize (address _owner, address _renderTokenAddress) public isInitializer("Escrow", "0") {
require(_owner != address(0), "_owner must not be null");
require(_renderTokenAddress != address(0), "_renderTokenAddress must not be null");
Ownable.initialize(_owner);
disbursalAddress = _owner;
renderTokenAddress = _renderTokenAddress;
}
/**
* @dev Change the address authorized to distribute tokens for completed jobs
*
* Because there are no on-chain details to indicate who performed a render, an outside
* system must call the disburseJob function with the information needed to properly
* distribute tokens. This function updates the address with the authority to perform distributions
* @param _newDisbursalAddress see disbursalAddress
*/
function changeDisbursalAddress(address _newDisbursalAddress) external onlyOwner {
disbursalAddress = _newDisbursalAddress;
emit DisbursalAddressUpdate(disbursalAddress);
}
/**
* @dev Change the address allowances will be sent to after job completion
*
* Ideally, this will not be used, but is included as a failsafe.
* RNDR is still in its infancy, and changes may need to be made to this
* contract and / or the renderToken contract. Including methods to update the
* addresses allows the contracts to update independently.
* If the RNDR token contract is ever migrated to another address for
* either added security or functionality, this will need to be called.
* @param _newRenderTokenAddress see renderTokenAddress
*/
function changeRenderTokenAddress(address _newRenderTokenAddress) external onlyOwner {
require(_newRenderTokenAddress != address(0), "_newRenderTokenAddress must not be null");
renderTokenAddress = _newRenderTokenAddress;
emit RenderTokenAddressUpdate(renderTokenAddress);
}
/**
* @dev Send allowances to node(s) that performed a job
*
* This can only be called by the disbursalAddress, an accound owned
* by OTOY, and it provides the number of tokens to send to each node
* @param _jobId the ID of the job used in the jobBalances mapping
* @param _recipients the address(es) of the nodes that performed rendering
* @param _amounts the amount(s) to send to each address. These must be in the same
* order as the recipient addresses
*/
function disburseJob(string _jobId, address[] _recipients, uint256[] _amounts) external canDisburse {
require(jobBalances[_jobId] > 0, "_jobId has no available balance");
require(_recipients.length == _amounts.length, "_recipients and _amounts must be the same length");
for(uint256 i = 0; i < _recipients.length; i++) {
jobBalances[_jobId] = jobBalances[_jobId].sub(_amounts[i]);
ERC20(renderTokenAddress).safeTransfer(_recipients[i], _amounts[i]);
}
emit JobBalanceUpdate(_jobId, jobBalances[_jobId]);
}
/**
* @dev Add RNDR tokens to a job
*
* This can only be called by a function on the RNDR token contract
* @param _jobId the ID of the job used in the jobBalances mapping
* @param _tokens the number of tokens sent by the artist to fund the job
*/
function fundJob(string _jobId, uint256 _tokens) external {
// Jobs can only be created by the address stored in the renderTokenAddress variable
require(msg.sender == renderTokenAddress, "message sender not authorized");
jobBalances[_jobId] = jobBalances[_jobId].add(_tokens);
emit JobBalanceUpdate(_jobId, jobBalances[_jobId]);
}
/**
* @dev See the tokens available for a job
*
* @param _jobId the ID used to lookup the job balance
*/
function jobBalance(string _jobId) external view returns(uint256) {
return jobBalances[_jobId];
}
}
// File: /Users/matthewmcclure/repos/Token-Audit/contracts/MigratableERC20.sol
/**
* @title MigratableERC20
* @dev This strategy carries out an optional migration of the token balances. This migration is performed and paid for
* @dev by the token holders. The new token contract starts with no initial supply and no balances. The only way to
* @dev "mint" the new tokens is for users to "turn in" their old ones. This is done by first approving the amount they
* @dev want to migrate via `ERC20.approve(newTokenAddress, amountToMigrate)` and then calling a function of the new
* @dev token called `migrateTokens`. The old tokens are sent to a burn address, and the holder receives an equal amount
* @dev in the new contract.
*/
contract MigratableERC20 is Migratable {
using SafeERC20 for ERC20;
/// Burn address where the old tokens are going to be transferred
address public constant BURN_ADDRESS = address(0xdead);
/// Address of the old token contract
ERC20 public legacyToken;
/**
* @dev Initializes the new token contract
* @param _legacyToken address of the old token contract
*/
function initialize(address _legacyToken) isInitializer("OptInERC20Migration", "1.9.0") public {
legacyToken = ERC20(_legacyToken);
}
/**
* @dev Migrates the total balance of the token holder to this token contract
* @dev This function will burn the old token balance and mint the same balance in the new token contract
*/
function migrate() public {
uint256 amount = legacyToken.balanceOf(msg.sender);
migrateToken(amount);
}
/**
* @dev Migrates the given amount of old-token balance to the new token contract
* @dev This function will burn a given amount of tokens from the old contract and mint the same amount in the new one
* @param _amount uint256 representing the amount of tokens to be migrated
*/
function migrateToken(uint256 _amount) public {
migrateTokenTo(msg.sender, _amount);
}
/**
* @dev Burns a given amount of the old token contract for a token holder and mints the same amount of
* @dev new tokens for a given recipient address
* @param _amount uint256 representing the amount of tokens to be migrated
* @param _to address the recipient that will receive the new minted tokens
*/
function migrateTokenTo(address _to, uint256 _amount) public {
_mintMigratedTokens(_to, _amount);
legacyToken.safeTransferFrom(msg.sender, BURN_ADDRESS, _amount);
}
/**
* @dev Internal minting function
* This function must be overwritten by the implementation
*/
function _mintMigratedTokens(address _to, uint256 _amount) internal;
}
// File: /Users/matthewmcclure/repos/Token-Audit/node_modules/openzeppelin-zos/contracts/token/ERC20/BasicToken.sol
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
// File: /Users/matthewmcclure/repos/Token-Audit/node_modules/openzeppelin-zos/contracts/token/ERC20/StandardToken.sol
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(address _from, address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(address _owner, address _spender) public view returns (uint256) {
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
// File: contracts/RenderToken.sol
// Escrow constract
/**
* @title RenderToken
* @dev ERC20 mintable token
* The token will be minted by the crowdsale contract only
*/
contract RenderToken is Migratable, MigratableERC20, Ownable, StandardToken {
string public constant name = "Render Token";
string public constant symbol = "RNDR";
uint8 public constant decimals = 18;
// The address of the contract that manages job balances. Address is used for forwarding tokens
// that come in to fund jobs
address public escrowContractAddress;
// Emit new contract address when escrowContractAddress has been changed
event EscrowContractAddressUpdate(address escrowContractAddress);
// Emit information related to tokens being escrowed
event TokensEscrowed(address indexed sender, string jobId, uint256 amount);
// Emit information related to legacy tokens being migrated
event TokenMigration(address indexed receiver, uint256 amount);
/**
* @dev Initailization
* @param _owner because this contract uses proxies, owner must be passed in as a param
*/
function initialize(address _owner, address _legacyToken) public isInitializer("RenderToken", "0") {
require(_owner != address(0), "_owner must not be null");
require(_legacyToken != address(0), "_legacyToken must not be null");
Ownable.initialize(_owner);
MigratableERC20.initialize(_legacyToken);
}
/**
* @dev Take tokens prior to beginning a job
*
* This function is called by the artist, and it will transfer tokens
* to a separate escrow contract to be held until the job is completed
* @param _jobID is the ID of the job used within the ORC backend
* @param _amount is the number of RNDR tokens being held in escrow
*/
function holdInEscrow(string _jobID, uint256 _amount) public {
require(transfer(escrowContractAddress, _amount), "token transfer to escrow address failed");
Escrow(escrowContractAddress).fundJob(_jobID, _amount);
emit TokensEscrowed(msg.sender, _jobID, _amount);
}
/**
* @dev Mints new tokens equal to the amount of legacy tokens burned
*
* This function is called internally, but triggered by a user choosing to
* migrate their balance.
* @param _to is the address tokens will be sent to
* @param _amount is the number of RNDR tokens being sent to the address
*/
function _mintMigratedTokens(address _to, uint256 _amount) internal {
require(_to != address(0), "_to address must not be null");
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit TokenMigration(_to, _amount);
emit Transfer(address(0), _to, _amount);
}
/**
* @dev Set the address of the escrow contract
*
* This will dictate the contract that will hold tokens in escrow and keep
* a ledger of funds available for jobs.
* RNDR is still in its infancy, and changes may need to be made to this
* contract and / or the escrow contract. Including methods to update the
* addresses allows the contracts to update independently.
* If the escrow contract is ever migrated to another address for
* either added security or functionality, this will need to be called.
* @param _escrowAddress see escrowContractAddress
*/
function setEscrowContractAddress(address _escrowAddress) public onlyOwner {
require(_escrowAddress != address(0), "_escrowAddress must not be null");
escrowContractAddress = _escrowAddress;
emit EscrowContractAddressUpdate(escrowContractAddress);
}
}
|
Migrates the total balance of the token holder to this token contract This function will burn the old token balance and mint the same balance in the new token contract/
|
function migrate() public {
uint256 amount = legacyToken.balanceOf(msg.sender);
migrateToken(amount);
}
| 14,998,961 |
pragma solidity >=0.4.21 <0.6.0;
pragma experimental ABIEncoderV2;
import "./Retraction.sol";
contract SalesContract is Retraction {
event PaidItem(
address seller,
address buyer,
uint price
);
event ContractIsSettled(
address seller,
address buyer,
uint price
);
event SetItem(
string name,
uint price
);
struct Item {
string name;
uint price;
bool itemReceived;
bool itemPaid;
}
Item public item;
bool public itemIsSet = false;
/**
* Constructor
* Sets the buyer and the intermediator
*/
constructor(address payable _buyer, address _intermediator)
public
{
buyer = _buyer;
intermediator = _intermediator;
}
/**
* Pay item
* Modifier: only buyer, contractIntact == true, msg.value == price
*/
function payItem()
public
payable
onlyBy(buyer)
contractIntact()
contractIsRetracted(false)
itemAlreadySet()
paymentGreaterOrEqualPrice()
{
item.itemPaid = true;
emit PaidItem(seller, msg.sender, msg.value);
}
/**
* Item is received
* If item is received buyer can call this function
* Modifier: only buyer, itemPaid == true
*/
function itemReceived()
public
onlyBy(buyer)
itemIsPaid()
{
item.itemReceived = true;
}
/**
* Withdraw
* Seller can withdraw money
* Modifier: only seller, itemReceived == true, contractIsClosed == true, contractRetracted == false
*/
function withdraw()
public
onlyBySellerOrBuyer()
contractIntact()
{
if(contractRetracted) {
if(buyerIsPaidBack) {
require(
msg.sender == buyer,
"Sender is not the allowed to perform this action."
);
} else {
require(
msg.sender == seller,
"Sender is not the allowed to perform this action."
);
}
emit WithdrawalFromRetraction(msg.sender, item.price);
} else {
require(
item.itemReceived == true,
"Item must be marked as received to withdraw money, please contact the buyer."
);
require(
msg.sender == seller,
"Sender is not the allowed to perform this action."
);
}
assert(address(this).balance > 0);
contractIsClosed = true;
msg.sender.transfer(item.price);
emit ContractIsSettled(msg.sender, buyer, item.price);
}
/**
* Setter
* Sets the Item (name, price, default itemPaid, default itemReceived)
*/
function setItem(string memory _name, uint _price)
public
onlyBy(seller)
itemIsNotSet()
{
item.name = _name;
item.price = _price;
item.itemPaid = false;
item.itemReceived = false;
itemIsSet = true;
}
/**
* Getter
* Get the current Item
*/
function getItem()
public
view
returns (Item memory i)
{
return item;
}
/**
* Getter
* Get Status if item is received
*/
function getItemReceivedStatus()
public
view
returns (bool)
{
return item.itemReceived;
}
/**
* Getter
* Get flag if item is set
*/
function getItemIsSet()
public
view
returns (bool)
{
return itemIsSet;
}
/**
* Getter
* Get Balance of contract
* Assertion: Balance must be null or price of item
*/
function getContractBalance() public view returns (uint) {
assert(address(this).balance == 0 || address(this).balance == item.price);
return address(this).balance;
}
/**
* Modifier
* Check if item is paid
*/
modifier itemIsPaid()
{
require(
item.itemPaid == true,
"Item not paid"
);
_;
}
/**
* Modifier
* Check if item is received
*/
modifier itemIsReceived()
{
require(
item.itemReceived == true,
"Item not received"
);
_;
}
/**
* Modifier
* Check if value of msg sender is equal to price of item
*/
modifier paymentGreaterOrEqualPrice()
{
require(
msg.value >= item.price,
"The paid amount was not equal to the listed price of the item"
);
_;
}
/**
* Modifier
* Check if item is set
*/
modifier itemIsNotSet()
{
require(
itemIsSet == false,
"Item can only be set once"
);
_;
}
/**
* Modifier
* Check if item is set
*/
modifier itemAlreadySet()
{
require(
itemIsSet == true,
"Item is not set"
);
_;
}
}
|
Setter Sets the Item (name, price, default itemPaid, default itemReceived)/
|
function setItem(string memory _name, uint _price)
public
onlyBy(seller)
itemIsNotSet()
{
item.name = _name;
item.price = _price;
item.itemPaid = false;
item.itemReceived = false;
itemIsSet = true;
}
| 12,965,645 |
pragma solidity ^0.4.19;
contract IGold {
function balanceOf(address _owner) constant returns (uint256);
function issueTokens(address _who, uint _tokens);
function burnTokens(address _who, uint _tokens);
}
// StdToken inheritance is commented, because no 'totalSupply' needed
contract IMNTP { /*is StdToken */
function balanceOf(address _owner) constant returns (uint256);
// Additional methods that MNTP contract provides
function lockTransfer(bool _lock);
function issueTokens(address _who, uint _tokens);
function burnTokens(address _who, uint _tokens);
}
contract SafeMath {
function safeAdd(uint a, uint b) internal returns (uint) {
uint c = a + b;
assert(c>=a && c>=b);
return c;
}
function safeSub(uint a, uint b) internal returns (uint) {
assert(b <= a);
return a - b;
}
}
contract CreatorEnabled {
address public creator = 0x0;
modifier onlyCreator() { require(msg.sender == creator); _; }
function changeCreator(address _to) public onlyCreator {
creator = _to;
}
}
contract StringMover {
function stringToBytes32(string s) constant returns(bytes32){
bytes32 out;
assembly {
out := mload(add(s, 32))
}
return out;
}
function stringToBytes64(string s) constant returns(bytes32,bytes32){
bytes32 out;
bytes32 out2;
assembly {
out := mload(add(s, 32))
out2 := mload(add(s, 64))
}
return (out,out2);
}
function bytes32ToString(bytes32 x) constant returns (string) {
bytes memory bytesString = new bytes(32);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
function bytes64ToString(bytes32 x, bytes32 y) constant returns (string) {
bytes memory bytesString = new bytes(64);
uint charCount = 0;
for (uint j = 0; j < 32; j++) {
byte char = byte(bytes32(uint(x) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
for (j = 0; j < 32; j++) {
char = byte(bytes32(uint(y) * 2 ** (8 * j)));
if (char != 0) {
bytesString[charCount] = char;
charCount++;
}
}
bytes memory bytesStringTrimmed = new bytes(charCount);
for (j = 0; j < charCount; j++) {
bytesStringTrimmed[j] = bytesString[j];
}
return string(bytesStringTrimmed);
}
}
contract Storage is SafeMath, StringMover {
function Storage() public {
controllerAddress = msg.sender;
}
address public controllerAddress = 0x0;
modifier onlyController() { require(msg.sender==controllerAddress); _; }
function setControllerAddress(address _newController) onlyController {
controllerAddress = _newController;
}
address public hotWalletAddress = 0x0;
function setHotWalletAddress(address _address) onlyController {
hotWalletAddress = _address;
}
// Fields - 1
mapping(uint => string) docs;
uint public docCount = 0;
// Fields - 2
mapping(string => mapping(uint => int)) fiatTxs;
mapping(string => uint) fiatBalancesCents;
mapping(string => uint) fiatTxCounts;
uint fiatTxTotal = 0;
// Fields - 3
mapping(string => mapping(uint => int)) goldTxs;
mapping(string => uint) goldHotBalances;
mapping(string => uint) goldTxCounts;
uint goldTxTotal = 0;
// Fields - 4
struct Request {
address sender;
string userId;
string requestHash;
bool buyRequest; // otherwise - sell
// 0 - init
// 1 - processed
// 2 - cancelled
uint8 state;
}
mapping (uint=>Request) requests;
uint public requestsCount = 0;
///////
function addDoc(string _ipfsDocLink) public onlyController returns(uint) {
docs[docCount] = _ipfsDocLink;
uint out = docCount;
docCount++;
return out;
}
function getDocCount() public constant returns (uint) {
return docCount;
}
function getDocAsBytes64(uint _index) public constant returns (bytes32,bytes32) {
require(_index < docCount);
return stringToBytes64(docs[_index]);
}
function addFiatTransaction(string _userId, int _amountCents) public onlyController returns(uint) {
require(0 != _amountCents);
uint c = fiatTxCounts[_userId];
fiatTxs[_userId][c] = _amountCents;
if (_amountCents > 0) {
fiatBalancesCents[_userId] = safeAdd(fiatBalancesCents[_userId], uint(_amountCents));
} else {
fiatBalancesCents[_userId] = safeSub(fiatBalancesCents[_userId], uint(-_amountCents));
}
fiatTxCounts[_userId] = safeAdd(fiatTxCounts[_userId], 1);
fiatTxTotal++;
return c;
}
function getFiatTransactionsCount(string _userId) public constant returns (uint) {
return fiatTxCounts[_userId];
}
function getAllFiatTransactionsCount() public constant returns (uint) {
return fiatTxTotal;
}
function getFiatTransaction(string _userId, uint _index) public constant returns(int) {
require(_index < fiatTxCounts[_userId]);
return fiatTxs[_userId][_index];
}
function getUserFiatBalance(string _userId) public constant returns(uint) {
return fiatBalancesCents[_userId];
}
function addGoldTransaction(string _userId, int _amount) public onlyController returns(uint) {
require(0 != _amount);
uint c = goldTxCounts[_userId];
goldTxs[_userId][c] = _amount;
if (_amount > 0) {
goldHotBalances[_userId] = safeAdd(goldHotBalances[_userId], uint(_amount));
} else {
goldHotBalances[_userId] = safeSub(goldHotBalances[_userId], uint(-_amount));
}
goldTxCounts[_userId] = safeAdd(goldTxCounts[_userId], 1);
goldTxTotal++;
return c;
}
function getGoldTransactionsCount(string _userId) public constant returns (uint) {
return goldTxCounts[_userId];
}
function getAllGoldTransactionsCount() public constant returns (uint) {
return goldTxTotal;
}
function getGoldTransaction(string _userId, uint _index) public constant returns(int) {
require(_index < goldTxCounts[_userId]);
return goldTxs[_userId][_index];
}
function getUserHotGoldBalance(string _userId) public constant returns(uint) {
return goldHotBalances[_userId];
}
function addBuyTokensRequest(address _who, string _userId, string _requestHash) public onlyController returns(uint) {
Request memory r;
r.sender = _who;
r.userId = _userId;
r.requestHash = _requestHash;
r.buyRequest = true;
r.state = 0;
requests[requestsCount] = r;
uint out = requestsCount;
requestsCount++;
return out;
}
function addSellTokensRequest(address _who, string _userId, string _requestHash) onlyController returns(uint) {
Request memory r;
r.sender = _who;
r.userId = _userId;
r.requestHash = _requestHash;
r.buyRequest = false;
r.state = 0;
requests[requestsCount] = r;
uint out = requestsCount;
requestsCount++;
return out;
}
function getRequestsCount() public constant returns(uint) {
return requestsCount;
}
function getRequest(uint _index) public constant returns(
address a,
bytes32 userId,
bytes32 hashA, bytes32 hashB,
bool buy, uint8 state)
{
require(_index < requestsCount);
Request memory r = requests[_index];
bytes32 userBytes = stringToBytes32(r.userId);
var (out1, out2) = stringToBytes64(r.requestHash);
return (r.sender, userBytes, out1, out2, r.buyRequest, r.state);
}
function cancelRequest(uint _index) onlyController public {
require(_index < requestsCount);
require(0==requests[_index].state);
requests[_index].state = 2;
}
function setRequestProcessed(uint _index) onlyController public {
requests[_index].state = 1;
}
}
contract GoldFiatFee is CreatorEnabled, StringMover {
string gmUserId = "";
// Functions:
function GoldFiatFee(string _gmUserId) {
creator = msg.sender;
gmUserId = _gmUserId;
}
function getGoldmintFeeAccount() public constant returns(bytes32) {
bytes32 userBytes = stringToBytes32(gmUserId);
return userBytes;
}
function setGoldmintFeeAccount(string _gmUserId) public onlyCreator {
gmUserId = _gmUserId;
}
function calculateBuyGoldFee(uint _mntpBalance, uint _goldValue) public constant returns(uint) {
return 0;
}
function calculateSellGoldFee(uint _mntpBalance, uint _goldValue) public constant returns(uint) {
// If the sender holds 0 MNTP, then the transaction fee is 3% fiat,
// If the sender holds at least 10 MNTP, then the transaction fee is 2% fiat,
// If the sender holds at least 1000 MNTP, then the transaction fee is 1.5% fiat,
// If the sender holds at least 10000 MNTP, then the transaction fee is 1% fiat,
if (_mntpBalance >= (10000 * 1 ether)) {
return (75 * _goldValue / 10000);
}
if (_mntpBalance >= (1000 * 1 ether)) {
return (15 * _goldValue / 1000);
}
if (_mntpBalance >= (10 * 1 ether)) {
return (25 * _goldValue / 1000);
}
// 3%
return (3 * _goldValue / 100);
}
}
contract IGoldFiatFee {
function getGoldmintFeeAccount()public constant returns(bytes32);
function calculateBuyGoldFee(uint _mntpBalance, uint _goldValue) public constant returns(uint);
function calculateSellGoldFee(uint _mntpBalance, uint _goldValue) public constant returns(uint);
}
contract StorageController is SafeMath, CreatorEnabled, StringMover {
Storage public stor;
IMNTP public mntpToken;
IGold public goldToken;
IGoldFiatFee public fiatFee;
address public ethDepositAddress = 0x0;
address public managerAddress = 0x0;
event NewTokenBuyRequest(address indexed _from, string indexed _userId);
event NewTokenSellRequest(address indexed _from, string indexed _userId);
event RequestCancelled(uint indexed _reqId);
event RequestProcessed(uint indexed _reqId);
event EthDeposited(uint indexed _requestId, address indexed _address, uint _ethValue);
modifier onlyManagerOrCreator() { require(msg.sender == managerAddress || msg.sender == creator); _; }
function StorageController(address _mntpContractAddress, address _goldContractAddress, address _storageAddress, address _fiatFeeContract) {
creator = msg.sender;
if (0 != _storageAddress) {
// use existing storage
stor = Storage(_storageAddress);
} else {
stor = new Storage();
}
require(0x0!=_mntpContractAddress);
require(0x0!=_goldContractAddress);
require(0x0!=_fiatFeeContract);
mntpToken = IMNTP(_mntpContractAddress);
goldToken = IGold(_goldContractAddress);
fiatFee = IGoldFiatFee(_fiatFeeContract);
}
function setEthDepositAddress(address _address) public onlyCreator {
ethDepositAddress = _address;
}
function setManagerAddress(address _address) public onlyCreator {
managerAddress = _address;
}
function getEthDepositAddress() public constant returns (address) {
return ethDepositAddress;
}
// Only old controller can call setControllerAddress
function changeController(address _newController) public onlyCreator {
stor.setControllerAddress(_newController);
}
function setHotWalletAddress(address _hotWalletAddress) public onlyCreator {
stor.setHotWalletAddress(_hotWalletAddress);
}
function getHotWalletAddress() public constant returns (address) {
return stor.hotWalletAddress();
}
function changeFiatFeeContract(address _newFiatFee) public onlyCreator {
fiatFee = IGoldFiatFee(_newFiatFee);
}
function addDoc(string _ipfsDocLink) public onlyCreator returns(uint) {
return stor.addDoc(_ipfsDocLink);
}
function getDocCount() public constant returns (uint) {
return stor.docCount();
}
function getDoc(uint _index) public constant returns (string) {
var (x, y) = stor.getDocAsBytes64(_index);
return bytes64ToString(x,y);
}
// _amountCents can be negative
// returns index in user array
function addFiatTransaction(string _userId, int _amountCents) public onlyManagerOrCreator returns(uint) {
return stor.addFiatTransaction(_userId, _amountCents);
}
function getFiatTransactionsCount(string _userId) public constant returns (uint) {
return stor.getFiatTransactionsCount(_userId);
}
function getAllFiatTransactionsCount() public constant returns (uint) {
return stor.getAllFiatTransactionsCount();
}
function getFiatTransaction(string _userId, uint _index) public constant returns(int) {
return stor.getFiatTransaction(_userId, _index);
}
function getUserFiatBalance(string _userId) public constant returns(uint) {
return stor.getUserFiatBalance(_userId);
}
function addGoldTransaction(string _userId, int _amount) public onlyManagerOrCreator returns(uint) {
return stor.addGoldTransaction(_userId, _amount);
}
function getGoldTransactionsCount(string _userId) public constant returns (uint) {
return stor.getGoldTransactionsCount(_userId);
}
function getAllGoldTransactionsCount() public constant returns (uint) {
return stor.getAllGoldTransactionsCount();
}
function getGoldTransaction(string _userId, uint _index) public constant returns(int) {
require(keccak256(_userId) != keccak256(""));
return stor.getGoldTransaction(_userId, _index);
}
function getUserHotGoldBalance(string _userId) public constant returns(uint) {
require(keccak256(_userId) != keccak256(""));
return stor.getUserHotGoldBalance(_userId);
}
function addBuyTokensRequest(string _userId, string _requestHash) public returns(uint) {
require(keccak256(_userId) != keccak256(""));
NewTokenBuyRequest(msg.sender, _userId);
return stor.addBuyTokensRequest(msg.sender, _userId, _requestHash);
}
function addSellTokensRequest(string _userId, string _requestHash) public returns(uint) {
require(keccak256(_userId) != keccak256(""));
NewTokenSellRequest(msg.sender, _userId);
return stor.addSellTokensRequest(msg.sender, _userId, _requestHash);
}
function getRequestsCount() public constant returns(uint) {
return stor.getRequestsCount();
}
function getRequest(uint _index) public constant returns(address, string, string, bool, uint8) {
var (sender, userIdBytes, hashA, hashB, buy, state) = stor.getRequest(_index);
string memory userId = bytes32ToString(userIdBytes);
string memory hash = bytes64ToString(hashA, hashB);
return (sender, userId, hash, buy, state);
}
function cancelRequest(uint _index) onlyManagerOrCreator public {
RequestCancelled(_index);
stor.cancelRequest(_index);
}
function processRequest(uint _index, uint _amountCents, uint _centsPerGold) onlyManagerOrCreator public {
require(_index < getRequestsCount());
var (sender, userId, hash, isBuy, state) = getRequest(_index);
require(0 == state);
if (isBuy) {
processBuyRequest(userId, sender, _amountCents, _centsPerGold);
} else {
processSellRequest(userId, sender, _amountCents, _centsPerGold);
}
// 3 - update state
stor.setRequestProcessed(_index);
// 4 - send event
RequestProcessed(_index);
}
function processBuyRequest(string _userId, address _userAddress, uint _amountCents, uint _centsPerGold) internal {
require(keccak256(_userId) != keccak256(""));
uint userFiatBalance = getUserFiatBalance(_userId);
require(userFiatBalance > 0);
if (_amountCents > userFiatBalance) {
_amountCents = userFiatBalance;
}
uint userMntpBalance = mntpToken.balanceOf(_userAddress);
uint fee = fiatFee.calculateBuyGoldFee(userMntpBalance, _amountCents);
require(_amountCents > fee);
// 1 - issue tokens minus fee
uint amountMinusFee = _amountCents;
if (fee > 0) {
amountMinusFee = safeSub(_amountCents, fee);
}
require(amountMinusFee > 0);
uint tokens = (uint(amountMinusFee) * 1 ether) / _centsPerGold;
issueGoldTokens(_userAddress, tokens);
// request from hot wallet
if (isHotWallet(_userAddress)) {
addGoldTransaction(_userId, int(tokens));
}
// 2 - add fiat tx
// negative for buy (total amount including fee!)
addFiatTransaction(_userId, - int(_amountCents));
// 3 - send fee to Goldmint
// positive for sell
if (fee > 0) {
string memory gmAccount = bytes32ToString(fiatFee.getGoldmintFeeAccount());
addFiatTransaction(gmAccount, int(fee));
}
}
function processSellRequest(string _userId, address _userAddress, uint _amountCents, uint _centsPerGold) internal {
require(keccak256(_userId) != keccak256(""));
uint tokens = (uint(_amountCents) * 1 ether) / _centsPerGold;
uint tokenBalance = goldToken.balanceOf(_userAddress);
if (isHotWallet(_userAddress)) {
tokenBalance = getUserHotGoldBalance(_userId);
}
if (tokenBalance < tokens) {
tokens = tokenBalance;
_amountCents = uint((tokens * _centsPerGold) / 1 ether);
}
burnGoldTokens(_userAddress, tokens);
// request from hot wallet
if (isHotWallet(_userAddress)) {
addGoldTransaction(_userId, - int(tokens));
}
// 2 - add fiat tx
uint userMntpBalance = mntpToken.balanceOf(_userAddress);
uint fee = fiatFee.calculateSellGoldFee(userMntpBalance, _amountCents);
require(_amountCents > fee);
uint amountMinusFee = _amountCents;
if (fee > 0) {
amountMinusFee = safeSub(_amountCents, fee);
}
require(amountMinusFee > 0);
// positive for sell
addFiatTransaction(_userId, int(amountMinusFee));
// 3 - send fee to Goldmint
if (fee > 0) {
string memory gmAccount = bytes32ToString(fiatFee.getGoldmintFeeAccount());
addFiatTransaction(gmAccount, int(fee));
}
}
//////// INTERNAL REQUESTS FROM HOT WALLET
function processInternalRequest(string _userId, bool _isBuy, uint _amountCents, uint _centsPerGold) onlyManagerOrCreator public {
if (_isBuy) {
processBuyRequest(_userId, getHotWalletAddress(), _amountCents, _centsPerGold);
} else {
processSellRequest(_userId, getHotWalletAddress(), _amountCents, _centsPerGold);
}
}
function transferGoldFromHotWallet(address _to, uint _value, string _userId) onlyManagerOrCreator public {
require(keccak256(_userId) != keccak256(""));
uint balance = getUserHotGoldBalance(_userId);
require(balance >= _value);
goldToken.burnTokens(getHotWalletAddress(), _value);
goldToken.issueTokens(_to, _value);
addGoldTransaction(_userId, -int(_value));
}
////////
function issueGoldTokens(address _userAddress, uint _tokenAmount) internal {
require(0!=_tokenAmount);
goldToken.issueTokens(_userAddress, _tokenAmount);
}
function burnGoldTokens(address _userAddress, uint _tokenAmount) internal {
require(0!=_tokenAmount);
goldToken.burnTokens(_userAddress, _tokenAmount);
}
function isHotWallet(address _address) internal returns(bool) {
return _address == getHotWalletAddress();
}
///////
function depositEth(uint _requestId) public payable {
require(ethDepositAddress != 0x0);
//min deposit is 0.01 ETH
require(msg.value >= 0.01 * 1 ether);
ethDepositAddress.transfer(msg.value);
EthDeposited(_requestId, msg.sender, msg.value);
}
// do not allow to send money to this contract...
function() external payable {
revert();
}
}
|
// INTERNAL REQUESTS FROM HOT WALLET
|
function processInternalRequest(string _userId, bool _isBuy, uint _amountCents, uint _centsPerGold) onlyManagerOrCreator public {
if (_isBuy) {
processBuyRequest(_userId, getHotWalletAddress(), _amountCents, _centsPerGold);
processSellRequest(_userId, getHotWalletAddress(), _amountCents, _centsPerGold);
}
}
| 6,321,647 |
./partial_match/1/0x3A2B16cA90ea56d34A00898850C52B1F1f2dAe26/sources/contracts/Votium.sol
|
evenly split deposit across multiple gauges in multiple rounds
|
function depositSplitGaugesRounds(
address _token,
uint256 _amount,
uint256 _numRounds,
address[] memory _gauges,
uint256 _maxPerVote,
address[] memory _excluded
) public {
require(_numRounds < 8, "!farFuture");
require(_numRounds > 1, "!numRounds");
require(_gauges.length > 1, "!gauges");
require(_amount > 0, "!amount");
uint256 totalDeposit = _amount * _numRounds * _gauges.length;
_takeDeposit(_token, totalDeposit);
uint256 rewardTotal = _amount - ((_amount * platformFee) / DENOMINATOR);
virtualBalance[_token] += rewardTotal * _numRounds * _gauges.length;
uint256 round = activeRound();
Incentive memory incentive = Incentive({
token: _token,
amount: rewardTotal,
maxPerVote: _maxPerVote,
distributed: 0,
recycled: 0,
depositor: msg.sender,
excluded: _excluded
});
for (uint256 i = 0; i < _numRounds; i++) {
_maintainUserRounds(round + i);
for (uint256 j = 0; j < _gauges.length; j++) {
incentives[round + i][_gauges[j]].push(incentive);
userDeposits[msg.sender][round + i][_gauges[j]].push(
incentives[round + i][_gauges[j]].length - 1
);
_maintainGaugeArrays(round + i, _gauges[j]);
emit NewIncentive(
_token,
rewardTotal,
round + i,
_gauges[j],
_maxPerVote,
false
);
}
}
}
| 15,666,860 |
./full_match/1/0x3dCA17feE19A6A3eA43526dF848ed0565165AFa2/sources/contracts/single.sol
|
Same as {xref-BEP721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is forwarded in {IBEP721Receiver-onBEP721Received} to contract recipients./
|
function _safeMint(
address to,
uint256 tokenId,
bytes memory _data
) internal virtual {
_mint(to, tokenId);
require(
_checkOnBEP721Received(address(0), to, tokenId, _data),
"BEP721: transfer to non BEP721Receiver implementer"
);
}
| 3,096,658 |
//SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.7.1;
pragma experimental ABIEncoderV2;
// import '@nomiclabs/buidler/console.sol';
import "./ERC1155.sol";
import "./IERC1155Views.sol";
contract TokensFlow is ERC1155, IERC1155Views {
using SafeMath for uint256;
using Address for address;
// See also _createSwapLimit()
struct SwapLimit {
bool recurring;
int256 initialSwapCredit;
int256 maxSwapCredit;
int swapCreditPeriod;
int firstTimeEnteredSwapCredit;
bytes32 hash;
}
struct TokenFlow {
uint256 parentToken;
SwapLimit limit;
int256 remainingSwapCredit;
int timeEnteredSwapCredit; // zero means not in a swap credit
int lastSwapTime; // ignored when not in a swap credit
bool enabled;
}
uint256 public maxTokenId;
mapping (uint256 => address) public tokenOwners;
mapping (uint256 => TokenFlow) public tokenFlow;
// IERC1155Views
mapping (uint256 => uint256) private totalSupplyImpl;
mapping (uint256 => string) private nameImpl;
mapping (uint256 => string) private symbolImpl;
mapping (uint256 => string) private uriImpl;
function totalSupply(uint256 _id) external override view returns (uint256) {
return totalSupplyImpl[_id];
}
function name(uint256 _id) external override view returns (string memory) {
return nameImpl[_id];
}
function symbol(uint256 _id) external override view returns (string memory) {
return symbolImpl[_id];
}
function decimals(uint256) external override pure returns (uint8) {
return 18;
}
function uri(uint256 _id) external override view returns (string memory) {
return uriImpl[_id];
}
// Administrativia
function newToken(uint256 _parent, string calldata _name, string calldata _symbol, string calldata _uri)
external returns (uint256)
{
return _newToken(_parent, _name, _symbol, _uri, msg.sender);
}
function setTokenOwner(uint256 _id, address _newOwner) external {
require(msg.sender == tokenOwners[_id]);
require(_id != 0);
tokenOwners[_id] = _newOwner;
}
function removeTokenOwner(uint256 _id) external {
require(msg.sender == tokenOwners[_id]);
tokenOwners[_id] = address(0);
}
// Intentially no setTokenName() and setTokenSymbol()
function setTokenUri(uint256 _id, string calldata _uri) external {
require(msg.sender == tokenOwners[_id]);
uriImpl[_id] = _uri;
}
// We don't check for circularities.
function setTokenParent(uint256 _child, uint256 _parent) external {
// require(_child != 0 && _child <= maxTokenId); // not needed
require(msg.sender == tokenOwners[_child]);
_setTokenParentNoCheck(_child, _parent);
}
// Each element of `_childs` list must be a child of the next one.
// TODO: Test. Especially test the case if the last child has no parent. Also test if a child is zero.
function setEnabled(uint256 _ancestor, uint256[] calldata _childs, bool _enabled) external {
require(msg.sender == tokenOwners[_ancestor]);
require(tokenFlow[_ancestor].enabled);
uint256 _firstChild = _childs[0]; // asserts on `_childs.length == 0`.
bool _hasRight = false; // if msg.sender is an ancestor
// Note that if in the below loops we disable ourselves, then it will be detected by a require
uint i = 0;
uint256 _parent;
for (uint256 _id = _firstChild; _id != 0; _id = _parent) {
_parent = tokenFlow[_id].parentToken;
if (i < _childs.length - 1) {
require(_parent == _childs[i + 1]);
}
if (_id == _ancestor) {
_hasRight = true;
break;
}
// We are not msg.sender
tokenFlow[_id].enabled = _enabled; // cannot enable for msg.sender
++i;
}
require(_hasRight);
}
// User can set negative values. It is a nonsense but does not harm.
function setRecurringFlow(
uint256 _child,
int256 _maxSwapCredit,
int256 _remainingSwapCredit,
int _swapCreditPeriod, int _timeEnteredSwapCredit,
bytes32 oldLimitHash) external
{
TokenFlow storage _flow = tokenFlow[_child];
require(msg.sender == tokenOwners[_flow.parentToken]);
require(_flow.limit.hash == oldLimitHash);
// require(_remainingSwapCredit <= _maxSwapCredit); // It is caller's responsibility.
_flow.limit = _createSwapLimit(true, _remainingSwapCredit, _maxSwapCredit, _swapCreditPeriod, _timeEnteredSwapCredit);
_flow.timeEnteredSwapCredit = _timeEnteredSwapCredit;
_flow.remainingSwapCredit = _remainingSwapCredit;
}
// User can set negative values. It is a nonsense but does not harm.
function setNonRecurringFlow(uint256 _child, int256 _remainingSwapCredit, bytes32 oldLimitHash) external {
TokenFlow storage _flow = tokenFlow[_child];
require(msg.sender == tokenOwners[_flow.parentToken]);
// require(_remainingSwapCredit <= _maxSwapCredit); // It is caller's responsibility.
require(_flow.limit.hash == oldLimitHash);
_flow.limit = _createSwapLimit(false, _remainingSwapCredit, 0, 0, 0);
_flow.remainingSwapCredit = _remainingSwapCredit;
}
// ERC-1155
// A token can anyway change its parent at any moment, so disabling of payments makes no sense.
// function safeTransferFrom(
// address _from,
// address _to,
// uint256 _id,
// uint256 _value,
// bytes calldata _data) external virtual override
// {
// require(tokenFlow[_id].enabled);
// super._safeTransferFrom(_from, _to, _id, _value, _data);
// }
// function safeBatchTransferFrom(
// address _from,
// address _to,
// uint256[] calldata _ids,
// uint256[] calldata _values,
// bytes calldata _data) external virtual override
// {
// for (uint i = 0; i < _ids.length; ++i) {
// require(tokenFlow[_ids[i]].enabled);
// }
// super._safeBatchTransferFrom(_from, _to, _ids, _values, _data);
// }
// Misc
function burn(address _from, uint256 _id, uint256 _value) external {
require(_from == msg.sender || operatorApproval[msg.sender][_from], "No approval.");
// SafeMath will throw with insuficient funds _from
// or if _id is not valid (balance will be 0)
balances[_id][_from] = balances[_id][_from].sub(_value);
totalSupplyImpl[_id] -= _value; // no need to check overflow due to previous line
emit TransferSingle(msg.sender, _from, address(0), _id, _value);
}
// Flow
// Each next token ID must be a parent of the previous one.
function exchangeToAncestor(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
// Intentionally no check for `msg.sender`.
require(_ids[_ids.length - 1] != 0); // The rest elements are checked below.
require(_amount < 1<<128);
uint256 _balance = balances[_ids[0]][msg.sender];
require(_amount <= _balance);
for(uint i = 0; i != _ids.length - 1; ++i) {
uint256 _id = _ids[i];
require(_id != 0);
uint256 _parent = tokenFlow[_id].parentToken;
require(_parent == _ids[i + 1]); // i ranges 0 .. _ids.length - 2
TokenFlow storage _flow = tokenFlow[_id];
require(_flow.enabled);
int _currentTimeResult = _currentTime();
uint256 _maxAllowedFlow;
bool _inSwapCreditResult;
if (_flow.limit.recurring) {
_inSwapCreditResult = _inSwapCredit(_flow, _currentTimeResult);
_maxAllowedFlow = _maxRecurringSwapAmount(_flow, _currentTimeResult, _inSwapCreditResult);
} else {
_maxAllowedFlow = _flow.remainingSwapCredit < 0 ? 0 : uint256(_flow.remainingSwapCredit);
}
require(_amount <= _maxAllowedFlow);
if (_flow.limit.recurring && !_inSwapCreditResult) {
_flow.timeEnteredSwapCredit = _currentTimeResult;
_flow.remainingSwapCredit = _flow.limit.maxSwapCredit;
}
_flow.lastSwapTime = _currentTimeResult; // TODO: no strictly necessary if !_flow.recurring
// require(_amount < 1<<128); // done above
_flow.remainingSwapCredit -= int256(_amount);
}
// if (_id == _flow.parentToken) return; // not necessary
_doBurn(msg.sender, _ids[0], _amount);
_doMint(msg.sender, _ids[_ids.length - 1], _amount, _data);
}
// Each next token ID must be a parent of the previous one.
function exchangeToDescendant(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
uint256 _parent = _ids[0];
require(_parent != 0);
for(uint i = 1; i != _ids.length; ++i) {
_parent = tokenFlow[_parent].parentToken;
require(_parent != 0);
require(_parent == _ids[i]); // consequently `_ids[i] != 0`
}
_doBurn(msg.sender, _ids[_ids.length - 1], _amount);
_doMint(msg.sender, _ids[0], _amount, _data);
}
// Internal
function _newToken(
uint256 _parent,
string memory _name, string memory _symbol, string memory _uri,
address _owner) internal returns (uint256)
{
tokenOwners[++maxTokenId] = _owner;
nameImpl[maxTokenId] = _name;
symbolImpl[maxTokenId] = _symbol;
uriImpl[maxTokenId] = _uri;
_setTokenParentNoCheck(maxTokenId, _parent);
emit NewToken(maxTokenId, _owner, _name, _symbol, _uri);
return maxTokenId;
}
function _doMint(address _to, uint256 _id, uint256 _value, bytes memory _data) public {
require(_to != address(0), "_to must be non-zero.");
if (_value != 0) {
totalSupplyImpl[_id] = _value.add(totalSupplyImpl[_id]);
balances[_id][_to] += _value; // no need to check for overflow due to the previous line
}
// MUST emit event
emit TransferSingle(msg.sender, address(0), _to, _id, _value);
// Now that the balance is updated and the event was emitted,
// call onERC1155Received if the destination is a contract.
if (_to.isContract()) {
_doSafeTransferAcceptanceCheck(msg.sender, address(0), _to, _id, _value, _data);
}
}
function _doBurn(address _from, uint256 _id, uint256 _value) public {
// require(_from != address(0), "_from must be non-zero.");
balances[_id][_from] = balances[_id][_from].sub(_value);
totalSupplyImpl[_id] -= _value; // no need to check for overflow due to the previous line
// MUST emit event
emit TransferSingle(msg.sender, _from, address(0), _id, _value);
}
// Also resets swap credits and `enabled`, so use with caution.
// Allow this even if `!enabled` and set `enabled` to `true` if no parent,
// as otherwise impossible to enable it again.
function _setTokenParentNoCheck(uint256 _child, uint256 _parent) internal virtual {
require(_parent <= maxTokenId);
tokenFlow[_child] = TokenFlow({
parentToken: _parent,
limit: _createSwapLimit(false, 0, 0, 0, 0),
timeEnteredSwapCredit: 0, // zero means not in a swap credit
lastSwapTime: 0,
remainingSwapCredit: 0,
enabled: _parent == 0
});
}
function _currentTime() internal virtual view returns(int) {
return int(block.timestamp);
}
function _inSwapCredit(TokenFlow memory _flow, int _currentTimeResult) public pure returns(bool) {
// solhint-disable indent
return _flow.timeEnteredSwapCredit != 0 &&
_currentTimeResult - _flow.timeEnteredSwapCredit < _flow.limit.swapCreditPeriod;
}
function _maxRecurringSwapAmount(TokenFlow memory _flow, int _currentTimeResult, bool _inSwapCreditResult)
public pure returns(uint256)
{
int256 result;
if (_inSwapCreditResult) {
int256 passedTime = _currentTimeResult - _flow.lastSwapTime;
int256 delta = _flow.limit.maxSwapCredit * passedTime / _flow.limit.swapCreditPeriod;
result = _flow.remainingSwapCredit - delta;
} else {
result = _flow.limit.maxSwapCredit;
}
return result < 0 ? 0 : uint256(result);
}
function _createSwapLimit(
bool _recurring,
int256 _initialSwapCredit,
int256 _maxSwapCredit,
int _swapCreditPeriod,
int _firstTimeEnteredSwapCredit) pure internal returns (SwapLimit memory)
{
return SwapLimit({
recurring: _recurring,
initialSwapCredit: _initialSwapCredit,
maxSwapCredit: _maxSwapCredit,
swapCreditPeriod: _swapCreditPeriod,
firstTimeEnteredSwapCredit: _firstTimeEnteredSwapCredit,
hash: keccak256(abi.encodePacked(_recurring, _initialSwapCredit, _maxSwapCredit, _swapCreditPeriod, _firstTimeEnteredSwapCredit))
});
}
// Events
event NewToken(uint256 indexed id, address indexed owner, string name, string symbol, string uri);
}
|
Each next token ID must be a parent of the previous one.
|
function exchangeToDescendant(uint256[] calldata _ids, uint256 _amount, bytes calldata _data) external {
uint256 _parent = _ids[0];
require(_parent != 0);
for(uint i = 1; i != _ids.length; ++i) {
_parent = tokenFlow[_parent].parentToken;
require(_parent != 0);
}
_doBurn(msg.sender, _ids[_ids.length - 1], _amount);
_doMint(msg.sender, _ids[0], _amount, _data);
}
| 1,073,116 |
./partial_match/1/0xd2947e1E2eA5c4cD14AaA2b7492549129b087DAA/sources/CosmicDriftNFT.sol
|
Reveal the minted NFTs up till a specific tokenId This will allow us to expand our collection with future sales Callable only by Owner _revealed Whether the collection is revealed or not _revealedTill Up till which tokenId is the collection revealed
|
function setRevealed(bool _revealed, uint256 _revealedTill)
external
onlyOwner
{
revealed = _revealed;
revealedTill = _revealedTill;
emit RevealedSet(_revealed, _revealedTill);
}
| 16,149,373 |
// File: @openzeppelin/contracts/utils/cryptography/MerkleProof.sol
// OpenZeppelin Contracts (last updated v4.6.0) (utils/cryptography/MerkleProof.sol)
pragma solidity ^0.8.0;
/**
* @dev These functions deal with verification of Merkle Trees proofs.
*
* The proofs can be generated using the JavaScript library
* https://github.com/miguelmota/merkletreejs[merkletreejs].
* Note: the hashing algorithm should be keccak256 and pair sorting should be enabled.
*
* See `test/utils/cryptography/MerkleProof.test.js` for some examples.
*
* WARNING: You should avoid using leaf values that are 64 bytes long prior to
* hashing, or use a hash function other than keccak256 for hashing leaves.
* This is because the concatenation of a sorted pair of internal nodes in
* the merkle tree could be reinterpreted as a leaf value.
*/
library MerkleProof {
/**
* @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree
* defined by `root`. For this, a `proof` must be provided, containing
* sibling hashes on the branch from the leaf to the root of the tree. Each
* pair of leaves and each pair of pre-images are assumed to be sorted.
*/
function verify(
bytes32[] memory proof,
bytes32 root,
bytes32 leaf
) internal pure returns (bool) {
return processProof(proof, leaf) == root;
}
/**
* @dev Returns the rebuilt hash obtained by traversing a Merkle tree up
* from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt
* hash matches the root of the tree. When processing the proof, the pairs
* of leafs & pre-images are assumed to be sorted.
*
* _Available since v4.4._
*/
function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) {
bytes32 computedHash = leaf;
for (uint256 i = 0; i < proof.length; i++) {
bytes32 proofElement = proof[i];
if (computedHash <= proofElement) {
// Hash(current computed hash + current element of the proof)
computedHash = _efficientHash(computedHash, proofElement);
} else {
// Hash(current element of the proof + current computed hash)
computedHash = _efficientHash(proofElement, computedHash);
}
}
return computedHash;
}
function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) {
assembly {
mstore(0x00, a)
mstore(0x20, b)
value := keccak256(0x00, 0x40)
}
}
}
// File: @openzeppelin/contracts/utils/Strings.sol
// OpenZeppelin Contracts v4.4.1 (utils/Strings.sol)
pragma solidity ^0.8.0;
/**
* @dev String operations.
*/
library Strings {
bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef";
/**
* @dev Converts a `uint256` to its ASCII `string` decimal representation.
*/
function toString(uint256 value) internal pure returns (string memory) {
// Inspired by OraclizeAPI's implementation - MIT licence
// https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol
if (value == 0) {
return "0";
}
uint256 temp = value;
uint256 digits;
while (temp != 0) {
digits++;
temp /= 10;
}
bytes memory buffer = new bytes(digits);
while (value != 0) {
digits -= 1;
buffer[digits] = bytes1(uint8(48 + uint256(value % 10)));
value /= 10;
}
return string(buffer);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation.
*/
function toHexString(uint256 value) internal pure returns (string memory) {
if (value == 0) {
return "0x00";
}
uint256 temp = value;
uint256 length = 0;
while (temp != 0) {
length++;
temp >>= 8;
}
return toHexString(value, length);
}
/**
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length.
*/
function toHexString(uint256 value, uint256 length) internal pure returns (string memory) {
bytes memory buffer = new bytes(2 * length + 2);
buffer[0] = "0";
buffer[1] = "x";
for (uint256 i = 2 * length + 1; i > 1; --i) {
buffer[i] = _HEX_SYMBOLS[value & 0xf];
value >>= 4;
}
require(value == 0, "Strings: hex length insufficient");
return string(buffer);
}
}
// File: @openzeppelin/contracts/utils/Context.sol
// OpenZeppelin Contracts v4.4.1 (utils/Context.sol)
pragma solidity ^0.8.0;
/**
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes calldata) {
return msg.data;
}
}
// File: @openzeppelin/contracts/access/Ownable.sol
// OpenZeppelin Contracts v4.4.1 (access/Ownable.sol)
pragma solidity ^0.8.0;
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
abstract contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor() {
_transferOwnership(_msgSender());
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view virtual returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(owner() == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public virtual onlyOwner {
_transferOwnership(address(0));
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public virtual onlyOwner {
require(newOwner != address(0), "Ownable: new owner is the zero address");
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Internal function without access restriction.
*/
function _transferOwnership(address newOwner) internal virtual {
address oldOwner = _owner;
_owner = newOwner;
emit OwnershipTransferred(oldOwner, newOwner);
}
}
// File: @openzeppelin/contracts/utils/Address.sol
// OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol)
pragma solidity ^0.8.1;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*
* [IMPORTANT]
* ====
* You shouldn't rely on `isContract` to protect against flash loan attacks!
*
* Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets
* like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract
* constructor.
* ====
*/
function isContract(address account) internal view returns (bool) {
// This method relies on extcodesize/address.code.length, which returns 0
// for contracts in construction, since the code is only stored at the end
// of the constructor execution.
return account.code.length > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
(bool success, ) = recipient.call{value: amount}("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain `call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
return functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value
) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(
address target,
bytes memory data,
uint256 value,
string memory errorMessage
) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
require(isContract(target), "Address: call to non-contract");
(bool success, bytes memory returndata) = target.call{value: value}(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) {
return functionStaticCall(target, data, "Address: low-level static call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a static call.
*
* _Available since v3.3._
*/
function functionStaticCall(
address target,
bytes memory data,
string memory errorMessage
) internal view returns (bytes memory) {
require(isContract(target), "Address: static call to non-contract");
(bool success, bytes memory returndata) = target.staticcall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) {
return functionDelegateCall(target, data, "Address: low-level delegate call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`],
* but performing a delegate call.
*
* _Available since v3.4._
*/
function functionDelegateCall(
address target,
bytes memory data,
string memory errorMessage
) internal returns (bytes memory) {
require(isContract(target), "Address: delegate call to non-contract");
(bool success, bytes memory returndata) = target.delegatecall(data);
return verifyCallResult(success, returndata, errorMessage);
}
/**
* @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the
* revert reason using the provided one.
*
* _Available since v4.3._
*/
function verifyCallResult(
bool success,
bytes memory returndata,
string memory errorMessage
) internal pure returns (bytes memory) {
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol
// OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721Receiver.sol)
pragma solidity ^0.8.0;
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
interface 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 `IERC721Receiver.onERC721Received.selector`.
*/
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
}
// File: @openzeppelin/contracts/utils/introspection/IERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Interface of the ERC165 standard, as defined in the
* https://eips.ethereum.org/EIPS/eip-165[EIP].
*
* Implementers can declare support of contract interfaces, which can then be
* queried by others ({ERC165Checker}).
*
* For an implementation, see {ERC165}.
*/
interface IERC165 {
/**
* @dev Returns true if this contract implements the interface defined by
* `interfaceId`. See the corresponding
* https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section]
* to learn more about how these ids are created.
*
* This function call must use less than 30 000 gas.
*/
function supportsInterface(bytes4 interfaceId) external view returns (bool);
}
// File: @openzeppelin/contracts/utils/introspection/ERC165.sol
// OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol)
pragma solidity ^0.8.0;
/**
* @dev Implementation of the {IERC165} interface.
*
* Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check
* for the additional interface id that will be supported. For example:
*
* ```solidity
* function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
* return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId);
* }
* ```
*
* Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation.
*/
abstract contract ERC165 is IERC165 {
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) {
return interfaceId == type(IERC165).interfaceId;
}
}
// File: @openzeppelin/contracts/token/ERC721/IERC721.sol
// OpenZeppelin Contracts (last updated v4.6.0) (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`.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes calldata data
) external;
/**
* @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients
* are aware of the ERC721 protocol to prevent tokens from being forever locked.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must exist and be owned by `from`.
* - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}.
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer.
*
* Emits a {Transfer} event.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Transfers `tokenId` token from `from` to `to`.
*
* WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible.
*
* Requirements:
*
* - `from` cannot be the zero address.
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
* - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}.
*
* Emits a {Transfer} event.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) external;
/**
* @dev Gives permission to `to` to transfer `tokenId` token to another account.
* The approval is cleared when the token is transferred.
*
* Only a single account can be approved at a time, so approving the zero address clears previous approvals.
*
* Requirements:
*
* - The caller must own the token or be an approved operator.
* - `tokenId` must exist.
*
* Emits an {Approval} event.
*/
function approve(address to, uint256 tokenId) external;
/**
* @dev Approve or remove `operator` as an operator for the caller.
* Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller.
*
* Requirements:
*
* - The `operator` cannot be the caller.
*
* Emits an {ApprovalForAll} event.
*/
function setApprovalForAll(address operator, bool _approved) external;
/**
* @dev Returns the account approved for `tokenId` token.
*
* Requirements:
*
* - `tokenId` must exist.
*/
function getApproved(uint256 tokenId) external view returns (address operator);
/**
* @dev Returns if the `operator` is allowed to manage all of the assets of `owner`.
*
* See {setApprovalForAll}
*/
function isApprovedForAll(address owner, address operator) external view returns (bool);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol
// OpenZeppelin Contracts (last updated v4.5.0) (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);
/**
* @dev Returns a token ID at a given `index` of all the tokens stored by the contract.
* Use along with {totalSupply} to enumerate all tokens.
*/
function tokenByIndex(uint256 index) external view returns (uint256);
}
// File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol
// OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol)
pragma solidity ^0.8.0;
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://eips.ethereum.org/EIPS/eip-721
*/
interface IERC721Metadata is IERC721 {
/**
* @dev Returns the token collection name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the token collection symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token.
*/
function tokenURI(uint256 tokenId) external view returns (string memory);
}
// File: contracts/ERC721A.sol
// Creator: Chiru Labs
pragma solidity ^0.8.0;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Does not support burning tokens to address(0).
*
* Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply
*/
contract ERC721A is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable {
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 internal currentIndex;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) internal _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
constructor(string memory name_, string memory symbol_) {
_name = name_;
_symbol = symbol_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index) public view override returns (uint256) {
require(index < totalSupply(), 'ERC721A: global index out of bounds');
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(totalSupply). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index) public view override returns (uint256) {
require(index < balanceOf(owner), 'ERC721A: owner index out of bounds');
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx;
address currOwnershipAddr;
// Counter overflow is impossible as the loop breaks when uint256 i is equal to another uint256 numMintedSoFar.
unchecked {
for (uint256 i; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
}
revert('ERC721A: unable to get token of owner by index');
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) {
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(owner != address(0), 'ERC721A: balance query for the zero address');
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(owner != address(0), 'ERC721A: number minted query for the zero address');
return uint256(_addressData[owner].numberMinted);
}
/**
* Gas spent here starts off proportional to the maximum mint batch size.
* It gradually moves to O(1) as tokens get transferred around in the collection over time.
*/
function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) {
require(_exists(tokenId), 'ERC721A: owner query for nonexistent token');
unchecked {
for (uint256 curr = tokenId; curr >= 0; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
}
revert('ERC721A: unable to determine the owner of token');
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId) public view virtual override returns (string memory) {
require(_exists(tokenId), 'ERC721Metadata: URI query for nonexistent token');
string memory baseURI = _baseURI();
return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : '';
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return '';
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, 'ERC721A: approval to current owner');
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
'ERC721A: approve caller is not owner nor approved for all'
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId) public view override returns (address) {
require(_exists(tokenId), 'ERC721A: approved query for nonexistent token');
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved) public override {
require(operator != _msgSender(), 'ERC721A: approve to caller');
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) {
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, '');
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
'ERC721A: transfer to non ERC721Receiver implementer'
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, '');
}
/**
* @dev Safely mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
_mint(to, quantity, _data, true);
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `quantity` must be greater than 0.
*
* Emits a {Transfer} event.
*/
function _mint(
address to,
uint256 quantity,
bytes memory _data,
bool safe
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), 'ERC721A: mint to the zero address');
require(quantity != 0, 'ERC721A: quantity must be greater than 0');
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
// Overflows are incredibly unrealistic.
// balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1
// updatedIndex overflows if currentIndex + quantity > 1.56e77 (2**256) - 1
unchecked {
_addressData[to].balance += uint128(quantity);
_addressData[to].numberMinted += uint128(quantity);
_ownerships[startTokenId].addr = to;
_ownerships[startTokenId].startTimestamp = uint64(block.timestamp);
uint256 updatedIndex = startTokenId;
for (uint256 i; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
if (safe) {
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
'ERC721A: transfer to non ERC721Receiver implementer'
);
}
updatedIndex++;
}
currentIndex = updatedIndex;
}
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(isApprovedOrOwner, 'ERC721A: transfer caller is not owner nor approved');
require(prevOwnership.addr == from, 'ERC721A: transfer from incorrect owner');
require(to != address(0), 'ERC721A: transfer to the zero address');
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
// Underflow of the sender's balance is impossible because we check for
// ownership above and the recipient's balance can't realistically overflow.
// Counter overflow is incredibly unrealistic as tokenId would have to be 2**256.
unchecked {
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId].addr = to;
_ownerships[tokenId].startTimestamp = uint64(block.timestamp);
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId].addr = prevOwnership.addr;
_ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp;
}
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert('ERC721A: transfer to non ERC721Receiver implementer');
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File: contracts/AstroMallows.sol
pragma solidity ^0.8.4;
contract AstroMallows is ERC721A, Ownable {
using Strings for uint256;
//----- VARIABLES -----
uint256 public constant MAX_SUPPLY = 4444;
uint256 public constant MAX_PER_WL = 2;
uint256 public constant MAX_PER_TX = 3;
uint256 public constant PRICE_WL = 0.06 ether;
uint256 public constant PRICE_PUBLIC = 0.09 ether;
bool public isPublicSaleActive = false;
string private _baseTokenURI;
uint256 private _reservedSupply = 200;
mapping(address => uint256) private _whitelistClaimed;
bytes32 private _merkleRoot;
address private constant _a1 = 0xA302249fE90E51F259C391763FBc6D2B44256df6;
address private constant _a2 = 0xCC765e1409B5E6648B58fAD73754D62C5D84dcF6;
//----- MODIFIERS -----
modifier onlyEOA() {
require(tx.origin == msg.sender, "No mass minting contracts.");
_;
}
//----- CONSTRUCTOR -----
constructor() ERC721A("AstroMallows", "AstroMallows") {}
//----- MINT FUNCTIONS -----
function mintWhitelist(bytes32[] calldata _merkleProof, uint256 quantity) external payable onlyEOA {
bytes32 leaf = keccak256(abi.encodePacked(msg.sender));
require(MerkleProof.verify(_merkleProof, _merkleRoot, leaf), "Wallet is not eligible for whitelist");
require(quantity > 0, "Quantity cannot be zero");
require(quantity <= MAX_PER_WL, "Quantity exceeds max quantity per transaction");
require(totalSupply() + quantity <= MAX_SUPPLY, "Quantity exceeds maximum supply");
require(_whitelistClaimed[msg.sender] + quantity <= MAX_PER_WL, "Quantity exceeds max quantity per wallet");
require(PRICE_WL * quantity == msg.value, "Invalid ETH amount provided");
_whitelistClaimed[msg.sender] += quantity;
_safeMint(msg.sender, quantity);
}
function mintPublic(uint256 quantity) external payable onlyEOA {
require(isPublicSaleActive, "Public sale is not active");
require(quantity > 0, "Quantity cannot be zero");
require(quantity <= MAX_PER_TX, "Quantity exceeds max quantity per transaction");
require(totalSupply() + quantity <= MAX_SUPPLY, "Quantity exceeds maximum public supply");
require(PRICE_PUBLIC * quantity == msg.value, "Invalid ETH amount provided");
_safeMint(msg.sender, quantity);
}
function mintReserved(uint256 quantity) external onlyOwner {
require(quantity <= _reservedSupply);
require(totalSupply() + quantity <= MAX_SUPPLY, "Quantity exceeds maximum supply");
_reservedSupply -= quantity;
_safeMint(msg.sender, quantity);
}
//----- TOKEN URI FUNCTIONS-----
function setBaseTokenURI(string calldata URI) external onlyOwner {
_baseTokenURI = URI; }
function _baseURI() internal view override returns (string memory) {
return _baseTokenURI;
}
function baseTokenURI() public view returns (string memory) {
return _baseTokenURI;
}
function tokenURI(uint256 tokenId) public view override returns (string memory) {
return super.tokenURI(tokenId);
}
//----- OTHER FUNCTIONS -----
function isWhitelistSaleActive() external view returns (bool) {
return (_merkleRoot != "");
}
function togglePublic() external onlyOwner {
isPublicSaleActive = !isPublicSaleActive;
}
function countClaimedWhitelist(address addr) external view returns (uint256) {
require(addr != address(0), "Null Address");
return _whitelistClaimed[addr];
}
function setMerkleRoot(bytes32 rootHash) external onlyOwner {
_merkleRoot = rootHash;
}
//----- WITHDRAW -----
function withdraw() external onlyOwner {
uint _a1amount = address(this).balance * 90/100;
uint _a2amount = address(this).balance * 10/100;
require(payable(_a1).send(_a1amount), "Failed to send to a1");
require(payable(_a2).send(_a2amount), "Failed to send to a2");
}
}
|
----- WITHDRAW -----
|
function withdraw() external onlyOwner {
uint _a1amount = address(this).balance * 90/100;
uint _a2amount = address(this).balance * 10/100;
require(payable(_a1).send(_a1amount), "Failed to send to a1");
require(payable(_a2).send(_a2amount), "Failed to send to a2");
}
| 10,438,005 |
pragma solidity ^0.4.8;
import './CapChatRegistry.sol';
import './Logic.sol';
/// @title CapChatUser
/// @author thekelvinliu <[email protected]>
contract CapChatUser {
// variables
/// address of the deployed registry contract
address constant registry = 0x84f1ac740f64a034b0609f29d103d4aeb286cbf1;
/// owner of this user contract
address owner;
/// the username associated with this contract
bytes32 username;
/// the registration id associated with this contract
uint16 registrationID;
/// the long-term public identity key associated with this contract
bytes32 public identityKey;
/// the medium-term public signed public prekey associated with this contract
bytes32 public signedPreKey;
/// the signature of the signed public prekey associated with this contract
bytes32[2] signedPreKeySig;
/// the array of one-time prekeys associated with this contract
bytes32[] oneTimePreKeys;
/// the index of the next one-time prekey to issue
uint otpkIndex;
/// the mapping of friendly user contracts associated with this contract
mapping (address => bool) friends;
// constructor
/// initializes a user contract
/// @param _username the username for this contract
/// @param _registrationID the registration id for this contract
/// @param _identityKey the long-term public identity key for this contract
/// @param _signedPreKey the medium-term signed public prekey for this contract
/// @param _signedPreKeySig the signature of the public prekey (signed with the identity key)
/// @param _oneTimePreKeys an array of one-time prekeys
function CapChatUser(
bytes32 _username,
uint16 _registrationID,
bytes32 _identityKey,
bytes32 _signedPreKey,
bytes32[2] _signedPreKeySig,
bytes32[] _oneTimePreKeys
) {
owner = msg.sender;
username = _username;
registrationID = _registrationID;
identityKey = _identityKey;
signedPreKey = _signedPreKey;
signedPreKeySig = _signedPreKeySig;
oneTimePreKeys = _oneTimePreKeys;
}
// events
// event RegistrationFailed();
// event RegistrationPassed();
event FriendAdded(address friend);
event FriendRemoved(address friend);
event OneTimePreKey(bytes32 otpk);
event OneTimePreKeysDepleted();
event OneTimePreKeysLow(uint count);
event OneTimePreKeysUpdated(uint count);
event SignedPreKeyUpdated();
event Unauthorized(address from, string action);
// functions
/// returns this contract's the signed public prekey signature
/// @return { "sig": "the signed public prekey signature" }
function getSignedPreKeySig() constant returns (bytes32[2] sig) {
return signedPreKeySig;
}
/// updates this contract's medium-term signed public prekey
/// @param _signedPreKey the new medium-term signed public prekey
/// @param _signedPreKeySig the signature of the new public prekey (signed with the identity key)
function updateSignedPreKey(
bytes32 _signedPreKey,
bytes32[2] _signedPreKeySig
) {
// only let this contract's owner add keys
if (msg.sender != owner) {
Unauthorized(msg.sender, 'updateSignedPreKey');
return;
}
signedPreKey = _signedPreKey;
signedPreKeySig = _signedPreKeySig;
SignedPreKeyUpdated();
}
/// adds the given user contract address to this contract's `friends` mapping
/// @param caddr the user contract address of the friend to be added
function addFriend(address caddr) {
// only let this contract's owner add friends
if (msg.sender != owner) {
Unauthorized(msg.sender, 'addFriend');
return;
}
friends[caddr] = true;
FriendAdded(caddr);
}
/// removes the given user contract address to this contract's `friends` mapping
/// @param caddr the user contract address of the friend to be removed
function removeFriend(address caddr) {
// only let this contract's owner remove friends
if (msg.sender != owner) {
Unauthorized(msg.sender, 'removeFriend');
return;
}
delete friends[caddr];
FriendRemoved(caddr);
}
/// issues a single one-time prekey from this contract's `oneTimePreKeys` array
function getOneTimePreKey() {
// only let this contract's friends to get a key
if (!friends[msg.sender]) {
Unauthorized(msg.sender, 'getOneTimePreKey');
return;
}
// no more keys
if (otpkIndex >= oneTimePreKeys.length) {
OneTimePreKeysDepleted();
return;
}
// issue the key
OneTimePreKey(oneTimePreKeys[otpkIndex++]);
// check if more keys are needed
uint remaining = oneTimePreKeys.length - otpkIndex;
if (remaining < 3)
OneTimePreKeysLow(remaining);
}
/// adds an array of new one-time prekeys to this contract's `oneTimePreKeys` array
/// @param _oneTimePreKeys the array of new one-time prekeys
function addOneTimePreKeys(bytes32[] _oneTimePreKeys) {
// only let this contract's owner add keys
if (msg.sender != owner) {
Unauthorized(msg.sender, 'addOneTimePreKeys');
return;
}
// move remaining keys to the front of oneTimePreKeys
if (otpkIndex != 0) {
uint newLength = 0;
for (otpkIndex; otpkIndex < oneTimePreKeys.length; otpkIndex++)
oneTimePreKeys[newLength++] = oneTimePreKeys[otpkIndex];
oneTimePreKeys.length = newLength;
}
// push new keys
for (uint i = 0; i < _oneTimePreKeys.length; i++)
oneTimePreKeys.push(_oneTimePreKeys[i]);
// reset index to 0
otpkIndex = 0;
// emit event
OneTimePreKeysUpdated(oneTimePreKeys.length);
}
/// checks the validity of this contract
/// @dev a contract is valid when the fields set in the contractor are no longer the initial values (i.e. `0x0`).
/// @dev additionally, `oneTimePreKeys` must contain at least three keys.
/// @return { "valid": "whether or not this contract is valid" }
function isValid() constant returns (bool valid) {
// set most checks
valid =
// owner cannot be zero address
owner != address(0x0)
// username cannot be empty string
&& username != bytes32('')
// registrationID cannot be zero
&& registrationID != 0
// public keys and signature cannot be zero
&& identityKey != bytes32(0)
&& signedPreKey != bytes32(0)
&& signedPreKeySig[0] != bytes32(0)
&& signedPreKeySig[1] != bytes32(0)
// oneTimePreKeys must have at least 3 keys
&& oneTimePreKeys.length > 2;
// ensure none of the keys in oneTimePreKeys is zero
for (uint i = 0; i < oneTimePreKeys.length; i++)
valid = valid && oneTimePreKeys[i] != bytes32(0);
}
/// registers this user contract with the registry
/// @return { "status": "whether or not this contract was registered" }
function register() returns (bool status) {
// only let this contract's owner register
if (msg.sender != owner) {
Unauthorized(msg.sender, 'register');
return false;
}
// only let valid contracts be registered
if (!isValid()) return false;
// get the address of the current logic contract
address logic = CapChatRegistry(registry).logicContract();
// register via the current logic contract
return Logic(logic).registerUser(username, this);
}
/// finds the the associated user contract address for the given username
/// @param username the username
/// @return { "caddr": "the associated user contract address" }
function find(bytes32 username) constant returns (address caddr) {
// only let this contract's owner find
if (msg.sender != owner) {
Unauthorized(msg.sender, 'find');
return;
}
// get the address of the current logic contract
address logic = CapChatRegistry(registry).logicContract();
// get user contract address via the current logic contract
return Logic(logic).getUser(username);
}
/// deregisters this user contract with the registry
/// @return { "status": "whether or not this contract was registered" }
function deregister() returns (bool status) {
// only let this contract's owner deregister
if (msg.sender != owner) {
Unauthorized(msg.sender, 'deregister');
return false;
}
// get the address of the current logic contract
address logic = CapChatRegistry(registry).logicContract();
// deregister via the current logic contract
return Logic(logic).deregisterUser(username);
}
}
|
adds an array of new one-time prekeys to this contract's `oneTimePreKeys` array _oneTimePreKeys the array of new one-time prekeys only let this contract's owner add keys move remaining keys to the front of oneTimePreKeys
|
function addOneTimePreKeys(bytes32[] _oneTimePreKeys) {
if (msg.sender != owner) {
Unauthorized(msg.sender, 'addOneTimePreKeys');
return;
}
if (otpkIndex != 0) {
uint newLength = 0;
for (otpkIndex; otpkIndex < oneTimePreKeys.length; otpkIndex++)
oneTimePreKeys[newLength++] = oneTimePreKeys[otpkIndex];
oneTimePreKeys.length = newLength;
}
oneTimePreKeys.push(_oneTimePreKeys[i]);
}
| 13,084,112 |
// SPDX-License-Identifier: MIT
pragma solidity >=0.8.0 <0.9.0;
import "./nft.sol";
contract Auction {
// 导入nft的集合
nft private nftset;
// 单项拍卖的信息
struct AuctionItem {
// 该项拍卖的uid
uint256 id;
// 拍卖基本信息
address payable beneficiary; //受益人,即拍卖发起者
uint256 tokenId; //所拍卖的 NFT id
uint auctionEnd; // 拍卖截止时间
uint startPrice; // 起拍价
// 拍卖的当前状态
address highestBidder; //当前最高出价者
uint highestBid; //当前最高出价值
bool ended; // 拍卖结束后设为 true,将禁止所有的变更
bool haveBid; // 判断是否有人进行出价,有人出价后设为 true,允许转账授权等操作
bidhistory[] bidhis;
}
//拍卖的历史记录(由触发事件HighestBidIncreased进行记录)
struct bidhistory {
address bidder; //所有历史竞拍者数组
uint bid; //所有历史竞拍者的出价
}
//可以取回的之前的出价
mapping(address => uint) public pendingReturns;
AuctionItem[] public aucItem;
mapping(uint256 => bool) public activeItems;
// 变更触发的事件
event AuctionAdded(uint256 id, uint256 tokenId, uint auctionEnd, uint startPrice);
event HighestBidIncreased(uint256 id, address bidder, uint amount);
event AuctionEnded(uint256 id, address winner, uint amount);
constructor(nft _nftset) {
nftset = _nftset;
}
modifier OnlyOwner(uint256 tokenId) {
require(nftset.ownerOf(tokenId) == msg.sender, "Sender does not own the item");
_;
}
modifier HasTransferApproval(uint256 tokenId) {
require(nftset.getApproved(tokenId) == address(this), "Auction is not approved");
_;
}
//modifier HasTransferApproval(uint256 tokenId) {
// require(nftset.getApproved(tokenId) == msg.sender, "Auction is not approved");
// _;
//}
modifier ItemExists(uint256 id) {
require(id < aucItem.length && aucItem[id].id == id, "Could not find item");
_;
}
modifier IsActive(uint256 id) {
require(block.timestamp <= aucItem[id].auctionEnd, "Auction time is over.");
_;
}
modifier IsnotActive(uint256 id) {
require(block.timestamp > aucItem[id].auctionEnd, "Auction hasn't finished yet.");
_;
}
modifier IsNotEnded(uint256 id) {
require(!aucItem[id].ended, "Action is over");
_;
}
modifier AbleFetch(uint256 id) {
require(!aucItem[id].haveBid, "You cannot fetch the nft.");
_;
}
modifier AbleClaim(uint256 id) {
require(
aucItem[id].haveBid && aucItem[id].highestBidder == msg.sender,
"You cannot claim the nft."
);
_;
}
/// 为 id 为 `_tokenId` 的 NFT 创建一个拍卖,
/// 拍卖时间为 `_biddingTime` 秒,
/// 起拍价为 `_startPrice`
function AuctionAdd(uint256 _tokenId, uint _biddingTime, uint _startPrice)
OnlyOwner(_tokenId)
///HasTransferApproval(tokenId)
external
returns (uint256) {
require(!activeItems[_tokenId], "This nft is already put up for auctioned");
uint256 newId = aucItem.length;
aucItem.push();
aucItem[newId].id = newId;
aucItem[newId].beneficiary = payable(msg.sender);
aucItem[newId].tokenId = _tokenId;
aucItem[newId].auctionEnd = block.timestamp + _biddingTime;
aucItem[newId].startPrice = _startPrice;
aucItem[newId].highestBidder = msg.sender;
aucItem[newId].highestBid = 0;
aucItem[newId].ended = false;
aucItem[newId].haveBid = false;
activeItems[_tokenId] = true;
assert(aucItem[newId].id == newId);
emit AuctionAdded(newId, _tokenId, block.timestamp + _biddingTime, _startPrice);
return newId;
}
/// 对拍卖进行出价,具体的出价随交易一起发送。
/// 如果没有在拍卖中胜出,则返还出价。
function bid(uint256 id)
ItemExists(id)
IsNotEnded(id)
IsActive(id)
///HasTransferApproval(aucItem[id].tokenId)
payable
external {
// 如果出价低于起拍价,返还你的钱
require(
msg.value >= aucItem[id].startPrice,
"Your bid is below the starting price."
);
// 如果出价不够高,返还你的钱
require(
msg.value > aucItem[id].highestBid,
"There already is a higher bid."
);
// 拍卖发起者不能自己参与拍卖
require(
msg.sender != aucItem[id].beneficiary,
"You cannot bid in the auction you initiate."
);
if (aucItem[id].highestBid != 0) {
// 返还出价时,简单地直接调用 highestBidder.send(highestBid) 函数,
// 是有安全风险的,因为它有可能执行一个非信任合约。
// 更为安全的做法是让接收方自己提取金钱。
pendingReturns[aucItem[id].highestBidder] += aucItem[id].highestBid;
}
aucItem[id].highestBidder = msg.sender;
aucItem[id].highestBid = msg.value;
if (!aucItem[id].haveBid)
aucItem[id].haveBid = true;
aucItem[id].bidhis.push();
uint len = aucItem[id].bidhis.length;
aucItem[id].bidhis[len - 1].bidder = msg.sender;
aucItem[id].bidhis[len - 1].bid = msg.value;
//aucItem[id].beneficiary.transfer(msg.value);
emit HighestBidIncreased(id, msg.sender, msg.value);
}
/// 取回出价(当该出价已被超越)
function withdraw()
external
returns (bool) {
require(
pendingReturns[msg.sender] > 0,
"You have no money to withdraw."
);
uint amount = pendingReturns[msg.sender];
bool isReturned;
pendingReturns[msg.sender] = 0;
isReturned = (payable(msg.sender)).send(amount);
if (!isReturned) {
// 这里不需抛出异常,只需重置未付款
pendingReturns[msg.sender] = amount;
return false;
}
return true;
}
function fetch(uint256 id)
ItemExists(id)
IsnotActive(id)
AbleFetch(id)
HasTransferApproval(aucItem[id].tokenId)
external {
aucItem[id].ended = true;
activeItems[aucItem[id].tokenId] = false;
}
function claim(uint256 id)
ItemExists(id)
IsnotActive(id)
AbleClaim(id)
HasTransferApproval(aucItem[id].tokenId)
external {
aucItem[id].ended = true;
activeItems[aucItem[id].tokenId] = false;
nftset.safeTransferFrom(aucItem[id].beneficiary, msg.sender, aucItem[id].tokenId);
nftset.ownerchange(aucItem[id].tokenId, msg.sender);
aucItem[id].beneficiary.transfer(aucItem[id].highestBid);
emit AuctionEnded(id, aucItem[id].highestBidder, aucItem[id].highestBid);
}
function totalForAuction() external view returns(uint256) {
return aucItem.length;
}
function getallauction() external returns(AuctionItem[] memory) {
return aucItem;
}
}
|
对拍卖进行出价,具体的出价随交易一起发送。 如果没有在拍卖中胜出,则返还出价。HasTransferApproval(aucItem[id].tokenId) 如果出价低于起拍价,返还你的钱 如果出价不够高,返还你的钱 拍卖发起者不能自己参与拍卖 返还出价时,简单地直接调用 highestBidder.send(highestBid) 函数, 是有安全风险的,因为它有可能执行一个非信任合约。 更为安全的做法是让接收方自己提取金钱。
|
function bid(uint256 id)
ItemExists(id)
IsNotEnded(id)
IsActive(id)
payable
external {
require(
msg.value >= aucItem[id].startPrice,
"Your bid is below the starting price."
);
require(
msg.value > aucItem[id].highestBid,
"There already is a higher bid."
);
require(
msg.sender != aucItem[id].beneficiary,
"You cannot bid in the auction you initiate."
);
if (aucItem[id].highestBid != 0) {
pendingReturns[aucItem[id].highestBidder] += aucItem[id].highestBid;
}
aucItem[id].highestBidder = msg.sender;
aucItem[id].highestBid = msg.value;
if (!aucItem[id].haveBid)
aucItem[id].haveBid = true;
aucItem[id].bidhis.push();
uint len = aucItem[id].bidhis.length;
aucItem[id].bidhis[len - 1].bidder = msg.sender;
aucItem[id].bidhis[len - 1].bid = msg.value;
emit HighestBidIncreased(id, msg.sender, msg.value);
}
| 7,317,631 |
./partial_match/288/0x5d4394E9146dEDa6a1908aE901387A83A8eF21d9/sources/contracts/LP/L2LiquidityPool.sol
|
Client deposit ERC20 from their account to this contract, which then releases funds on the L1 side _amount amount that client wants to transfer. _tokenAddress L2 token address/ check whether user sends ovm_ETH or ERC20 override the _amount and token address transfer funds if users deposit ERC20
|
function clientDepositL2(
uint256 _amount,
address _tokenAddress
)
external
payable
whenNotPaused
{
uint256 startingGas = gasleft();
require(startingGas > extraGasRelay, "Insufficient Gas For a Relay Transaction");
uint256 desiredGasLeft = startingGas.sub(extraGasRelay);
uint256 i;
while (gasleft() > desiredGasLeft) {
i++;
}
require(msg.value != 0 || _tokenAddress != Lib_PredeployAddresses.OVM_ETH, "Amount Incorrect");
if (msg.value != 0) {
_amount = msg.value;
_tokenAddress = Lib_PredeployAddresses.OVM_ETH;
}
PoolInfo storage pool = poolInfo[_tokenAddress];
require(pool.l2TokenAddress != address(0), "Token Address Not Registered");
if (_tokenAddress != Lib_PredeployAddresses.OVM_ETH) {
IERC20(_tokenAddress).safeTransferFrom(msg.sender, address(this), _amount);
}
iL1LiquidityPool.clientPayL1.selector,
msg.sender,
_amount,
pool.l1TokenAddress
);
address(L1LiquidityPoolAddress),
getFinalizeDepositL1Gas(),
data
);
emit ClientDepositL2(
msg.sender,
_amount,
_tokenAddress
);
}
| 16,906,360 |
pragma solidity ^0.5.11;
// Vision.Network 100G Token v2.0
//
// Upgraded in Aug 2019
//
// More info:
// https://vision.network
// https://voken.io
//
// Contact us:
// [email protected]
// [email protected]
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks.
*/
library SafeMath256 {
/**
* @dev Returns the addition of two unsigned integers, reverting on 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).
*/
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).
*/
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.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*/
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.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
return a / b;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by 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.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @dev Library for managing addresses assigned to a Role.
*/
library Roles {
struct Role {
mapping (address => bool) bearer;
}
/**
* @dev Give an account access to this role.
*/
function add(Role storage role, address account) internal {
require(!has(role, account), "Roles: account already has role");
role.bearer[account] = true;
}
/**
* @dev Remove an account's access to this role.
*/
function remove(Role storage role, address account) internal {
require(has(role, account), "Roles: account does not have role");
role.bearer[account] = false;
}
/**
* @dev Check if an account has this role.
*
* @return bool
*/
function has(Role storage role, address account) internal view returns (bool) {
require(account != address(0), "Roles: account is the zero address");
return role.bearer[account];
}
}
/**
* @dev Interface of the ERC20 standard
*/
interface IERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
function totalSupply() external view returns (uint256);
function balanceOf(address account) external view returns (uint256);
function transfer(address recipient, uint256 amount) external returns (bool);
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
function approve(address spender, uint256 amount) external returns (bool);
function allowance(address owner, address spender) external view returns (uint256);
event Transfer(address indexed from, address indexed to, uint256 value);
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Interface of an allocation contract.
*/
interface IAllocation {
function reservedOf(address account) external view returns (uint256);
}
/**
* @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.
*/
contract Ownable {
address internal _owner;
address internal _newOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
event OwnershipAccepted(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 addresses of the current and new owner.
*/
function owner() public view returns (address currentOwner, address newOwner) {
currentOwner = _owner;
newOwner = _newOwner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(msg.sender), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner(address account) public view returns (bool) {
return account == _owner;
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*
* IMPORTANT: Need to run {acceptOwnership} by the new owner.
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_newOwner = newOwner;
}
/**
* @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 Accept ownership of the contract.
*
* Can only be called by the new owner.
*/
function acceptOwnership() public {
require(msg.sender == _newOwner, "Ownable: caller is not the new owner address");
require(msg.sender != address(0), "Ownable: caller is the zero address");
emit OwnershipAccepted(_owner, msg.sender);
_owner = msg.sender;
_newOwner = address(0);
}
/**
* @dev Rescue compatible ERC20 Token
*
* Can only be called by the current owner.
*/
function rescueTokens(address tokenAddr, address recipient, uint256 amount) external onlyOwner {
IERC20 _token = IERC20(tokenAddr);
require(recipient != address(0), "Rescue: recipient is the zero address");
uint256 balance = _token.balanceOf(address(this));
require(balance >= amount, "Rescue: amount exceeds balance");
_token.transfer(recipient, amount);
}
/**
* @dev Withdraw Ether
*
* Can only be called by the current owner.
*/
function withdrawEther(address payable recipient, uint256 amount) external onlyOwner {
require(recipient != address(0), "Withdraw: recipient is the zero address");
uint256 balance = address(this).balance;
require(balance >= amount, "Withdraw: amount exceeds balance");
recipient.transfer(amount);
}
}
/**
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
bool private _paused;
event Paused();
event Unpaused();
/**
* @dev Constructor
*/
constructor () internal {
_paused = false;
}
/**
* @return Returns true if the contract is paused, false otherwise.
*/
function paused() public view returns (bool) {
return _paused;
}
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!_paused, "Paused");
_;
}
/**
* @dev Sets paused state.
*
* Can only be called by the current owner.
*/
function setPaused(bool value) external onlyOwner {
_paused = value;
if (_paused) {
emit Paused();
} else {
emit Unpaused();
}
}
}
/**
* @title Voken Main Contract v2.0
*/
contract Voken2 is Ownable, Pausable, IERC20 {
using SafeMath256 for uint256;
using Roles for Roles.Role;
Roles.Role private _globals;
Roles.Role private _proxies;
Roles.Role private _minters;
string private _name = "Vision.Network 100G Token v2.0";
string private _symbol = "Voken2.0";
uint8 private _decimals = 6;
uint256 private _cap;
uint256 private _totalSupply;
bool private _whitelistingMode;
bool private _safeMode;
uint16 private _BURNING_PERMILL;
uint256 private _whitelistCounter;
uint256 private _WHITELIST_TRIGGER = 1001000000; // 1001 VOKEN for sign-up trigger
uint256 private _WHITELIST_REFUND = 1000000; // 1 VOKEN for success signal
uint256[15] private _WHITELIST_REWARDS = [
300000000, // 300 Voken for Level.1
200000000, // 200 Voken for Level.2
100000000, // 100 Voken for Level.3
100000000, // 100 Voken for Level.4
100000000, // 100 Voken for Level.5
50000000, // 50 Voken for Level.6
40000000, // 40 Voken for Level.7
30000000, // 30 Voken for Level.8
20000000, // 20 Voken for Level.9
10000000, // 10 Voken for Level.10
10000000, // 10 Voken for Level.11
10000000, // 10 Voken for Level.12
10000000, // 10 Voken for Level.13
10000000, // 10 Voken for Level.14
10000000 // 10 Voken for Level.15
];
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => IAllocation[]) private _allocations;
mapping (address => mapping (address => bool)) private _addressAllocations;
mapping (address => address) private _referee;
mapping (address => address[]) private _referrals;
event Donate(address indexed account, uint256 amount);
event Burn(address indexed account, uint256 amount);
event ProxyAdded(address indexed account);
event ProxyRemoved(address indexed account);
event GlobalAdded(address indexed account);
event GlobalRemoved(address indexed account);
event MinterAdded(address indexed account);
event MinterRemoved(address indexed account);
event Mint(address indexed account, uint256 amount);
event MintWithAllocation(address indexed account, uint256 amount, IAllocation indexed allocationContract);
event WhitelistSignUpEnabled();
event WhitelistSignUpDisabled();
event WhitelistSignUp(address indexed account, address indexed refereeAccount);
event SafeModeOn();
event SafeModeOff();
event BurningModeOn();
event BurningModeOff();
/**
* @dev Returns true if the `account` has the Global role
*/
function isGlobal(address account) public view returns (bool) {
return _globals.has(account);
}
/**
* @dev Give an `account` access to the Global role.
*
* Can only be called by the current owner.
*/
function addGlobal(address account) public onlyOwner {
_globals.add(account);
emit GlobalAdded(account);
}
/**
* @dev Remove an `account` access from the Global role.
*
* Can only be called by the current owner.
*/
function removeGlobal(address account) public onlyOwner {
_globals.remove(account);
emit GlobalRemoved(account);
}
/**
* @dev Throws if called by account which is not a proxy.
*/
modifier onlyProxy() {
require(isProxy(msg.sender), "ProxyRole: caller does not have the Proxy role");
_;
}
/**
* @dev Returns true if the `account` has the Proxy role.
*/
function isProxy(address account) public view returns (bool) {
return _proxies.has(account);
}
/**
* @dev Give an `account` access to the Proxy role.
*
* Can only be called by the current owner.
*/
function addProxy(address account) public onlyOwner {
_proxies.add(account);
emit ProxyAdded(account);
}
/**
* @dev Remove an `account` access from the Proxy role.
*
* Can only be called by the current owner.
*/
function removeProxy(address account) public onlyOwner {
_proxies.remove(account);
emit ProxyRemoved(account);
}
/**
* @dev Throws if called by account which is not a minter.
*/
modifier onlyMinter() {
require(isMinter(msg.sender), "MinterRole: caller does not have the Minter role");
_;
}
/**
* @dev Returns true if the `account` has the Minter role
*/
function isMinter(address account) public view returns (bool) {
return _minters.has(account);
}
/**
* @dev Give an `account` access to the Minter role.
*
* Can only be called by the current owner.
*/
function addMinter(address account) public onlyOwner {
_minters.add(account);
emit MinterAdded(account);
}
/**
* @dev Remove an `account` access from the Minter role.
*
* Can only be called by the current owner.
*/
function removeMinter(address account) public onlyOwner {
_minters.remove(account);
emit MinterRemoved(account);
}
/**
* @dev Constructor
*/
constructor () public {
addGlobal(address(this));
addProxy(msg.sender);
addMinter(msg.sender);
setWhitelistingMode(true);
setSafeMode(true);
setBurningMode(10);
_cap = 35000000000000000; // 35 billion cap, that is 35000000000.000000
_whitelistCounter = 1;
_referee[msg.sender] = msg.sender;
emit WhitelistSignUp(msg.sender, msg.sender);
}
/**
* @dev Donate
*/
function () external payable {
if (msg.value > 0) {
emit Donate(msg.sender, msg.value);
}
}
/**
* @dev Returns the full name of VOKEN.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of VOKEN.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev Returns the cap on VOKEN's total supply.
*/
function cap() public view returns (uint256) {
return _cap;
}
/**
* @dev Returns the amount of VOKEN in existence.
*/
function totalSupply() public view returns (uint256) {
return _totalSupply;
}
/**
* @dev Returns the amount of VOKEN owned by `account`.
*/
function balanceOf(address account) public view returns (uint256) {
return _balances[account];
}
/**
* @dev Returns the reserved amount of VOKEN by `account`.
*/
function reservedOf(address account) public view returns (uint256 reserved) {
uint256 __len = _allocations[account].length;
if (__len > 0) {
for (uint256 i = 0; i < __len; i++) {
reserved = reserved.add(_allocations[account][i].reservedOf(account));
}
}
}
/**
* @dev Returns the available amount of VOKEN by `account` and a certain `amount`.
*/
function _getAvailableAmount(address account, uint256 amount) private view returns (uint256) {
uint256 __available = balanceOf(account).sub(reservedOf(account));
if (amount <= __available) {
return amount;
}
else if (__available > 0) {
return __available;
}
revert("VOKEN: available balance is zero");
}
/**
* @dev Returns the allocation contracts' addresses on `account`.
*/
function allocations(address account) public view returns (IAllocation[] memory contracts) {
contracts = _allocations[account];
}
/**
* @dev Moves `amount` VOKEN from the caller's account to `recipient`.
*
* Auto handle {WhitelistSignUp} when `amount` is a specific value.
* Auto handle {Burn} when `recipient` is a `address(this)` or `address(0)`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) public whenNotPaused returns (bool) {
// Whitelist sign-up
if (amount == _WHITELIST_TRIGGER && _whitelistingMode && whitelisted(recipient) && !whitelisted(msg.sender)) {
_move(msg.sender, address(this), _WHITELIST_TRIGGER);
_whitelist(msg.sender, recipient);
_distributeForWhitelist(msg.sender);
}
// Burn
else if (recipient == address(this) || recipient == address(0)) {
_burn(msg.sender, amount);
}
// Normal Transfer
else {
_transfer(msg.sender, recipient, _getAvailableAmount(msg.sender, amount));
}
return true;
}
/**
* @dev Moves `amount` VOKEN from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Auto handle {Burn} when `recipient` is a `address(this)` or `address(0)`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
* Emits an {Approval} event indicating the updated allowance.
*/
function transferFrom(address sender, address recipient, uint256 amount) public whenNotPaused returns (bool) {
// Burn
if (recipient == address(this) || recipient == address(0)) {
_burn(msg.sender, amount);
}
// Normal transfer
else {
uint256 __amount = _getAvailableAmount(sender, amount);
_transfer(sender, recipient, __amount);
_approve(sender, msg.sender, _allowances[sender][msg.sender].sub(__amount, "VOKEN: transfer amount exceeds allowance"));
}
return true;
}
/**
* @dev Destroys `amount` VOKEN from the caller.
*
* Emits a {Transfer} event with `to` set to the zero address.
*/
function burn(uint256 amount) public whenNotPaused returns (bool) {
_burn(msg.sender, amount);
return true;
}
/**
* @dev Destoys `amount` VOKEN from `account`.`amount` is then deducted
* from the caller's allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
* Emits an {Approval} event indicating the updated allowance.
*/
function burnFrom(address account, uint256 amount) public whenNotPaused returns (bool) {
_burn(account, amount);
_approve(account, msg.sender, _allowances[account][msg.sender].sub(amount, "VOKEN: burn amount exceeds allowance"));
return true;
}
/**
* @dev Creates `amount` VOKEN and assigns them to `account`.
*
* Can only be called by a minter.
*/
function mint(address account, uint256 amount) public whenNotPaused onlyMinter returns (bool) {
_mint(account, amount);
return true;
}
/**
* @dev Creates `amount` VOKEN and assigns them to `account`.
*
* With an `allocationContract`
*
* Can only be called by a minter.
*/
function mintWithAllocation(address account, uint256 amount, IAllocation allocationContract) public whenNotPaused onlyMinter returns (bool) {
_mintWithAllocation(account, amount, allocationContract);
return true;
}
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 value) public whenNotPaused returns (bool) {
_approve(msg.sender, spender, value);
return true;
}
/**
* @dev Returns the remaining number of VOKEN that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}.
* This is zero by default.
*/
function allowance(address owner, address spender) public view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* Emits an {Approval} event indicating the updated allowance.
*/
function increaseAllowance(address spender, uint256 addedValue) public whenNotPaused 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.
*
* Emits an {Approval} event indicating the updated allowance.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public whenNotPaused returns (bool) {
_approve(msg.sender, spender, _allowances[msg.sender][spender].sub(subtractedValue, "VOKEN: decreased allowance below zero"));
return true;
}
/**
* @dev Moves VOKEN `amount` from `sender` to `recipient`.
*
* May reject non-whitelist transaction.
*
* Emits a {Transfer} event.
*/
function _transfer(address sender, address recipient, uint256 amount) private {
require(recipient != address(0), "VOKEN: recipient is the zero address");
if (_safeMode && !isGlobal(sender) && !isGlobal(recipient)) {
require(whitelisted(sender), "VOKEN: sender is not whitelisted");
}
if (_BURNING_PERMILL > 0) {
uint256 __burning = amount.mul(_BURNING_PERMILL).div(1000);
uint256 __amount = amount.sub(__burning);
_balances[sender] = _balances[sender].sub(__amount);
_balances[recipient] = _balances[recipient].add(__amount);
emit Transfer(sender, recipient, __amount);
_burn(sender, __burning);
}
else {
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
}
/**
* @dev Moves VOKEN `amount` from `sender` to `recipient`.
*
* May reject non-whitelist transaction.
*
* Emits a {Transfer} event.
*/
function _move(address sender, address recipient, uint256 amount) private {
require(recipient != address(0), "VOKEN: recipient is the zero address");
_balances[sender] = _balances[sender].sub(amount);
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/**
* @dev Creates `amount` VOKEN and assigns them to `account`, increasing the total supply.
*
* Emits a {Mint} event.
* Emits a {Transfer} event with `from` set to the zero address.
*/
function _mint(address account, uint256 amount) private {
require(_totalSupply.add(amount) <= _cap, "VOKEN: total supply cap exceeded");
require(account != address(0), "VOKEN: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Mint(account, amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Creates `amount` VOKEN and assigns them to `account`, increasing the total supply.
*
* With an `allocationContract`
*
* Emits a {Transfer} event with `from` set to the zero address.
*/
function _mintWithAllocation(address account, uint256 amount, IAllocation allocationContract) private {
require(_totalSupply.add(amount) <= _cap, "VOKEN: total supply cap exceeded");
require(account != address(0), "VOKEN: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
if (!_addressAllocations[account][address(allocationContract)]) {
_allocations[account].push(allocationContract);
_addressAllocations[account][address(allocationContract)] = true;
}
emit MintWithAllocation(account, amount, allocationContract);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` VOKEN from `account`, reducing the total supply.
*
* Emits a {Burn} event.
* Emits a {Transfer} event with `to` set to the zero address.
*/
function _burn(address account, uint256 amount) private {
uint256 __amount = _getAvailableAmount(account, amount);
_balances[account] = _balances[account].sub(__amount, "VOKEN: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(__amount);
_cap = _cap.sub(__amount);
emit Burn(account, __amount);
emit Transfer(account, address(0), __amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s VOKEN.
*
* Emits an {Approval} event.
*/
function _approve(address owner, address spender, uint256 value) private {
require(owner != address(0), "VOKEN: approve from the zero address");
require(spender != address(0), "VOKEN: approve to the zero address");
require(value <= _getAvailableAmount(spender, value), "VOKEN: approve exceeds available balance");
_allowances[owner][spender] = value;
emit Approval(owner, spender, value);
}
/**
* @dev Sets the full name of VOKEN.
*
* Can only be called by the current owner.
*/
function rename(string calldata value) external onlyOwner {
_name = value;
}
/**
* @dev Sets the symbol of VOKEN.
*
* Can only be called by the current owner.
*/
function setSymbol(string calldata value) external onlyOwner {
_symbol = value;
}
/**
* @dev Returns true if the `account` is whitelisted.
*/
function whitelisted(address account) public view returns (bool) {
return _referee[account] != address(0);
}
/**
* @dev Returns the whitelist counter.
*/
function whitelistCounter() public view returns (uint256) {
return _whitelistCounter;
}
/**
* @dev Returns true if the sign-up for whitelist is allowed.
*/
function whitelistingMode() public view returns (bool) {
return _whitelistingMode;
}
/**
* @dev Returns the referee of an `account`.
*/
function whitelistReferee(address account) public view returns (address) {
return _referee[account];
}
/**
* @dev Returns referrals of a `account`
*/
function whitelistReferrals(address account) public view returns (address[] memory) {
return _referrals[account];
}
/**
* @dev Returns the referrals count of an `account`.
*/
function whitelistReferralsCount(address account) public view returns (uint256) {
return _referrals[account].length;
}
/**
* @dev Push whitelist, batch.
*
* Can only be called by a proxy.
*/
function pushWhitelist(address[] memory accounts, address[] memory refereeAccounts) public onlyProxy returns (bool) {
require(accounts.length == refereeAccounts.length, "VOKEN Whitelist: batch length is not match");
for (uint256 i = 0; i < accounts.length; i++) {
if (accounts[i] != address(0) && !whitelisted(accounts[i]) && whitelisted(refereeAccounts[i])) {
_whitelist(accounts[i], refereeAccounts[i]);
}
}
return true;
}
/**
* @dev Whitelist an `account` with a `refereeAccount`.
*
* Emits {WhitelistSignUp} event.
*/
function _whitelist(address account, address refereeAccount) private {
require(!whitelisted(account), "Whitelist: account is already whitelisted");
require(whitelisted(refereeAccount), "Whitelist: refereeAccount is not whitelisted");
_referee[account] = refereeAccount;
_referrals[refereeAccount].push(account);
_whitelistCounter = _whitelistCounter.add(1);
emit WhitelistSignUp(account, refereeAccount);
}
/**
* @dev Distribute.
*/
function _distributeForWhitelist(address account) private {
uint256 __distributedAmount;
uint256 __burnAmount;
address __account = account;
for(uint i = 0; i < _WHITELIST_REWARDS.length; i++) {
address __referee = _referee[__account];
if (__referee != address(0) && __referee != __account && _referrals[__referee].length > i) {
_move(address(this), __referee, _WHITELIST_REWARDS[i]);
__distributedAmount = __distributedAmount.add(_WHITELIST_REWARDS[i]);
}
__account = __referee;
}
// Burn
__burnAmount = _WHITELIST_TRIGGER.sub(_WHITELIST_REFUND).sub(__distributedAmount);
if (__burnAmount > 0) {
_burn(address(this), __burnAmount);
}
// Transfer VOKEN refund as a success signal.
_move(address(this), account, _WHITELIST_REFUND);
}
/**
* @dev Enable/disable sign-up for whitelist.
*
* Can only be called by the current owner.
*/
function setWhitelistingMode(bool value) public onlyOwner {
_whitelistingMode = value;
if (_whitelistingMode) {
emit WhitelistSignUpEnabled();
} else {
emit WhitelistSignUpDisabled();
}
}
/**
* @dev Returns true if a transaction from non-whitelisted address is not allowed.
*/
function safeMode() public view returns (bool) {
return _safeMode;
}
/**
* @dev Disable/enable non-whitelist transaction.
*
* Can only be called by the current owner.
*/
function setSafeMode(bool value) public onlyOwner {
_safeMode = value;
if (_safeMode) {
emit SafeModeOn();
} else {
emit SafeModeOff();
}
}
/**
* Returns {bool}, {value} of burning mode.
*/
function burningMode() public view returns (bool, uint16) {
return (_BURNING_PERMILL > 0, _BURNING_PERMILL);
}
/**
* @dev Sets the burning mode by `value`.
*/
function setBurningMode(uint16 value) public onlyOwner {
require(value <= 1000, "BurningMode: value is greater than 1000");
if (value > 0) {
_BURNING_PERMILL = value;
emit BurningModeOn();
}
else {
_BURNING_PERMILL = 0;
emit BurningModeOff();
}
}
}
|
Creates `amount` VOKEN and assigns them to `account`, increasing the total supply. With an `allocationContract` Emits a {Transfer} event with `from` set to the zero address./
|
function _mintWithAllocation(address account, uint256 amount, IAllocation allocationContract) private {
require(_totalSupply.add(amount) <= _cap, "VOKEN: total supply cap exceeded");
require(account != address(0), "VOKEN: mint to the zero address");
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
if (!_addressAllocations[account][address(allocationContract)]) {
_allocations[account].push(allocationContract);
_addressAllocations[account][address(allocationContract)] = true;
}
emit MintWithAllocation(account, amount, allocationContract);
emit Transfer(address(0), account, amount);
}
| 15,798,664 |
/**
*Submitted for verification at Etherscan.io on 2021-03-31
*/
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
pragma solidity 0.5.12;
contract ICErc20 {
address public underlying;
function mint(uint256 mintAmount) external returns (uint);
function redeemUnderlying(uint256 redeemAmount) external returns (uint);
function balanceOfUnderlying(address owner) external returns (uint);
function getCash() external view returns (uint);
function supplyRatePerBlock() external view returns (uint);
}
contract GemLike {
function allowance(address, address) public returns (uint);
function approve(address, uint) public;
function transfer(address, uint) public returns (bool);
function transferFrom(address, address, uint) public returns (bool);
}
contract ValueLike {
function peek() public returns (uint, bool);
}
contract SaiTubLike {
function skr() public view returns (GemLike);
function gem() public view returns (GemLike);
function gov() public view returns (GemLike);
function sai() public view returns (GemLike);
function pep() public view returns (ValueLike);
function vox() public view returns (VoxLike);
function bid(uint) public view returns (uint);
function ink(bytes32) public view returns (uint);
function tag() public view returns (uint);
function tab(bytes32) public returns (uint);
function rap(bytes32) public returns (uint);
function draw(bytes32, uint) public;
function shut(bytes32) public;
function exit(uint) public;
function give(bytes32, address) public;
}
contract VoxLike {
function par() public returns (uint);
}
contract JoinLike {
function ilk() public returns (bytes32);
function gem() public returns (GemLike);
function dai() public returns (GemLike);
function join(address, uint) public;
function exit(address, uint) public;
}
contract VatLike {
function ilks(bytes32) public view returns (uint, uint, uint, uint, uint);
function hope(address) public;
function frob(bytes32, address, address, address, int, int) public;
}
contract ManagerLike {
function vat() public view returns (address);
function urns(uint) public view returns (address);
function open(bytes32, address) public returns (uint);
function frob(uint, int, int) public;
function give(uint, address) public;
function move(uint, address, uint) public;
}
contract OtcLike {
function getPayAmount(address, address, uint) public view returns (uint);
function buyAllAmount(address, uint, address, uint) public;
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @dev Interface of the global ERC1820 Registry, as defined in the
* https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register
* implementers for interfaces in this registry, as well as query support.
*
* Implementers may be shared by multiple accounts, and can also implement more
* than a single interface for each account. Contracts can implement interfaces
* for themselves, but externally-owned accounts (EOA) must delegate this to a
* contract.
*
* {IERC165} interfaces can also be queried via the registry.
*
* For an in-depth explanation and source code analysis, see the EIP text.
*/
interface IERC1820Registry {
/**
* @dev Sets `newManager` as the manager for `account`. A manager of an
* account is able to set interface implementers for it.
*
* By default, each account is its own manager. Passing a value of `0x0` in
* `newManager` will reset the manager to this initial state.
*
* Emits a {ManagerChanged} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
*/
function setManager(address account, address newManager) external;
/**
* @dev Returns the manager for `account`.
*
* See {setManager}.
*/
function getManager(address account) external view returns (address);
/**
* @dev Sets the `implementer` contract as `account`'s implementer for
* `interfaceHash`.
*
* `account` being the zero address is an alias for the caller's address.
* The zero address can also be used in `implementer` to remove an old one.
*
* See {interfaceHash} to learn how these are created.
*
* Emits an {InterfaceImplementerSet} event.
*
* Requirements:
*
* - the caller must be the current manager for `account`.
* - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not
* end in 28 zeroes).
* - `implementer` must implement {IERC1820Implementer} and return true when
* queried for support, unless `implementer` is the caller. See
* {IERC1820Implementer-canImplementInterfaceForAddress}.
*/
function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external;
/**
* @dev Returns the implementer of `interfaceHash` for `account`. If no such
* implementer is registered, returns the zero address.
*
* If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28
* zeroes), `account` will be queried for support of it.
*
* `account` being the zero address is an alias for the caller's address.
*/
function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address);
/**
* @dev Returns the interface hash for an `interfaceName`, as defined in the
* corresponding
* https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP].
*/
function interfaceHash(string calldata interfaceName) external pure returns (bytes32);
/**
* @notice Updates the cache with whether the contract implements an ERC165 interface or not.
* @param account Address of the contract for which to update the cache.
* @param interfaceId ERC165 interface for which to update the cache.
*/
function updateERC165Cache(address account, bytes4 interfaceId) external;
/**
* @notice Checks whether a contract implements an ERC165 interface or not.
* If the result is not cached a direct lookup on the contract address is performed.
* If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling
* {updateERC165Cache} with the contract address.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool);
/**
* @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache.
* @param account Address of the contract to check.
* @param interfaceId ERC165 interface to check.
* @return True if `account` implements `interfaceId`, false otherwise.
*/
function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool);
event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer);
event ManagerChanged(address indexed account, address indexed newManager);
}
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot overflow.
*
* _Available since v2.4.0._
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* _Available since v2.4.0._
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
/**
* @title Initializable
*
* @dev Helper contract to support initializer functions. To use it, replace
* the constructor with a function that has the `initializer` modifier.
* WARNING: Unlike constructors, initializer functions must be manually
* invoked. This applies both to deploying an Initializable contract, as well
* as extending an Initializable contract via inheritance.
* WARNING: When used with inheritance, manual care must be taken to not invoke
* a parent initializer twice, or ensure that all initializers are idempotent,
* because this is not dealt with automatically as with constructors.
*/
contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private initializing;
/**
* @dev Modifier to use in the initializer function of a contract.
*/
modifier initializer() {
require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized");
bool isTopLevelCall = !initializing;
if (isTopLevelCall) {
initializing = true;
initialized = true;
}
_;
if (isTopLevelCall) {
initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
uint256 cs;
assembly { cs := extcodesize(address) }
return cs == 0;
}
// Reserved storage space to allow for layout changes in the future.
uint256[50] private ______gap;
}
/**
* @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.
*/
contract ReentrancyGuard is Initializable {
// counter to allow mutex lock with only one SSTORE operation
uint256 private _guardCounter;
function initialize() public initializer {
// The counter starts at one to prevent changing it from zero to a non-zero
// value, which is a more expensive operation.
_guardCounter = 1;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
_guardCounter += 1;
uint256 localCounter = _guardCounter;
_;
require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call");
}
uint256[50] private ______gap;
}
/**
* @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];
}
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @author Brendan Asselstine
* @notice A library that uses entropy to select a random number within a bound. Compensates for modulo bias.
* @dev Thanks to https://medium.com/hownetworks/dont-waste-cycles-with-modulo-bias-35b6fdafcf94
*/
library UniformRandomNumber {
/// @notice Select a random number without modulo bias using a random seed and upper bound
/// @param _entropy The seed for randomness
/// @param _upperBound The upper bound of the desired number
/// @return A random number less than the _upperBound
function uniform(uint256 _entropy, uint256 _upperBound) internal pure returns (uint256) {
require(_upperBound > 0, "UniformRand/min-bound");
uint256 min = -_upperBound % _upperBound;
uint256 random = _entropy;
while (true) {
if (random >= min) {
break;
}
random = uint256(keccak256(abi.encodePacked(random)));
}
return random % _upperBound;
}
}
/**
* @reviewers: [@clesaege, @unknownunknown1, @ferittuncer]
* @auditors: []
* @bounties: [<14 days 10 ETH max payout>]
* @deployments: []
*/
/**
* @title SortitionSumTreeFactory
* @author Enrique Piqueras - <[email protected]>
* @dev A factory of trees that keep track of staked values for sortition.
*/
library SortitionSumTreeFactory {
/* Structs */
struct SortitionSumTree {
uint K; // The maximum number of childs per node.
// We use this to keep track of vacant positions in the tree after removing a leaf. This is for keeping the tree as balanced as possible without spending gas on moving nodes around.
uint[] stack;
uint[] nodes;
// Two-way mapping of IDs to node indexes. Note that node index 0 is reserved for the root node, and means the ID does not have a node.
mapping(bytes32 => uint) IDsToNodeIndexes;
mapping(uint => bytes32) nodeIndexesToIDs;
}
/* Storage */
struct SortitionSumTrees {
mapping(bytes32 => SortitionSumTree) sortitionSumTrees;
}
/* internal */
/**
* @dev Create a sortition sum tree at the specified key.
* @param _key The key of the new tree.
* @param _K The number of children each node in the tree should have.
*/
function createTree(SortitionSumTrees storage self, bytes32 _key, uint _K) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
require(tree.K == 0, "Tree already exists.");
require(_K > 1, "K must be greater than one.");
tree.K = _K;
tree.stack.length = 0;
tree.nodes.length = 0;
tree.nodes.push(0);
}
/**
* @dev Set a value of a tree.
* @param _key The key of the tree.
* @param _value The new value.
* @param _ID The ID of the value.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function set(SortitionSumTrees storage self, bytes32 _key, uint _value, bytes32 _ID) internal {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (treeIndex == 0) { // No existing node.
if (_value != 0) { // Non zero value.
// Append.
// Add node.
if (tree.stack.length == 0) { // No vacant spots.
// Get the index and append the value.
treeIndex = tree.nodes.length;
tree.nodes.push(_value);
// Potentially append a new node and make the parent a sum node.
if (treeIndex != 1 && (treeIndex - 1) % tree.K == 0) { // Is first child.
uint parentIndex = treeIndex / tree.K;
bytes32 parentID = tree.nodeIndexesToIDs[parentIndex];
uint newIndex = treeIndex + 1;
tree.nodes.push(tree.nodes[parentIndex]);
delete tree.nodeIndexesToIDs[parentIndex];
tree.IDsToNodeIndexes[parentID] = newIndex;
tree.nodeIndexesToIDs[newIndex] = parentID;
}
} else { // Some vacant spot.
// Pop the stack and append the value.
treeIndex = tree.stack[tree.stack.length - 1];
tree.stack.length--;
tree.nodes[treeIndex] = _value;
}
// Add label.
tree.IDsToNodeIndexes[_ID] = treeIndex;
tree.nodeIndexesToIDs[treeIndex] = _ID;
updateParents(self, _key, treeIndex, true, _value);
}
} else { // Existing node.
if (_value == 0) { // Zero value.
// Remove.
// Remember value and set to 0.
uint value = tree.nodes[treeIndex];
tree.nodes[treeIndex] = 0;
// Push to stack.
tree.stack.push(treeIndex);
// Clear label.
delete tree.IDsToNodeIndexes[_ID];
delete tree.nodeIndexesToIDs[treeIndex];
updateParents(self, _key, treeIndex, false, value);
} else if (_value != tree.nodes[treeIndex]) { // New, non zero value.
// Set.
bool plusOrMinus = tree.nodes[treeIndex] <= _value;
uint plusOrMinusValue = plusOrMinus ? _value - tree.nodes[treeIndex] : tree.nodes[treeIndex] - _value;
tree.nodes[treeIndex] = _value;
updateParents(self, _key, treeIndex, plusOrMinus, plusOrMinusValue);
}
}
}
/* internal Views */
/**
* @dev Query the leaves of a tree. Note that if `startIndex == 0`, the tree is empty and the root node will be returned.
* @param _key The key of the tree to get the leaves from.
* @param _cursor The pagination cursor.
* @param _count The number of items to return.
* @return The index at which leaves start, the values of the returned leaves, and whether there are more for pagination.
* `O(n)` where
* `n` is the maximum number of nodes ever appended.
*/
function queryLeafs(
SortitionSumTrees storage self,
bytes32 _key,
uint _cursor,
uint _count
) internal view returns(uint startIndex, uint[] memory values, bool hasMore) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
// Find the start index.
for (uint i = 0; i < tree.nodes.length; i++) {
if ((tree.K * i) + 1 >= tree.nodes.length) {
startIndex = i;
break;
}
}
// Get the values.
uint loopStartIndex = startIndex + _cursor;
values = new uint[](loopStartIndex + _count > tree.nodes.length ? tree.nodes.length - loopStartIndex : _count);
uint valuesIndex = 0;
for (uint j = loopStartIndex; j < tree.nodes.length; j++) {
if (valuesIndex < _count) {
values[valuesIndex] = tree.nodes[j];
valuesIndex++;
} else {
hasMore = true;
break;
}
}
}
/**
* @dev Draw an ID from a tree using a number. Note that this function reverts if the sum of all values in the tree is 0.
* @param _key The key of the tree.
* @param _drawnNumber The drawn number.
* @return The drawn ID.
* `O(k * log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function draw(SortitionSumTrees storage self, bytes32 _key, uint _drawnNumber) internal view returns(bytes32 ID) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = 0;
uint currentDrawnNumber = _drawnNumber % tree.nodes[0];
while ((tree.K * treeIndex) + 1 < tree.nodes.length) // While it still has children.
for (uint i = 1; i <= tree.K; i++) { // Loop over children.
uint nodeIndex = (tree.K * treeIndex) + i;
uint nodeValue = tree.nodes[nodeIndex];
if (currentDrawnNumber >= nodeValue) currentDrawnNumber -= nodeValue; // Go to the next child.
else { // Pick this child.
treeIndex = nodeIndex;
break;
}
}
ID = tree.nodeIndexesToIDs[treeIndex];
}
/** @dev Gets a specified ID's associated value.
* @param _key The key of the tree.
* @param _ID The ID of the value.
* @return The associated value.
*/
function stakeOf(SortitionSumTrees storage self, bytes32 _key, bytes32 _ID) internal view returns(uint value) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint treeIndex = tree.IDsToNodeIndexes[_ID];
if (treeIndex == 0) value = 0;
else value = tree.nodes[treeIndex];
}
function total(SortitionSumTrees storage self, bytes32 _key) internal view returns (uint) {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
if (tree.nodes.length == 0) {
return 0;
} else {
return tree.nodes[0];
}
}
/* Private */
/**
* @dev Update all the parents of a node.
* @param _key The key of the tree to update.
* @param _treeIndex The index of the node to start from.
* @param _plusOrMinus Wether to add (true) or substract (false).
* @param _value The value to add or substract.
* `O(log_k(n))` where
* `k` is the maximum number of childs per node in the tree,
* and `n` is the maximum number of nodes ever appended.
*/
function updateParents(SortitionSumTrees storage self, bytes32 _key, uint _treeIndex, bool _plusOrMinus, uint _value) private {
SortitionSumTree storage tree = self.sortitionSumTrees[_key];
uint parentIndex = _treeIndex;
while (parentIndex != 0) {
parentIndex = (parentIndex - 1) / tree.K;
tree.nodes[parentIndex] = _plusOrMinus ? tree.nodes[parentIndex] + _value : tree.nodes[parentIndex] - _value;
}
}
}
/**
* @author Brendan Asselstine
* @notice Tracks committed and open balances for addresses. Affords selection of an address by indexing all committed balances.
*
* Balances are tracked in Draws. There is always one open Draw. Deposits are always added to the open Draw.
* When a new draw is opened, the previous opened draw is committed.
*
* The committed balance for an address is the total of their balances for committed Draws.
* An address's open balance is their balance in the open Draw.
*/
library DrawManager {
using SortitionSumTreeFactory for SortitionSumTreeFactory.SortitionSumTrees;
using SafeMath for uint256;
/**
* The ID to use for the selection tree.
*/
bytes32 public constant TREE_OF_DRAWS = "TreeOfDraws";
uint8 public constant MAX_BRANCHES_PER_NODE = 10;
/**
* Stores information for all draws.
*/
struct State {
/**
* Each Draw stores it's address balances in a sortitionSumTree. Draw trees are indexed using the Draw index.
* There is one root sortitionSumTree that stores all of the draw totals. The root tree is indexed using the constant TREE_OF_DRAWS.
*/
SortitionSumTreeFactory.SortitionSumTrees sortitionSumTrees;
/**
* Stores the consolidated draw index that an address deposited to.
*/
mapping(address => uint256) consolidatedDrawIndices;
/**
* Stores the last Draw index that an address deposited to.
*/
mapping(address => uint256) latestDrawIndices;
/**
* Stores a mapping of Draw index => Draw total
*/
mapping(uint256 => uint256) __deprecated__drawTotals;
/**
* The current open Draw index
*/
uint256 openDrawIndex;
/**
* The total of committed balances
*/
uint256 __deprecated__committedSupply;
}
/**
* @notice Opens the next Draw and commits the previous open Draw (if any).
* @param self The drawState this library is attached to
* @return The index of the new open Draw
*/
function openNextDraw(State storage self) public returns (uint256) {
if (self.openDrawIndex == 0) {
// If there is no previous draw, we must initialize
self.sortitionSumTrees.createTree(TREE_OF_DRAWS, MAX_BRANCHES_PER_NODE);
} else {
// else add current draw to sortition sum trees
bytes32 drawId = bytes32(self.openDrawIndex);
uint256 drawTotal = openSupply(self);
self.sortitionSumTrees.set(TREE_OF_DRAWS, drawTotal, drawId);
}
// now create a new draw
uint256 drawIndex = self.openDrawIndex.add(1);
self.sortitionSumTrees.createTree(bytes32(drawIndex), MAX_BRANCHES_PER_NODE);
self.openDrawIndex = drawIndex;
return drawIndex;
}
/**
* @notice Deposits the given amount into the current open draw by the given user.
* @param self The DrawManager state
* @param _addr The address to deposit for
* @param _amount The amount to deposit
*/
function deposit(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 openDrawIndex = self.openDrawIndex;
// update the current draw
uint256 currentAmount = self.sortitionSumTrees.stakeOf(bytes32(openDrawIndex), userId);
currentAmount = currentAmount.add(_amount);
drawSet(self, openDrawIndex, currentAmount, _addr);
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
// if this is the user's first draw, set it
if (consolidatedDrawIndex == 0) {
self.consolidatedDrawIndices[_addr] = openDrawIndex;
// otherwise, if the consolidated draw is not this draw
} else if (consolidatedDrawIndex != openDrawIndex) {
// if a second draw does not exist
if (latestDrawIndex == 0) {
// set the second draw to the current draw
self.latestDrawIndices[_addr] = openDrawIndex;
// otherwise if a second draw exists but is not the current one
} else if (latestDrawIndex != openDrawIndex) {
// merge it into the first draw, and update the second draw index to this one
uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId);
uint256 latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId);
drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(latestAmount), _addr);
drawSet(self, latestDrawIndex, 0, _addr);
self.latestDrawIndices[_addr] = openDrawIndex;
}
}
}
/**
* @notice Deposits into a user's committed balance, thereby bypassing the open draw.
* @param self The DrawManager state
* @param _addr The address of the user for whom to deposit
* @param _amount The amount to deposit
*/
function depositCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
// if they have a committed balance
if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) {
uint256 consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId);
drawSet(self, consolidatedDrawIndex, consolidatedAmount.add(_amount), _addr);
} else { // they must not have any committed balance
self.latestDrawIndices[_addr] = consolidatedDrawIndex;
self.consolidatedDrawIndices[_addr] = self.openDrawIndex.sub(1);
drawSet(self, self.consolidatedDrawIndices[_addr], _amount, _addr);
}
}
/**
* @notice Withdraws a user's committed and open draws.
* @param self The DrawManager state
* @param _addr The address whose balance to withdraw
*/
function withdraw(State storage self, address _addr) public requireOpenDraw(self) onlyNonZero(_addr) {
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
if (consolidatedDrawIndex != 0) {
drawSet(self, consolidatedDrawIndex, 0, _addr);
delete self.consolidatedDrawIndices[_addr];
}
if (latestDrawIndex != 0) {
drawSet(self, latestDrawIndex, 0, _addr);
delete self.latestDrawIndices[_addr];
}
}
/**
* @notice Withdraw's from a user's open balance
* @param self The DrawManager state
* @param _addr The user to withdrawn from
* @param _amount The amount to withdraw
*/
function withdrawOpen(State storage self, address _addr, uint256 _amount) public requireOpenDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 openTotal = self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), userId);
require(_amount <= openTotal, "DrawMan/exceeds-open");
uint256 remaining = openTotal.sub(_amount);
drawSet(self, self.openDrawIndex, remaining, _addr);
}
/**
* @notice Withdraw's from a user's committed balance. Fails if the user attempts to take more than available.
* @param self The DrawManager state
* @param _addr The user to withdraw from
* @param _amount The amount to withdraw.
*/
function withdrawCommitted(State storage self, address _addr, uint256 _amount) public requireCommittedDraw(self) onlyNonZero(_addr) {
bytes32 userId = bytes32(uint256(_addr));
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
uint256 consolidatedAmount = 0;
uint256 latestAmount = 0;
uint256 total = 0;
if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) {
latestAmount = self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), userId);
total = total.add(latestAmount);
}
if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) {
consolidatedAmount = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), userId);
total = total.add(consolidatedAmount);
}
// If the total is greater than zero, then consolidated *must* have the committed balance
// However, if the total is zero then the consolidated balance may be the open balance
if (total == 0) {
return;
}
require(_amount <= total, "Pool/exceed");
uint256 remaining = total.sub(_amount);
// if there was a second amount that needs to be updated
if (remaining > consolidatedAmount) {
uint256 secondRemaining = remaining.sub(consolidatedAmount);
drawSet(self, latestDrawIndex, secondRemaining, _addr);
} else if (latestAmount > 0) { // else delete the second amount if it exists
delete self.latestDrawIndices[_addr];
drawSet(self, latestDrawIndex, 0, _addr);
}
// if the consolidated amount needs to be destroyed
if (remaining == 0) {
delete self.consolidatedDrawIndices[_addr];
drawSet(self, consolidatedDrawIndex, 0, _addr);
} else if (remaining < consolidatedAmount) {
drawSet(self, consolidatedDrawIndex, remaining, _addr);
}
}
/**
* @notice Returns the total balance for an address, including committed balances and the open balance.
*/
function balanceOf(State storage drawState, address _addr) public view returns (uint256) {
return committedBalanceOf(drawState, _addr).add(openBalanceOf(drawState, _addr));
}
/**
* @notice Returns the total committed balance for an address.
* @param self The DrawManager state
* @param _addr The address whose committed balance should be returned
* @return The total committed balance
*/
function committedBalanceOf(State storage self, address _addr) public view returns (uint256) {
uint256 balance = 0;
uint256 consolidatedDrawIndex = self.consolidatedDrawIndices[_addr];
uint256 latestDrawIndex = self.latestDrawIndices[_addr];
if (consolidatedDrawIndex != 0 && consolidatedDrawIndex != self.openDrawIndex) {
balance = self.sortitionSumTrees.stakeOf(bytes32(consolidatedDrawIndex), bytes32(uint256(_addr)));
}
if (latestDrawIndex != 0 && latestDrawIndex != self.openDrawIndex) {
balance = balance.add(self.sortitionSumTrees.stakeOf(bytes32(latestDrawIndex), bytes32(uint256(_addr))));
}
return balance;
}
/**
* @notice Returns the open balance for an address
* @param self The DrawManager state
* @param _addr The address whose open balance should be returned
* @return The open balance
*/
function openBalanceOf(State storage self, address _addr) public view returns (uint256) {
if (self.openDrawIndex == 0) {
return 0;
} else {
return self.sortitionSumTrees.stakeOf(bytes32(self.openDrawIndex), bytes32(uint256(_addr)));
}
}
/**
* @notice Returns the open Draw balance for the DrawManager
* @param self The DrawManager state
* @return The open draw total balance
*/
function openSupply(State storage self) public view returns (uint256) {
return self.sortitionSumTrees.total(bytes32(self.openDrawIndex));
}
/**
* @notice Returns the committed balance for the DrawManager
* @param self The DrawManager state
* @return The total committed balance
*/
function committedSupply(State storage self) public view returns (uint256) {
return self.sortitionSumTrees.total(TREE_OF_DRAWS);
}
/**
* @notice Updates the Draw balance for an address.
* @param self The DrawManager state
* @param _drawIndex The Draw index
* @param _amount The new balance
* @param _addr The address whose balance should be updated
*/
function drawSet(State storage self, uint256 _drawIndex, uint256 _amount, address _addr) internal {
bytes32 drawId = bytes32(_drawIndex);
bytes32 userId = bytes32(uint256(_addr));
uint256 oldAmount = self.sortitionSumTrees.stakeOf(drawId, userId);
if (oldAmount != _amount) {
// If the amount has changed
// Update the Draw's balance for that address
self.sortitionSumTrees.set(drawId, _amount, userId);
// if the draw is committed
if (_drawIndex != self.openDrawIndex) {
// Get the new draw total
uint256 newDrawTotal = self.sortitionSumTrees.total(drawId);
// update the draw in the committed tree
self.sortitionSumTrees.set(TREE_OF_DRAWS, newDrawTotal, drawId);
}
}
}
/**
* @notice Selects an address by indexing into the committed tokens using the passed token.
* If there is no committed supply, the zero address is returned.
* @param self The DrawManager state
* @param _token The token index to select
* @return The selected address
*/
function draw(State storage self, uint256 _token) public view returns (address) {
// If there is no one to select, just return the zero address
if (committedSupply(self) == 0) {
return address(0);
}
require(_token < committedSupply(self), "Pool/ineligible");
bytes32 drawIndex = self.sortitionSumTrees.draw(TREE_OF_DRAWS, _token);
uint256 drawSupply = self.sortitionSumTrees.total(drawIndex);
uint256 drawToken = _token % drawSupply;
return address(uint256(self.sortitionSumTrees.draw(drawIndex, drawToken)));
}
/**
* @notice Selects an address using the entropy as an index into the committed tokens
* The entropy is passed into the UniformRandomNumber library to remove modulo bias.
* @param self The DrawManager state
* @param _entropy The random entropy to use
* @return The selected address
*/
function drawWithEntropy(State storage self, bytes32 _entropy) public view returns (address) {
uint256 bound = committedSupply(self);
address selected;
if (bound == 0) {
selected = address(0);
} else {
selected = draw(self, UniformRandomNumber.uniform(uint256(_entropy), bound));
}
return selected;
}
modifier requireOpenDraw(State storage self) {
require(self.openDrawIndex > 0, "Pool/no-open");
_;
}
modifier requireCommittedDraw(State storage self) {
require(self.openDrawIndex > 1, "Pool/no-commit");
_;
}
modifier onlyNonZero(address _addr) {
require(_addr != address(0), "Pool/not-zero");
_;
}
}
/**
* @title FixidityLib
* @author Gadi Guy, Alberto Cuesta Canada
* @notice This library provides fixed point arithmetic with protection against
* overflow.
* All operations are done with int256 and the operands must have been created
* with any of the newFrom* functions, which shift the comma digits() to the
* right and check for limits.
* When using this library be sure of using maxNewFixed() as the upper limit for
* creation of fixed point numbers. Use maxFixedMul(), maxFixedDiv() and
* maxFixedAdd() if you want to be certain that those operations don't
* overflow.
*/
library FixidityLib {
/**
* @notice Number of positions that the comma is shifted to the right.
*/
function digits() public pure returns(uint8) {
return 24;
}
/**
* @notice This is 1 in the fixed point units used in this library.
* @dev Test fixed1() equals 10^digits()
* Hardcoded to 24 digits.
*/
function fixed1() public pure returns(int256) {
return 1000000000000000000000000;
}
/**
* @notice The amount of decimals lost on each multiplication operand.
* @dev Test mulPrecision() equals sqrt(fixed1)
* Hardcoded to 24 digits.
*/
function mulPrecision() public pure returns(int256) {
return 1000000000000;
}
/**
* @notice Maximum value that can be represented in an int256
* @dev Test maxInt256() equals 2^255 -1
*/
function maxInt256() public pure returns(int256) {
return 57896044618658097711785492504343953926634992332820282019728792003956564819967;
}
/**
* @notice Minimum value that can be represented in an int256
* @dev Test minInt256 equals (2^255) * (-1)
*/
function minInt256() public pure returns(int256) {
return -57896044618658097711785492504343953926634992332820282019728792003956564819968;
}
/**
* @notice Maximum value that can be converted to fixed point. Optimize for
* @dev deployment.
* Test maxNewFixed() equals maxInt256() / fixed1()
* Hardcoded to 24 digits.
*/
function maxNewFixed() public pure returns(int256) {
return 57896044618658097711785492504343953926634992332820282;
}
/**
* @notice Minimum value that can be converted to fixed point. Optimize for
* deployment.
* @dev Test minNewFixed() equals -(maxInt256()) / fixed1()
* Hardcoded to 24 digits.
*/
function minNewFixed() public pure returns(int256) {
return -57896044618658097711785492504343953926634992332820282;
}
/**
* @notice Maximum value that can be safely used as an addition operator.
* @dev Test maxFixedAdd() equals maxInt256()-1 / 2
* Test add(maxFixedAdd(),maxFixedAdd()) equals maxFixedAdd() + maxFixedAdd()
* Test add(maxFixedAdd()+1,maxFixedAdd()) throws
* Test add(-maxFixedAdd(),-maxFixedAdd()) equals -maxFixedAdd() - maxFixedAdd()
* Test add(-maxFixedAdd(),-maxFixedAdd()-1) throws
*/
function maxFixedAdd() public pure returns(int256) {
return 28948022309329048855892746252171976963317496166410141009864396001978282409983;
}
/**
* @notice Maximum negative value that can be safely in a subtraction.
* @dev Test maxFixedSub() equals minInt256() / 2
*/
function maxFixedSub() public pure returns(int256) {
return -28948022309329048855892746252171976963317496166410141009864396001978282409984;
}
/**
* @notice Maximum value that can be safely used as a multiplication operator.
* @dev Calculated as sqrt(maxInt256()*fixed1()).
* Be careful with your sqrt() implementation. I couldn't find a calculator
* that would give the exact square root of maxInt256*fixed1 so this number
* is below the real number by no more than 3*10**28. It is safe to use as
* a limit for your multiplications, although powers of two of numbers over
* this value might still work.
* Test multiply(maxFixedMul(),maxFixedMul()) equals maxFixedMul() * maxFixedMul()
* Test multiply(maxFixedMul(),maxFixedMul()+1) throws
* Test multiply(-maxFixedMul(),maxFixedMul()) equals -maxFixedMul() * maxFixedMul()
* Test multiply(-maxFixedMul(),maxFixedMul()+1) throws
* Hardcoded to 24 digits.
*/
function maxFixedMul() public pure returns(int256) {
return 240615969168004498257251713877715648331380787511296;
}
/**
* @notice Maximum value that can be safely used as a dividend.
* @dev divide(maxFixedDiv,newFixedFraction(1,fixed1())) = maxInt256().
* Test maxFixedDiv() equals maxInt256()/fixed1()
* Test divide(maxFixedDiv(),multiply(mulPrecision(),mulPrecision())) = maxFixedDiv()*(10^digits())
* Test divide(maxFixedDiv()+1,multiply(mulPrecision(),mulPrecision())) throws
* Hardcoded to 24 digits.
*/
function maxFixedDiv() public pure returns(int256) {
return 57896044618658097711785492504343953926634992332820282;
}
/**
* @notice Maximum value that can be safely used as a divisor.
* @dev Test maxFixedDivisor() equals fixed1()*fixed1() - Or 10**(digits()*2)
* Test divide(10**(digits()*2 + 1),10**(digits()*2)) = returns 10*fixed1()
* Test divide(10**(digits()*2 + 1),10**(digits()*2 + 1)) = throws
* Hardcoded to 24 digits.
*/
function maxFixedDivisor() public pure returns(int256) {
return 1000000000000000000000000000000000000000000000000;
}
/**
* @notice Converts an int256 to fixed point units, equivalent to multiplying
* by 10^digits().
* @dev Test newFixed(0) returns 0
* Test newFixed(1) returns fixed1()
* Test newFixed(maxNewFixed()) returns maxNewFixed() * fixed1()
* Test newFixed(maxNewFixed()+1) fails
*/
function newFixed(int256 x)
public
pure
returns (int256)
{
require(x <= maxNewFixed());
require(x >= minNewFixed());
return x * fixed1();
}
/**
* @notice Converts an int256 in the fixed point representation of this
* library to a non decimal. All decimal digits will be truncated.
*/
function fromFixed(int256 x)
public
pure
returns (int256)
{
return x / fixed1();
}
/**
* @notice Converts an int256 which is already in some fixed point
* representation to a different fixed precision representation.
* Both the origin and destination precisions must be 38 or less digits.
* Origin values with a precision higher than the destination precision
* will be truncated accordingly.
* @dev
* Test convertFixed(1,0,0) returns 1;
* Test convertFixed(1,1,1) returns 1;
* Test convertFixed(1,1,0) returns 0;
* Test convertFixed(1,0,1) returns 10;
* Test convertFixed(10,1,0) returns 1;
* Test convertFixed(10,0,1) returns 100;
* Test convertFixed(100,1,0) returns 10;
* Test convertFixed(100,0,1) returns 1000;
* Test convertFixed(1000,2,0) returns 10;
* Test convertFixed(1000,0,2) returns 100000;
* Test convertFixed(1000,2,1) returns 100;
* Test convertFixed(1000,1,2) returns 10000;
* Test convertFixed(maxInt256,1,0) returns maxInt256/10;
* Test convertFixed(maxInt256,0,1) throws
* Test convertFixed(maxInt256,38,0) returns maxInt256/(10**38);
* Test convertFixed(1,0,38) returns 10**38;
* Test convertFixed(maxInt256,39,0) throws
* Test convertFixed(1,0,39) throws
*/
function convertFixed(int256 x, uint8 _originDigits, uint8 _destinationDigits)
public
pure
returns (int256)
{
require(_originDigits <= 38 && _destinationDigits <= 38);
uint8 decimalDifference;
if ( _originDigits > _destinationDigits ){
decimalDifference = _originDigits - _destinationDigits;
return x/(uint128(10)**uint128(decimalDifference));
}
else if ( _originDigits < _destinationDigits ){
decimalDifference = _destinationDigits - _originDigits;
// Cast uint8 -> uint128 is safe
// Exponentiation is safe:
// _originDigits and _destinationDigits limited to 38 or less
// decimalDifference = abs(_destinationDigits - _originDigits)
// decimalDifference < 38
// 10**38 < 2**128-1
require(x <= maxInt256()/uint128(10)**uint128(decimalDifference));
require(x >= minInt256()/uint128(10)**uint128(decimalDifference));
return x*(uint128(10)**uint128(decimalDifference));
}
// _originDigits == digits())
return x;
}
/**
* @notice Converts an int256 which is already in some fixed point
* representation to that of this library. The _originDigits parameter is the
* precision of x. Values with a precision higher than FixidityLib.digits()
* will be truncated accordingly.
*/
function newFixed(int256 x, uint8 _originDigits)
public
pure
returns (int256)
{
return convertFixed(x, _originDigits, digits());
}
/**
* @notice Converts an int256 in the fixed point representation of this
* library to a different representation. The _destinationDigits parameter is the
* precision of the output x. Values with a precision below than
* FixidityLib.digits() will be truncated accordingly.
*/
function fromFixed(int256 x, uint8 _destinationDigits)
public
pure
returns (int256)
{
return convertFixed(x, digits(), _destinationDigits);
}
/**
* @notice Converts two int256 representing a fraction to fixed point units,
* equivalent to multiplying dividend and divisor by 10^digits().
* @dev
* Test newFixedFraction(maxFixedDiv()+1,1) fails
* Test newFixedFraction(1,maxFixedDiv()+1) fails
* Test newFixedFraction(1,0) fails
* Test newFixedFraction(0,1) returns 0
* Test newFixedFraction(1,1) returns fixed1()
* Test newFixedFraction(maxFixedDiv(),1) returns maxFixedDiv()*fixed1()
* Test newFixedFraction(1,fixed1()) returns 1
* Test newFixedFraction(1,fixed1()-1) returns 0
*/
function newFixedFraction(
int256 numerator,
int256 denominator
)
public
pure
returns (int256)
{
require(numerator <= maxNewFixed());
require(denominator <= maxNewFixed());
require(denominator != 0);
int256 convertedNumerator = newFixed(numerator);
int256 convertedDenominator = newFixed(denominator);
return divide(convertedNumerator, convertedDenominator);
}
/**
* @notice Returns the integer part of a fixed point number.
* @dev
* Test integer(0) returns 0
* Test integer(fixed1()) returns fixed1()
* Test integer(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1()
* Test integer(-fixed1()) returns -fixed1()
* Test integer(newFixed(-maxNewFixed())) returns -maxNewFixed()*fixed1()
*/
function integer(int256 x) public pure returns (int256) {
return (x / fixed1()) * fixed1(); // Can't overflow
}
/**
* @notice Returns the fractional part of a fixed point number.
* In the case of a negative number the fractional is also negative.
* @dev
* Test fractional(0) returns 0
* Test fractional(fixed1()) returns 0
* Test fractional(fixed1()-1) returns 10^24-1
* Test fractional(-fixed1()) returns 0
* Test fractional(-fixed1()+1) returns -10^24-1
*/
function fractional(int256 x) public pure returns (int256) {
return x - (x / fixed1()) * fixed1(); // Can't overflow
}
/**
* @notice Converts to positive if negative.
* Due to int256 having one more negative number than positive numbers
* abs(minInt256) reverts.
* @dev
* Test abs(0) returns 0
* Test abs(fixed1()) returns -fixed1()
* Test abs(-fixed1()) returns fixed1()
* Test abs(newFixed(maxNewFixed())) returns maxNewFixed()*fixed1()
* Test abs(newFixed(minNewFixed())) returns -minNewFixed()*fixed1()
*/
function abs(int256 x) public pure returns (int256) {
if (x >= 0) {
return x;
} else {
int256 result = -x;
assert (result > 0);
return result;
}
}
/**
* @notice x+y. If any operator is higher than maxFixedAdd() it
* might overflow.
* In solidity maxInt256 + 1 = minInt256 and viceversa.
* @dev
* Test add(maxFixedAdd(),maxFixedAdd()) returns maxInt256()-1
* Test add(maxFixedAdd()+1,maxFixedAdd()+1) fails
* Test add(-maxFixedSub(),-maxFixedSub()) returns minInt256()
* Test add(-maxFixedSub()-1,-maxFixedSub()-1) fails
* Test add(maxInt256(),maxInt256()) fails
* Test add(minInt256(),minInt256()) fails
*/
function add(int256 x, int256 y) public pure returns (int256) {
int256 z = x + y;
if (x > 0 && y > 0) assert(z > x && z > y);
if (x < 0 && y < 0) assert(z < x && z < y);
return z;
}
/**
* @notice x-y. You can use add(x,-y) instead.
* @dev Tests covered by add(x,y)
*/
function subtract(int256 x, int256 y) public pure returns (int256) {
return add(x,-y);
}
/**
* @notice x*y. If any of the operators is higher than maxFixedMul() it
* might overflow.
* @dev
* Test multiply(0,0) returns 0
* Test multiply(maxFixedMul(),0) returns 0
* Test multiply(0,maxFixedMul()) returns 0
* Test multiply(maxFixedMul(),fixed1()) returns maxFixedMul()
* Test multiply(fixed1(),maxFixedMul()) returns maxFixedMul()
* Test all combinations of (2,-2), (2, 2.5), (2, -2.5) and (0.5, -0.5)
* Test multiply(fixed1()/mulPrecision(),fixed1()*mulPrecision())
* Test multiply(maxFixedMul()-1,maxFixedMul()) equals multiply(maxFixedMul(),maxFixedMul()-1)
* Test multiply(maxFixedMul(),maxFixedMul()) returns maxInt256() // Probably not to the last digits
* Test multiply(maxFixedMul()+1,maxFixedMul()) fails
* Test multiply(maxFixedMul(),maxFixedMul()+1) fails
*/
function multiply(int256 x, int256 y) public pure returns (int256) {
if (x == 0 || y == 0) return 0;
if (y == fixed1()) return x;
if (x == fixed1()) return y;
// Separate into integer and fractional parts
// x = x1 + x2, y = y1 + y2
int256 x1 = integer(x) / fixed1();
int256 x2 = fractional(x);
int256 y1 = integer(y) / fixed1();
int256 y2 = fractional(y);
// (x1 + x2) * (y1 + y2) = (x1 * y1) + (x1 * y2) + (x2 * y1) + (x2 * y2)
int256 x1y1 = x1 * y1;
if (x1 != 0) assert(x1y1 / x1 == y1); // Overflow x1y1
// x1y1 needs to be multiplied back by fixed1
// solium-disable-next-line mixedcase
int256 fixed_x1y1 = x1y1 * fixed1();
if (x1y1 != 0) assert(fixed_x1y1 / x1y1 == fixed1()); // Overflow x1y1 * fixed1
x1y1 = fixed_x1y1;
int256 x2y1 = x2 * y1;
if (x2 != 0) assert(x2y1 / x2 == y1); // Overflow x2y1
int256 x1y2 = x1 * y2;
if (x1 != 0) assert(x1y2 / x1 == y2); // Overflow x1y2
x2 = x2 / mulPrecision();
y2 = y2 / mulPrecision();
int256 x2y2 = x2 * y2;
if (x2 != 0) assert(x2y2 / x2 == y2); // Overflow x2y2
// result = fixed1() * x1 * y1 + x1 * y2 + x2 * y1 + x2 * y2 / fixed1();
int256 result = x1y1;
result = add(result, x2y1); // Add checks for overflow
result = add(result, x1y2); // Add checks for overflow
result = add(result, x2y2); // Add checks for overflow
return result;
}
/**
* @notice 1/x
* @dev
* Test reciprocal(0) fails
* Test reciprocal(fixed1()) returns fixed1()
* Test reciprocal(fixed1()*fixed1()) returns 1 // Testing how the fractional is truncated
* Test reciprocal(2*fixed1()*fixed1()) returns 0 // Testing how the fractional is truncated
*/
function reciprocal(int256 x) public pure returns (int256) {
require(x != 0);
return (fixed1()*fixed1()) / x; // Can't overflow
}
/**
* @notice x/y. If the dividend is higher than maxFixedDiv() it
* might overflow. You can use multiply(x,reciprocal(y)) instead.
* There is a loss of precision on division for the lower mulPrecision() decimals.
* @dev
* Test divide(fixed1(),0) fails
* Test divide(maxFixedDiv(),1) = maxFixedDiv()*(10^digits())
* Test divide(maxFixedDiv()+1,1) throws
* Test divide(maxFixedDiv(),maxFixedDiv()) returns fixed1()
*/
function divide(int256 x, int256 y) public pure returns (int256) {
if (y == fixed1()) return x;
require(y != 0);
require(y <= maxFixedDivisor());
return multiply(x, reciprocal(y));
}
}
/**
* @title Blocklock
* @author Brendan Asselstine
* @notice A time lock with a cooldown period. When locked, the contract will remain locked until it is unlocked manually
* or the lock duration expires. After the contract is unlocked, it cannot be locked until the cooldown duration expires.
*/
library Blocklock {
using SafeMath for uint256;
struct State {
uint256 lockedAt;
uint256 unlockedAt;
uint256 lockDuration;
uint256 cooldownDuration;
}
/**
* @notice Sets the duration of the lock. This how long the lock lasts before it expires and automatically unlocks.
* @param self The Blocklock state
* @param lockDuration The duration, in blocks, that the lock should last.
*/
function setLockDuration(State storage self, uint256 lockDuration) public {
require(lockDuration > 0, "Blocklock/lock-min");
self.lockDuration = lockDuration;
}
/**
* @notice Sets the cooldown duration in blocks. This is the number of blocks that must pass before being able to
* lock again. The cooldown duration begins when the lock duration expires, or when it is unlocked manually.
* @param self The Blocklock state
* @param cooldownDuration The duration of the cooldown, in blocks.
*/
function setCooldownDuration(State storage self, uint256 cooldownDuration) public {
require(cooldownDuration > 0, "Blocklock/cool-min");
self.cooldownDuration = cooldownDuration;
}
/**
* @notice Returns whether the state is locked at the given block number.
* @param self The Blocklock state
* @param blockNumber The current block number.
*/
function isLocked(State storage self, uint256 blockNumber) public view returns (bool) {
uint256 endAt = lockEndAt(self);
return (
self.lockedAt != 0 &&
blockNumber >= self.lockedAt &&
blockNumber < endAt
);
}
/**
* @notice Locks the state at the given block number.
* @param self The Blocklock state
* @param blockNumber The block number to use as the lock start time
*/
function lock(State storage self, uint256 blockNumber) public {
require(canLock(self, blockNumber), "Blocklock/no-lock");
self.lockedAt = blockNumber;
}
/**
* @notice Manually unlocks the lock.
* @param self The Blocklock state
* @param blockNumber The block number at which the lock is being unlocked.
*/
function unlock(State storage self, uint256 blockNumber) public {
self.unlockedAt = blockNumber;
}
/**
* @notice Returns whether the Blocklock can be locked at the given block number
* @param self The Blocklock state
* @param blockNumber The block number to check against
* @return True if we can lock at the given block number, false otherwise.
*/
function canLock(State storage self, uint256 blockNumber) public view returns (bool) {
uint256 endAt = lockEndAt(self);
return (
self.lockedAt == 0 ||
blockNumber >= endAt.add(self.cooldownDuration)
);
}
function cooldownEndAt(State storage self) internal view returns (uint256) {
return lockEndAt(self).add(self.cooldownDuration);
}
function lockEndAt(State storage self) internal view returns (uint256) {
uint256 endAt = self.lockedAt.add(self.lockDuration);
// if we unlocked early
if (self.unlockedAt >= self.lockedAt && self.unlockedAt < endAt) {
endAt = self.unlockedAt;
}
return endAt;
}
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
/**
* @dev Interface of the ERC777Token standard as defined in the EIP.
*
* This contract uses the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let
* token holders and recipients react to token movements by using setting implementers
* for the associated interfaces in said registry. See {IERC1820Registry} and
* {ERC1820Implementer}.
*/
interface IERC777 {
/**
* @dev Returns the name of the token.
*/
function name() external view returns (string memory);
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the smallest part of the token that is not divisible. This
* means all token operations (creation, movement and destruction) must have
* amounts that are a multiple of this number.
*
* For most token contracts, this value will equal 1.
*/
function granularity() external view returns (uint256);
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by an account (`owner`).
*/
function balanceOf(address owner) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* If send or receive hooks are registered for the caller and `recipient`,
* the corresponding functions will be called with `data` and empty
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function send(address recipient, uint256 amount, bytes calldata data) external;
/**
* @dev Destroys `amount` tokens from the caller's account, reducing the
* total supply.
*
* If a send hook is registered for the caller, the corresponding function
* will be called with `data` and empty `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - the caller must have at least `amount` tokens.
*/
function burn(uint256 amount, bytes calldata data) external;
/**
* @dev Returns true if an account is an operator of `tokenHolder`.
* Operators can send and burn tokens on behalf of their owners. All
* accounts are their own operator.
*
* See {operatorSend} and {operatorBurn}.
*/
function isOperatorFor(address operator, address tokenHolder) external view returns (bool);
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor}.
*
* Emits an {AuthorizedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function authorizeOperator(address operator) external;
/**
* @dev Make an account an operator of the caller.
*
* See {isOperatorFor} and {defaultOperators}.
*
* Emits a {RevokedOperator} event.
*
* Requirements
*
* - `operator` cannot be calling address.
*/
function revokeOperator(address operator) external;
/**
* @dev Returns the list of default operators. These accounts are operators
* for all token holders, even if {authorizeOperator} was never called on
* them.
*
* This list is immutable, but individual holders may revoke these via
* {revokeOperator}, in which case {isOperatorFor} will return false.
*/
function defaultOperators() external view returns (address[] memory);
/**
* @dev Moves `amount` tokens from `sender` to `recipient`. The caller must
* be an operator of `sender`.
*
* If send or receive hooks are registered for `sender` and `recipient`,
* the corresponding functions will be called with `data` and
* `operatorData`. See {IERC777Sender} and {IERC777Recipient}.
*
* Emits a {Sent} event.
*
* Requirements
*
* - `sender` cannot be the zero address.
* - `sender` must have at least `amount` tokens.
* - the caller must be an operator for `sender`.
* - `recipient` cannot be the zero address.
* - if `recipient` is a contract, it must implement the {IERC777Recipient}
* interface.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
/**
* @dev Destoys `amount` tokens from `account`, reducing the total supply.
* The caller must be an operator of `account`.
*
* If a send hook is registered for `account`, the corresponding function
* will be called with `data` and `operatorData`. See {IERC777Sender}.
*
* Emits a {Burned} event.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
* - the caller must be an operator for `account`.
*/
function operatorBurn(
address account,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
) external;
event Sent(
address indexed operator,
address indexed from,
address indexed to,
uint256 amount,
bytes data,
bytes operatorData
);
event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData);
event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
event AuthorizedOperator(address indexed operator, address indexed tokenHolder);
event RevokedOperator(address indexed operator, address indexed tokenHolder);
}
/**
* @dev Interface of the ERC777TokensSender standard as defined in the EIP.
*
* {IERC777} Token holders can be notified of operations performed on their
* tokens by having a contract implement this interface (contract holders can be
* their own implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Sender {
/**
* @dev Called by an {IERC777} token contract whenever a registered holder's
* (`from`) tokens are about to be moved or destroyed. The type of operation
* is conveyed by `to` being the zero address or not.
*
* This call occurs _before_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the pre-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* This test is non-exhaustive, and there may be false-negatives: during the
* execution of a contract's constructor, its address will be reported as
* not containing a contract.
*
* 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.
*/
function isContract(address account) internal view returns (bool) {
// This method relies in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
// 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 != 0x0 && codehash != accountHash);
}
/**
* @dev Converts an `address` into `address payable`. Note that this is
* simply a type cast: the actual underlying value is not changed.
*
* _Available since v2.4.0._
*/
function toPayable(address account) internal pure returns (address payable) {
return address(uint160(account));
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*
* _Available since v2.4.0._
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-call-value
(bool success, ) = recipient.call.value(amount)("");
require(success, "Address: unable to send value, recipient may have reverted");
}
}
/**
* @dev Implementation of the {IERC777} interface.
*
* Largely taken from the OpenZeppelin ERC777 contract.
*
* Support for ERC20 is included in this contract, as specified by the EIP: both
* the ERC777 and ERC20 interfaces can be safely used when interacting with it.
* Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token
* movements.
*
* Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there
* are no special restrictions in the amount of tokens that created, moved, or
* destroyed. This makes integration with ERC20 applications seamless.
*
* It is important to note that no Mint events are emitted. Tokens are minted in batches
* by a state change in a tree data structure, so emitting a Mint event for each user
* is not possible.
*
*/
contract PoolToken is Initializable, IERC20, IERC777 {
using SafeMath for uint256;
using Address for address;
/**
* Event emitted when a user or operator redeems tokens
*/
event Redeemed(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData);
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("ERC777TokensSender")
bytes32 constant internal TOKENS_SENDER_INTERFACE_HASH =
0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895;
// keccak256("ERC777TokensRecipient")
bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
// keccak256("ERC777Token")
bytes32 constant internal TOKENS_INTERFACE_HASH =
0xac7fbab5f54a3ca8194167523c6753bfeb96a445279294b6125b68cce2177054;
// keccak256("ERC20Token")
bytes32 constant internal ERC20_TOKENS_INTERFACE_HASH =
0xaea199e31a596269b42cdafd93407f14436db6e4cad65417994c2eb37381e05a;
string internal _name;
string internal _symbol;
// This isn't ever read from - it's only used to respond to the defaultOperators query.
address[] internal _defaultOperatorsArray;
// Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators).
mapping(address => bool) internal _defaultOperators;
// For each account, a mapping of its operators and revoked default operators.
mapping(address => mapping(address => bool)) internal _operators;
mapping(address => mapping(address => bool)) internal _revokedDefaultOperators;
// ERC20-allowances
mapping (address => mapping (address => uint256)) internal _allowances;
// The Pool that is bound to this token
BasePool internal _pool;
/**
* @notice Initializes the PoolToken.
* @param name The name of the token
* @param symbol The token symbol
* @param defaultOperators The default operators who are allowed to move tokens
*/
function init (
string memory name,
string memory symbol,
address[] memory defaultOperators,
BasePool pool
) public initializer {
require(bytes(name).length != 0, "PoolToken/name");
require(bytes(symbol).length != 0, "PoolToken/symbol");
require(address(pool) != address(0), "PoolToken/pool-zero");
_name = name;
_symbol = symbol;
_pool = pool;
_defaultOperatorsArray = defaultOperators;
for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) {
_defaultOperators[_defaultOperatorsArray[i]] = true;
}
// register interfaces
ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_INTERFACE_HASH, address(this));
ERC1820_REGISTRY.setInterfaceImplementer(address(this), ERC20_TOKENS_INTERFACE_HASH, address(this));
}
/**
* @notice Returns the address of the Pool contract
* @return The address of the pool contract
*/
function pool() public view returns (BasePool) {
return _pool;
}
/**
* @notice Calls the ERC777 transfer hook, and emits Redeemed and Transfer. Can only be called by the Pool contract.
* @param from The address from which to redeem tokens
* @param amount The amount of tokens to redeem
*/
function poolRedeem(address from, uint256 amount) external onlyPool {
_callTokensToSend(from, from, address(0), amount, '', '');
emit Redeemed(from, from, amount, '', '');
emit Transfer(from, address(0), amount);
}
/**
* @dev See {IERC777-name}.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev See {IERC777-symbol}.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev See {ERC20Detailed-decimals}.
*
* Always returns 18, as per the
* [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility).
*/
function decimals() public view returns (uint8) {
return 18;
}
/**
* @dev See {IERC777-granularity}.
*
* This implementation always returns `1`.
*/
function granularity() public view returns (uint256) {
return 1;
}
/**
* @dev See {IERC777-totalSupply}.
*/
function totalSupply() public view returns (uint256) {
return _pool.committedSupply();
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address _addr) external view returns (uint256) {
return _pool.committedBalanceOf(_addr);
}
/**
* @dev See {IERC777-send}.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function send(address recipient, uint256 amount, bytes calldata data) external {
_send(msg.sender, msg.sender, recipient, amount, data, "");
}
/**
* @dev See {IERC20-transfer}.
*
* Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient}
* interface if it is a contract.
*
* Also emits a {Sent} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool) {
require(recipient != address(0), "PoolToken/transfer-zero");
address from = msg.sender;
_callTokensToSend(from, from, recipient, amount, "", "");
_move(from, from, recipient, amount, "", "");
_callTokensReceived(from, from, recipient, amount, "", "", false);
return true;
}
/**
* @dev Allows a user to withdraw their tokens as the underlying asset.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function redeem(uint256 amount, bytes calldata data) external {
_redeem(msg.sender, msg.sender, amount, data, "");
}
/**
* @dev See {IERC777-burn}. Not currently implemented.
*
* Also emits a {Transfer} event for ERC20 compatibility.
*/
function burn(uint256, bytes calldata) external {
revert("PoolToken/no-support");
}
/**
* @dev See {IERC777-isOperatorFor}.
*/
function isOperatorFor(
address operator,
address tokenHolder
) public view returns (bool) {
return operator == tokenHolder ||
(_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) ||
_operators[tokenHolder][operator];
}
/**
* @dev See {IERC777-authorizeOperator}.
*/
function authorizeOperator(address operator) external {
require(msg.sender != operator, "PoolToken/auth-self");
if (_defaultOperators[operator]) {
delete _revokedDefaultOperators[msg.sender][operator];
} else {
_operators[msg.sender][operator] = true;
}
emit AuthorizedOperator(operator, msg.sender);
}
/**
* @dev See {IERC777-revokeOperator}.
*/
function revokeOperator(address operator) external {
require(operator != msg.sender, "PoolToken/revoke-self");
if (_defaultOperators[operator]) {
_revokedDefaultOperators[msg.sender][operator] = true;
} else {
delete _operators[msg.sender][operator];
}
emit RevokedOperator(operator, msg.sender);
}
/**
* @dev See {IERC777-defaultOperators}.
*/
function defaultOperators() public view returns (address[] memory) {
return _defaultOperatorsArray;
}
/**
* @dev See {IERC777-operatorSend}.
*
* Emits {Sent} and {Transfer} events.
*/
function operatorSend(
address sender,
address recipient,
uint256 amount,
bytes calldata data,
bytes calldata operatorData
)
external
{
require(isOperatorFor(msg.sender, sender), "PoolToken/not-operator");
_send(msg.sender, sender, recipient, amount, data, operatorData);
}
/**
* @dev See {IERC777-operatorBurn}.
*
* Currently not supported
*/
function operatorBurn(address, uint256, bytes calldata, bytes calldata) external {
revert("PoolToken/no-support");
}
/**
* @dev Allows an operator to redeem tokens for the underlying asset on behalf of a user.
*
* Emits {Redeemed} and {Transfer} events.
*/
function operatorRedeem(address account, uint256 amount, bytes calldata data, bytes calldata operatorData) external {
require(isOperatorFor(msg.sender, account), "PoolToken/not-operator");
_redeem(msg.sender, account, amount, data, operatorData);
}
/**
* @dev See {IERC20-allowance}.
*
* Note that operator and allowance concepts are orthogonal: operators may
* not have allowance, and accounts with allowance may not be operators
* themselves.
*/
function allowance(address holder, address spender) public view returns (uint256) {
return _allowances[holder][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Note that accounts cannot have allowance issued by their operators.
*/
function approve(address spender, uint256 value) external returns (bool) {
address holder = msg.sender;
_approve(holder, spender, value);
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, "PoolToken/negative"));
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Note that operator and allowance concepts are orthogonal: operators cannot
* call `transferFrom` (unless they have allowance), and accounts with
* allowance cannot call `operatorSend` (unless they are operators).
*
* Emits {Sent}, {Transfer} and {Approval} events.
*/
function transferFrom(address holder, address recipient, uint256 amount) external returns (bool) {
require(recipient != address(0), "PoolToken/to-zero");
require(holder != address(0), "PoolToken/from-zero");
address spender = msg.sender;
_callTokensToSend(spender, holder, recipient, amount, "", "");
_move(spender, holder, recipient, amount, "", "");
_approve(holder, spender, _allowances[holder][spender].sub(amount, "PoolToken/exceed-allow"));
_callTokensReceived(spender, holder, recipient, amount, "", "", false);
return true;
}
/**
* Called by the associated Pool to emit `Mint` events.
* @param amount The amount that was minted
*/
function poolMint(uint256 amount) external onlyPool {
_mintEvents(address(_pool), address(_pool), amount, '', '');
}
/**
* Emits {Minted} and {IERC20-Transfer} events.
*/
function _mintEvents(
address operator,
address account,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal
{
emit Minted(operator, account, amount, userData, operatorData);
emit Transfer(address(0), account, amount);
}
/**
* @dev Send tokens
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _send(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
require(from != address(0), "PoolToken/from-zero");
require(to != address(0), "PoolToken/to-zero");
_callTokensToSend(operator, from, to, amount, userData, operatorData);
_move(operator, from, to, amount, userData, operatorData);
_callTokensReceived(operator, from, to, amount, userData, operatorData, false);
}
/**
* @dev Redeems tokens for the underlying asset.
* @param operator address operator requesting the operation
* @param from address token holder address
* @param amount uint256 amount of tokens to redeem
* @param data bytes extra information provided by the token holder
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _redeem(
address operator,
address from,
uint256 amount,
bytes memory data,
bytes memory operatorData
)
private
{
require(from != address(0), "PoolToken/from-zero");
_callTokensToSend(operator, from, address(0), amount, data, operatorData);
_pool.withdrawCommittedDepositFrom(from, amount);
emit Redeemed(operator, from, amount, data, operatorData);
emit Transfer(from, address(0), amount);
}
/**
* @notice Moves tokens from one user to another. Emits Sent and Transfer events.
*/
function _move(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
private
{
_pool.moveCommitted(from, to, amount);
emit Sent(operator, from, to, amount, userData, operatorData);
emit Transfer(from, to, amount);
}
/**
* Approves of a token spend by a spender for a holder.
* @param holder The address from which the tokens are spent
* @param spender The address that is spending the tokens
* @param value The amount of tokens to spend
*/
function _approve(address holder, address spender, uint256 value) private {
require(spender != address(0), "PoolToken/from-zero");
_allowances[holder][spender] = value;
emit Approval(holder, spender, value);
}
/**
* @dev Call from.tokensToSend() if the interface is registered
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
*/
function _callTokensToSend(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData
)
internal notLocked
{
address implementer = ERC1820_REGISTRY.getInterfaceImplementer(from, TOKENS_SENDER_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData);
}
}
/**
* @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but
* tokensReceived() was not registered for the recipient
* @param operator address operator requesting the transfer
* @param from address token holder address
* @param to address recipient address
* @param amount uint256 amount of tokens to transfer
* @param userData bytes extra information provided by the token holder (if any)
* @param operatorData bytes extra information provided by the operator (if any)
* @param requireReceptionAck whether to require that, if the recipient is a contract, it has registered a IERC777Recipient
*/
function _callTokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes memory userData,
bytes memory operatorData,
bool requireReceptionAck
)
private
{
address implementer = ERC1820_REGISTRY.getInterfaceImplementer(to, TOKENS_RECIPIENT_INTERFACE_HASH);
if (implementer != address(0)) {
IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData);
} else if (requireReceptionAck) {
require(!to.isContract(), "PoolToken/no-recip-inter");
}
}
/**
* @notice Requires the sender to be the pool contract
*/
modifier onlyPool() {
require(msg.sender == address(_pool), "PoolToken/only-pool");
_;
}
/**
* @notice Requires the contract to be unlocked
*/
modifier notLocked() {
require(!_pool.isLocked(), "PoolToken/is-locked");
_;
}
}
/**
* @title The Pool contract
* @author Brendan Asselstine
* @notice This contract allows users to pool deposits into Compound and win the accrued interest in periodic draws.
* Funds are immediately deposited and withdrawn from the Compound cToken contract.
* Draws go through three stages: open, committed and rewarded in that order.
* Only one draw is ever in the open stage. Users deposits are always added to the open draw. Funds in the open Draw are that user's open balance.
* When a Draw is committed, the funds in it are moved to a user's committed total and the total committed balance of all users is updated.
* When a Draw is rewarded, the gross winnings are the accrued interest since the last reward (if any). A winner is selected with their chances being
* proportional to their committed balance vs the total committed balance of all users.
*
*
* With the above in mind, there is always an open draw and possibly a committed draw. The progression is:
*
* Step 1: Draw 1 Open
* Step 2: Draw 2 Open | Draw 1 Committed
* Step 3: Draw 3 Open | Draw 2 Committed | Draw 1 Rewarded
* Step 4: Draw 4 Open | Draw 3 Committed | Draw 2 Rewarded
* Step 5: Draw 5 Open | Draw 4 Committed | Draw 3 Rewarded
* Step X: ...
*/
contract BasePool is Initializable, ReentrancyGuard {
using DrawManager for DrawManager.State;
using SafeMath for uint256;
using Roles for Roles.Role;
using Blocklock for Blocklock.State;
bytes32 internal constant ROLLED_OVER_ENTROPY_MAGIC_NUMBER = bytes32(uint256(1));
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// We inline the result of the following hashes because Solidity doesn't resolve them at compile time.
// See https://github.com/ethereum/solidity/issues/4024.
// keccak256("PoolTogetherRewardListener")
bytes32 constant internal REWARD_LISTENER_INTERFACE_HASH =
0x68f03b0b1a978ee238a70b362091d993343460bc1a2830ab3f708936d9f564a4;
/**
* Emitted when a user deposits into the Pool.
* @param sender The purchaser of the tickets
* @param amount The size of the deposit
*/
event Deposited(address indexed sender, uint256 amount);
/**
* Emitted when a user deposits into the Pool and the deposit is immediately committed
* @param sender The purchaser of the tickets
* @param amount The size of the deposit
*/
event DepositedAndCommitted(address indexed sender, uint256 amount);
/**
* Emitted when Sponsors have deposited into the Pool
* @param sender The purchaser of the tickets
* @param amount The size of the deposit
*/
event SponsorshipDeposited(address indexed sender, uint256 amount);
/**
* Emitted when an admin has been added to the Pool.
* @param admin The admin that was added
*/
event AdminAdded(address indexed admin);
/**
* Emitted when an admin has been removed from the Pool.
* @param admin The admin that was removed
*/
event AdminRemoved(address indexed admin);
/**
* Emitted when a user withdraws from the pool.
* @param sender The user that is withdrawing from the pool
* @param amount The amount that the user withdrew
*/
event Withdrawn(address indexed sender, uint256 amount);
/**
* Emitted when a user withdraws their sponsorship and fees from the pool.
* @param sender The user that is withdrawing
* @param amount The amount they are withdrawing
*/
event SponsorshipAndFeesWithdrawn(address indexed sender, uint256 amount);
/**
* Emitted when a user withdraws from their open deposit.
* @param sender The user that is withdrawing
* @param amount The amount they are withdrawing
*/
event OpenDepositWithdrawn(address indexed sender, uint256 amount);
/**
* Emitted when a user withdraws from their committed deposit.
* @param sender The user that is withdrawing
* @param amount The amount they are withdrawing
*/
event CommittedDepositWithdrawn(address indexed sender, uint256 amount);
/**
* Emitted when an address collects a fee
* @param sender The address collecting the fee
* @param amount The fee amount
* @param drawId The draw from which the fee was awarded
*/
event FeeCollected(address indexed sender, uint256 amount, uint256 drawId);
/**
* Emitted when a new draw is opened for deposit.
* @param drawId The draw id
* @param feeBeneficiary The fee beneficiary for this draw
* @param secretHash The committed secret hash
* @param feeFraction The fee fraction of the winnings to be given to the beneficiary
*/
event Opened(
uint256 indexed drawId,
address indexed feeBeneficiary,
bytes32 secretHash,
uint256 feeFraction
);
/**
* Emitted when a draw is committed.
* @param drawId The draw id
*/
event Committed(
uint256 indexed drawId
);
/**
* Emitted when a draw is rewarded.
* @param drawId The draw id
* @param winner The address of the winner
* @param entropy The entropy used to select the winner
* @param winnings The net winnings given to the winner
* @param fee The fee being given to the draw beneficiary
*/
event Rewarded(
uint256 indexed drawId,
address indexed winner,
bytes32 entropy,
uint256 winnings,
uint256 fee
);
/**
* Emitted when a RewardListener call fails
* @param drawId The draw id
* @param winner The address that one the draw
* @param impl The implementation address of the RewardListener
*/
event RewardListenerFailed(
uint256 indexed drawId,
address indexed winner,
address indexed impl
);
/**
* Emitted when the fee fraction is changed. Takes effect on the next draw.
* @param feeFraction The next fee fraction encoded as a fixed point 18 decimal
*/
event NextFeeFractionChanged(uint256 feeFraction);
/**
* Emitted when the next fee beneficiary changes. Takes effect on the next draw.
* @param feeBeneficiary The next fee beneficiary
*/
event NextFeeBeneficiaryChanged(address indexed feeBeneficiary);
/**
* Emitted when an admin pauses the contract
*/
event DepositsPaused(address indexed sender);
/**
* Emitted when an admin unpauses the contract
*/
event DepositsUnpaused(address indexed sender);
/**
* Emitted when the draw is rolled over in the event that the secret is forgotten.
*/
event RolledOver(uint256 indexed drawId);
struct Draw {
uint256 feeFraction; //fixed point 18
address feeBeneficiary;
uint256 openedBlock;
bytes32 secretHash;
bytes32 entropy;
address winner;
uint256 netWinnings;
uint256 fee;
}
/**
* The Compound cToken that this Pool is bound to.
*/
ICErc20 public cToken;
/**
* The fee beneficiary to use for subsequent Draws.
*/
address public nextFeeBeneficiary;
/**
* The fee fraction to use for subsequent Draws.
*/
uint256 public nextFeeFraction;
/**
* The total of all balances
*/
uint256 public accountedBalance;
/**
* The total deposits and winnings for each user.
*/
mapping (address => uint256) internal balances;
/**
* A mapping of draw ids to Draw structures
*/
mapping(uint256 => Draw) internal draws;
/**
* A structure that is used to manage the user's odds of winning.
*/
DrawManager.State internal drawState;
/**
* A structure containing the administrators
*/
Roles.Role internal admins;
/**
* Whether the contract is paused
*/
bool public paused;
Blocklock.State internal blocklock;
PoolToken public poolToken;
/**
* @notice Initializes a new Pool contract.
* @param _owner The owner of the Pool. They are able to change settings and are set as the owner of new lotteries.
* @param _cToken The Compound Finance MoneyMarket contract to supply and withdraw tokens.
* @param _feeFraction The fraction of the gross winnings that should be transferred to the owner as the fee. Is a fixed point 18 number.
* @param _feeBeneficiary The address that will receive the fee fraction
*/
function init (
address _owner,
address _cToken,
uint256 _feeFraction,
address _feeBeneficiary,
uint256 _lockDuration,
uint256 _cooldownDuration
) public initializer {
require(_owner != address(0), "Pool/owner-zero");
require(_cToken != address(0), "Pool/ctoken-zero");
cToken = ICErc20(_cToken);
_addAdmin(_owner);
_setNextFeeFraction(_feeFraction);
_setNextFeeBeneficiary(_feeBeneficiary);
initBlocklock(_lockDuration, _cooldownDuration);
}
function setPoolToken(PoolToken _poolToken) external onlyAdmin {
require(address(poolToken) == address(0), "Pool/token-was-set");
require(address(_poolToken.pool()) == address(this), "Pool/token-mismatch");
poolToken = _poolToken;
}
function initBlocklock(uint256 _lockDuration, uint256 _cooldownDuration) internal {
blocklock.setLockDuration(_lockDuration);
blocklock.setCooldownDuration(_cooldownDuration);
}
/**
* @notice Opens a new Draw.
* @param _secretHash The secret hash to commit to the Draw.
*/
function open(bytes32 _secretHash) internal {
drawState.openNextDraw();
draws[drawState.openDrawIndex] = Draw(
nextFeeFraction,
nextFeeBeneficiary,
block.number,
_secretHash,
bytes32(0),
address(0),
uint256(0),
uint256(0)
);
emit Opened(
drawState.openDrawIndex,
nextFeeBeneficiary,
_secretHash,
nextFeeFraction
);
}
/**
* @notice Emits the Committed event for the current open draw.
*/
function emitCommitted() internal {
uint256 drawId = currentOpenDrawId();
emit Committed(drawId);
if (address(poolToken) != address(0)) {
poolToken.poolMint(openSupply());
}
}
/**
* @notice Commits the current open draw, if any, and opens the next draw using the passed hash. Really this function is only called twice:
* the first after Pool contract creation and the second immediately after.
* Can only be called by an admin.
* May fire the Committed event, and always fires the Open event.
* @param nextSecretHash The secret hash to use to open a new Draw
*/
function openNextDraw(bytes32 nextSecretHash) public onlyAdmin {
if (currentCommittedDrawId() > 0) {
require(currentCommittedDrawHasBeenRewarded(), "Pool/not-reward");
}
if (currentOpenDrawId() != 0) {
emitCommitted();
}
open(nextSecretHash);
}
/**
* @notice Ignores the current draw, and opens the next draw.
* @dev This function will be removed once the winner selection has been decentralized.
* @param nextSecretHash The hash to commit for the next draw
*/
function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public onlyAdmin {
rollover();
openNextDraw(nextSecretHash);
}
/**
* @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash.
* Can only be called by an admin.
* Fires the Rewarded event, the Committed event, and the Open event.
* @param nextSecretHash The secret hash to use to open a new Draw
* @param lastSecret The secret to reveal to reward the current committed Draw.
* @param _salt The salt that was used to conceal the secret
*/
function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public onlyAdmin {
reward(lastSecret, _salt);
openNextDraw(nextSecretHash);
}
/**
* @notice Rewards the winner for the current committed Draw using the passed secret.
* The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance.
* A winner is calculated using the revealed secret.
* If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings.
* The draw beneficiary's balance is updated with the fee.
* The accounted balance is updated to include the fee and, if there was a winner, the net winnings.
* Fires the Rewarded event.
* @param _secret The secret to reveal for the current committed Draw
* @param _salt The salt that was used to conceal the secret
*/
function reward(bytes32 _secret, bytes32 _salt) public onlyAdmin onlyLocked requireCommittedNoReward nonReentrant {
// require that there is a committed draw
// require that the committed draw has not been rewarded
uint256 drawId = currentCommittedDrawId();
Draw storage draw = draws[drawId];
require(draw.secretHash == keccak256(abi.encodePacked(_secret, _salt)), "Pool/bad-secret");
// derive entropy from the revealed secret
bytes32 entropy = keccak256(abi.encodePacked(_secret));
_reward(drawId, draw, entropy);
}
function _reward(uint256 drawId, Draw storage draw, bytes32 entropy) internal {
blocklock.unlock(block.number);
// Select the winner using the hash as entropy
address winningAddress = calculateWinner(entropy);
// Calculate the gross winnings
uint256 underlyingBalance = balance();
uint256 grossWinnings;
// It's possible when the APR is zero that the underlying balance will be slightly lower than the accountedBalance
// due to rounding errors in the Compound contract.
if (underlyingBalance > accountedBalance) {
grossWinnings = capWinnings(underlyingBalance.sub(accountedBalance));
}
// Calculate the beneficiary fee
uint256 fee = calculateFee(draw.feeFraction, grossWinnings);
// Update balance of the beneficiary
balances[draw.feeBeneficiary] = balances[draw.feeBeneficiary].add(fee);
// Calculate the net winnings
uint256 netWinnings = grossWinnings.sub(fee);
draw.winner = winningAddress;
draw.netWinnings = netWinnings;
draw.fee = fee;
draw.entropy = entropy;
// If there is a winner who is to receive non-zero winnings
if (winningAddress != address(0) && netWinnings != 0) {
// Updated the accounted total
accountedBalance = underlyingBalance;
// Update balance of the winner
balances[winningAddress] = balances[winningAddress].add(netWinnings);
// Enter their winnings into the open draw
drawState.deposit(winningAddress, netWinnings);
callRewarded(winningAddress, netWinnings, drawId);
} else {
// Only account for the fee
accountedBalance = accountedBalance.add(fee);
}
emit Rewarded(
drawId,
winningAddress,
entropy,
netWinnings,
fee
);
emit FeeCollected(draw.feeBeneficiary, fee, drawId);
}
/**
* @notice Calls the reward listener for the winner, if a listener exists.
* @dev Checks for a listener using the ERC1820 registry. The listener is given a gas stipend of 200,000 to run the function.
* The number 200,000 was selected because it's safely above the gas requirements for PoolTogether [Pod](https://github.com/pooltogether/pods) contract.
*
* @param winner The winner. If they have a listener registered in the ERC1820 registry it will be called.
* @param netWinnings The amount that was won.
* @param drawId The draw id that was won.
*/
function callRewarded(address winner, uint256 netWinnings, uint256 drawId) internal {
address impl = ERC1820_REGISTRY.getInterfaceImplementer(winner, REWARD_LISTENER_INTERFACE_HASH);
if (impl != address(0)) {
(bool success,) = impl.call.gas(200000)(abi.encodeWithSignature("rewarded(address,uint256,uint256)", winner, netWinnings, drawId));
if (!success) {
emit RewardListenerFailed(drawId, winner, impl);
}
}
}
/**
* @notice A function that skips the reward for the committed draw id.
* @dev This function will be removed once the entropy is decentralized.
*/
function rollover() public onlyAdmin requireCommittedNoReward {
uint256 drawId = currentCommittedDrawId();
Draw storage draw = draws[drawId];
draw.entropy = ROLLED_OVER_ENTROPY_MAGIC_NUMBER;
emit RolledOver(
drawId
);
emit Rewarded(
drawId,
address(0),
ROLLED_OVER_ENTROPY_MAGIC_NUMBER,
0,
0
);
}
/**
* @notice Ensures that the winnings don't overflow. Note that we can make this integer max, because the fee
* is always less than zero (meaning the FixidityLib.multiply will always make the number smaller)
*/
function capWinnings(uint256 _grossWinnings) internal pure returns (uint256) {
uint256 max = uint256(FixidityLib.maxNewFixed());
if (_grossWinnings > max) {
return max;
}
return _grossWinnings;
}
/**
* @notice Calculate the beneficiary fee using the passed fee fraction and gross winnings.
* @param _feeFraction The fee fraction, between 0 and 1, represented as a 18 point fixed number.
* @param _grossWinnings The gross winnings to take a fraction of.
*/
function calculateFee(uint256 _feeFraction, uint256 _grossWinnings) internal pure returns (uint256) {
int256 grossWinningsFixed = FixidityLib.newFixed(int256(_grossWinnings));
// _feeFraction *must* be less than 1 ether, so it will never overflow
int256 feeFixed = FixidityLib.multiply(grossWinningsFixed, FixidityLib.newFixed(int256(_feeFraction), uint8(18)));
return uint256(FixidityLib.fromFixed(feeFixed));
}
/**
* @notice Allows a user to deposit a sponsorship amount. The deposit is transferred into the cToken.
* Sponsorships allow a user to contribute to the pool without becoming eligible to win. They can withdraw their sponsorship at any time.
* The deposit will immediately be added to Compound and the interest will contribute to the next draw.
* @param _amount The amount of the token underlying the cToken to deposit.
*/
function depositSponsorship(uint256 _amount) public unlessDepositsPaused nonReentrant {
// Transfer the tokens into this contract
require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail");
// Deposit the sponsorship amount
_depositSponsorshipFrom(msg.sender, _amount);
}
/**
* @notice Deposits the token balance for this contract as a sponsorship.
* If people erroneously transfer tokens to this contract, this function will allow us to recoup those tokens as sponsorship.
*/
function transferBalanceToSponsorship() public unlessDepositsPaused {
// Deposit the sponsorship amount
_depositSponsorshipFrom(address(this), token().balanceOf(address(this)));
}
/**
* @notice Deposits into the pool under the current open Draw. The deposit is transferred into the cToken.
* Once the open draw is committed, the deposit will be added to the user's total committed balance and increase their chances of winning
* proportional to the total committed balance of all users.
* @param _amount The amount of the token underlying the cToken to deposit.
*/
function depositPool(uint256 _amount) public requireOpenDraw unlessDepositsPaused nonReentrant notLocked {
// Transfer the tokens into this contract
require(token().transferFrom(msg.sender, address(this), _amount), "Pool/t-fail");
// Deposit the funds
_depositPoolFrom(msg.sender, _amount);
}
/**
* @notice Deposits sponsorship for a user
* @param _spender The user who is sponsoring
* @param _amount The amount they are sponsoring
*/
function _depositSponsorshipFrom(address _spender, uint256 _amount) internal {
// Deposit the funds
_depositFrom(_spender, _amount);
emit SponsorshipDeposited(_spender, _amount);
}
/**
* @notice Deposits into the pool for a user. The deposit will be open until the next draw is committed.
* @param _spender The user who is depositing
* @param _amount The amount the user is depositing
*/
function _depositPoolFrom(address _spender, uint256 _amount) internal {
// Update the user's eligibility
drawState.deposit(_spender, _amount);
_depositFrom(_spender, _amount);
emit Deposited(_spender, _amount);
}
/**
* @notice Deposits into the pool for a user. The deposit is made part of the currently committed draw
* @param _spender The user who is depositing
* @param _amount The amount to deposit
*/
function _depositPoolFromCommitted(address _spender, uint256 _amount) internal notLocked {
// Update the user's eligibility
drawState.depositCommitted(_spender, _amount);
_depositFrom(_spender, _amount);
emit DepositedAndCommitted(_spender, _amount);
}
/**
* @notice Deposits into the pool for a user. Updates their balance and transfers their tokens into this contract.
* @param _spender The user who is depositing
* @param _amount The amount they are depositing
*/
function _depositFrom(address _spender, uint256 _amount) internal {
// Update the user's balance
balances[_spender] = balances[_spender].add(_amount);
// Update the total of this contract
accountedBalance = accountedBalance.add(_amount);
// Deposit into Compound
require(token().approve(address(cToken), _amount), "Pool/approve");
require(cToken.mint(_amount) == 0, "Pool/supply");
}
/**
* Withdraws the given amount from the user's deposits. It first withdraws from their sponsorship,
* then their open deposits, then their committed deposits.
*
* @param amount The amount to withdraw.
*/
function withdraw(uint256 amount) public nonReentrant notLocked {
uint256 remainingAmount = amount;
// first sponsorship
uint256 sponsorshipAndFeesBalance = sponsorshipAndFeeBalanceOf(msg.sender);
if (sponsorshipAndFeesBalance < remainingAmount) {
withdrawSponsorshipAndFee(sponsorshipAndFeesBalance);
remainingAmount = remainingAmount.sub(sponsorshipAndFeesBalance);
} else {
withdrawSponsorshipAndFee(remainingAmount);
return;
}
// now pending
uint256 pendingBalance = drawState.openBalanceOf(msg.sender);
if (pendingBalance < remainingAmount) {
_withdrawOpenDeposit(msg.sender, pendingBalance);
remainingAmount = remainingAmount.sub(pendingBalance);
} else {
_withdrawOpenDeposit(msg.sender, remainingAmount);
return;
}
// now committed. remainingAmount should not be greater than committed balance.
_withdrawCommittedDeposit(msg.sender, remainingAmount);
}
/**
* @notice Withdraw the sender's entire balance back to them.
*/
function withdraw() public nonReentrant notLocked {
uint256 committedBalance = drawState.committedBalanceOf(msg.sender);
uint256 balance = balances[msg.sender];
// Update their chances of winning
drawState.withdraw(msg.sender);
_withdraw(msg.sender, balance);
if (address(poolToken) != address(0)) {
poolToken.poolRedeem(msg.sender, committedBalance);
}
emit Withdrawn(msg.sender, balance);
}
/**
* Withdraws only from the sender's sponsorship and fee balances
* @param _amount The amount to withdraw
*/
function withdrawSponsorshipAndFee(uint256 _amount) public {
uint256 sponsorshipAndFees = sponsorshipAndFeeBalanceOf(msg.sender);
require(_amount <= sponsorshipAndFees, "Pool/exceeds-sfee");
_withdraw(msg.sender, _amount);
emit SponsorshipAndFeesWithdrawn(msg.sender, _amount);
}
/**
* Returns the total balance of the user's sponsorship and fees
* @param _sender The user whose balance should be returned
*/
function sponsorshipAndFeeBalanceOf(address _sender) public view returns (uint256) {
return balances[_sender].sub(drawState.balanceOf(_sender));
}
/**
* Withdraws from the user's open deposits
* @param _amount The amount to withdraw
*/
function withdrawOpenDeposit(uint256 _amount) public nonReentrant notLocked {
_withdrawOpenDeposit(msg.sender, _amount);
}
function _withdrawOpenDeposit(address sender, uint256 _amount) internal {
drawState.withdrawOpen(sender, _amount);
_withdraw(sender, _amount);
emit OpenDepositWithdrawn(sender, _amount);
}
/**
* Withdraws from the user's committed deposits
* @param _amount The amount to withdraw
*/
function withdrawCommittedDeposit(uint256 _amount) public nonReentrant notLocked returns (bool) {
_withdrawCommittedDeposit(msg.sender, _amount);
return true;
}
function _withdrawCommittedDeposit(address sender, uint256 _amount) internal {
_withdrawCommittedDepositAndEmit(sender, _amount);
if (address(poolToken) != address(0)) {
poolToken.poolRedeem(sender, _amount);
}
}
/**
* Allows the associated PoolToken to withdraw for a user; useful when redeeming through the token.
* @param _from The user to withdraw from
* @param _amount The amount to withdraw
*/
function withdrawCommittedDepositFrom(
address _from,
uint256 _amount
) external onlyToken notLocked returns (bool) {
return _withdrawCommittedDepositAndEmit(_from, _amount);
}
/**
* A function that withdraws committed deposits for a user and emits the corresponding events.
* @param _from User to withdraw for
* @param _amount The amount to withdraw
*/
function _withdrawCommittedDepositAndEmit(address _from, uint256 _amount) internal returns (bool) {
drawState.withdrawCommitted(_from, _amount);
_withdraw(_from, _amount);
emit CommittedDepositWithdrawn(_from, _amount);
return true;
}
/**
* @notice Allows the associated PoolToken to move committed tokens from one user to another.
* @param _from The account to move tokens from
* @param _to The account that is receiving the tokens
* @param _amount The amount of tokens to transfer
*/
function moveCommitted(
address _from,
address _to,
uint256 _amount
) external onlyToken onlyCommittedBalanceGteq(_from, _amount) notLocked returns (bool) {
balances[_from] = balances[_from].sub(_amount, "move could not sub amount");
balances[_to] = balances[_to].add(_amount);
drawState.withdrawCommitted(_from, _amount);
drawState.depositCommitted(_to, _amount);
return true;
}
/**
* @notice Transfers tokens from the cToken contract to the sender. Updates the accounted balance.
*/
function _withdraw(address _sender, uint256 _amount) internal {
uint256 balance = balances[_sender];
require(_amount <= balance, "Pool/no-funds");
// Update the user's balance
balances[_sender] = balance.sub(_amount);
// Update the total of this contract
accountedBalance = accountedBalance.sub(_amount);
// Withdraw from Compound and transfer
require(cToken.redeemUnderlying(_amount) == 0, "Pool/redeem");
require(token().transfer(_sender, _amount), "Pool/transfer");
}
/**
* @notice Returns the id of the current open Draw.
* @return The current open Draw id
*/
function currentOpenDrawId() public view returns (uint256) {
return drawState.openDrawIndex;
}
/**
* @notice Returns the id of the current committed Draw.
* @return The current committed Draw id
*/
function currentCommittedDrawId() public view returns (uint256) {
if (drawState.openDrawIndex > 1) {
return drawState.openDrawIndex - 1;
} else {
return 0;
}
}
/**
* @notice Returns whether the current committed draw has been rewarded
* @return True if the current committed draw has been rewarded, false otherwise
*/
function currentCommittedDrawHasBeenRewarded() internal view returns (bool) {
Draw storage draw = draws[currentCommittedDrawId()];
return draw.entropy != bytes32(0);
}
/**
* @notice Gets information for a given draw.
* @param _drawId The id of the Draw to retrieve info for.
* @return Fields including:
* feeFraction: the fee fraction
* feeBeneficiary: the beneficiary of the fee
* openedBlock: The block at which the draw was opened
* secretHash: The hash of the secret committed to this draw.
* entropy: the entropy used to select the winner
* winner: the address of the winner
* netWinnings: the total winnings less the fee
* fee: the fee taken by the beneficiary
*/
function getDraw(uint256 _drawId) public view returns (
uint256 feeFraction,
address feeBeneficiary,
uint256 openedBlock,
bytes32 secretHash,
bytes32 entropy,
address winner,
uint256 netWinnings,
uint256 fee
) {
Draw storage draw = draws[_drawId];
feeFraction = draw.feeFraction;
feeBeneficiary = draw.feeBeneficiary;
openedBlock = draw.openedBlock;
secretHash = draw.secretHash;
entropy = draw.entropy;
winner = draw.winner;
netWinnings = draw.netWinnings;
fee = draw.fee;
}
/**
* @notice Returns the total of the address's balance in committed Draws. That is, the total that contributes to their chances of winning.
* @param _addr The address of the user
* @return The total committed balance for the user
*/
function committedBalanceOf(address _addr) external view returns (uint256) {
return drawState.committedBalanceOf(_addr);
}
/**
* @notice Returns the total of the address's balance in the open Draw. That is, the total that will *eventually* contribute to their chances of winning.
* @param _addr The address of the user
* @return The total open balance for the user
*/
function openBalanceOf(address _addr) external view returns (uint256) {
return drawState.openBalanceOf(_addr);
}
/**
* @notice Returns a user's total balance. This includes their sponsorships, fees, open deposits, and committed deposits.
* @param _addr The address of the user to check.
* @return The user's current balance.
*/
function totalBalanceOf(address _addr) external view returns (uint256) {
return balances[_addr];
}
/**
* @notice Returns a user's committed balance. This is the balance of their Pool tokens.
* @param _addr The address of the user to check.
* @return The user's current balance.
*/
function balanceOf(address _addr) external view returns (uint256) {
return drawState.committedBalanceOf(_addr);
}
/**
* @notice Calculates a winner using the passed entropy for the current committed balances.
* @param _entropy The entropy to use to select the winner
* @return The winning address
*/
function calculateWinner(bytes32 _entropy) public view returns (address) {
return drawState.drawWithEntropy(_entropy);
}
/**
* @notice Returns the total committed balance. Used to compute an address's chances of winning.
* @return The total committed balance.
*/
function committedSupply() public view returns (uint256) {
return drawState.committedSupply();
}
/**
* @notice Returns the total open balance. This balance is the number of tickets purchased for the open draw.
* @return The total open balance
*/
function openSupply() public view returns (uint256) {
return drawState.openSupply();
}
/**
* @notice Calculates the total estimated interest earned for the given number of blocks
* @param _blocks The number of block that interest accrued for
* @return The total estimated interest as a 18 point fixed decimal.
*/
function estimatedInterestRate(uint256 _blocks) public view returns (uint256) {
return supplyRatePerBlock().mul(_blocks);
}
/**
* @notice Convenience function to return the supplyRatePerBlock value from the money market contract.
* @return The cToken supply rate per block
*/
function supplyRatePerBlock() public view returns (uint256) {
return cToken.supplyRatePerBlock();
}
/**
* @notice Sets the beneficiary fee fraction for subsequent Draws.
* Fires the NextFeeFractionChanged event.
* Can only be called by an admin.
* @param _feeFraction The fee fraction to use.
* Must be between 0 and 1 and formatted as a fixed point number with 18 decimals (as in Ether).
*/
function setNextFeeFraction(uint256 _feeFraction) public onlyAdmin {
_setNextFeeFraction(_feeFraction);
}
function _setNextFeeFraction(uint256 _feeFraction) internal {
require(_feeFraction <= 1 ether, "Pool/less-1");
nextFeeFraction = _feeFraction;
emit NextFeeFractionChanged(_feeFraction);
}
/**
* @notice Sets the fee beneficiary for subsequent Draws.
* Can only be called by admins.
* @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address.
*/
function setNextFeeBeneficiary(address _feeBeneficiary) public onlyAdmin {
_setNextFeeBeneficiary(_feeBeneficiary);
}
/**
* @notice Sets the fee beneficiary for subsequent Draws.
* @param _feeBeneficiary The beneficiary for the fee fraction. Cannot be the 0 address.
*/
function _setNextFeeBeneficiary(address _feeBeneficiary) internal {
require(_feeBeneficiary != address(0), "Pool/not-zero");
nextFeeBeneficiary = _feeBeneficiary;
emit NextFeeBeneficiaryChanged(_feeBeneficiary);
}
/**
* @notice Adds an administrator.
* Can only be called by administrators.
* Fires the AdminAdded event.
* @param _admin The address of the admin to add
*/
function addAdmin(address _admin) public onlyAdmin {
_addAdmin(_admin);
}
/**
* @notice Checks whether a given address is an administrator.
* @param _admin The address to check
* @return True if the address is an admin, false otherwise.
*/
function isAdmin(address _admin) public view returns (bool) {
return admins.has(_admin);
}
/**
* @notice Checks whether a given address is an administrator.
* @param _admin The address to check
* @return True if the address is an admin, false otherwise.
*/
function _addAdmin(address _admin) internal {
admins.add(_admin);
emit AdminAdded(_admin);
}
/**
* @notice Removes an administrator
* Can only be called by an admin.
* Admins cannot remove themselves. This ensures there is always one admin.
* @param _admin The address of the admin to remove
*/
function removeAdmin(address _admin) public onlyAdmin {
require(admins.has(_admin), "Pool/no-admin");
require(_admin != msg.sender, "Pool/remove-self");
admins.remove(_admin);
emit AdminRemoved(_admin);
}
/**
* Requires that there is a committed draw that has not been rewarded.
*/
modifier requireCommittedNoReward() {
require(currentCommittedDrawId() > 0, "Pool/committed");
require(!currentCommittedDrawHasBeenRewarded(), "Pool/already");
_;
}
/**
* @notice Returns the token underlying the cToken.
* @return An ERC20 token address
*/
function token() public view returns (IERC20) {
return IERC20(cToken.underlying());
}
/**
* @notice Returns the underlying balance of this contract in the cToken.
* @return The cToken underlying balance for this contract.
*/
function balance() public returns (uint256) {
return cToken.balanceOfUnderlying(address(this));
}
/**
* @notice Locks the movement of tokens (essentially the committed deposits and winnings)
* @dev The lock only lasts for a duration of blocks. The lock cannot be relocked until the cooldown duration completes.
*/
function lockTokens() public onlyAdmin {
blocklock.lock(block.number);
}
/**
* @notice Unlocks the movement of tokens (essentially the committed deposits)
*/
function unlockTokens() public onlyAdmin {
blocklock.unlock(block.number);
}
/**
* Pauses all deposits into the contract. This was added so that we can slowly deprecate Pools. Users can continue
* to collect rewards and withdraw, but eventually the Pool will grow smaller.
*
* emits DepositsPaused
*/
function pauseDeposits() public unlessDepositsPaused onlyAdmin {
paused = true;
emit DepositsPaused(msg.sender);
}
/**
* @notice Unpauses all deposits into the contract
*
* emits DepositsUnpaused
*/
function unpauseDeposits() public whenDepositsPaused onlyAdmin {
paused = false;
emit DepositsUnpaused(msg.sender);
}
/**
* @notice Check if the contract is locked.
* @return True if the contract is locked, false otherwise
*/
function isLocked() public view returns (bool) {
return blocklock.isLocked(block.number);
}
/**
* @notice Returns the block number at which the lock expires
* @return The block number at which the lock expires
*/
function lockEndAt() public view returns (uint256) {
return blocklock.lockEndAt();
}
/**
* @notice Check cooldown end block
* @return The block number at which the cooldown ends and the contract can be re-locked
*/
function cooldownEndAt() public view returns (uint256) {
return blocklock.cooldownEndAt();
}
/**
* @notice Returns whether the contract can be locked
* @return True if the contract can be locked, false otherwise
*/
function canLock() public view returns (bool) {
return blocklock.canLock(block.number);
}
/**
* @notice Duration of the lock
* @return Returns the duration of the lock in blocks.
*/
function lockDuration() public view returns (uint256) {
return blocklock.lockDuration;
}
/**
* @notice Returns the cooldown duration. The cooldown period starts after the Pool has been unlocked.
* The Pool cannot be locked during the cooldown period.
* @return The cooldown duration in blocks
*/
function cooldownDuration() public view returns (uint256) {
return blocklock.cooldownDuration;
}
/**
* @notice requires the pool not to be locked
*/
modifier notLocked() {
require(!blocklock.isLocked(block.number), "Pool/locked");
_;
}
/**
* @notice requires the pool to be locked
*/
modifier onlyLocked() {
require(blocklock.isLocked(block.number), "Pool/unlocked");
_;
}
/**
* @notice requires the caller to be an admin
*/
modifier onlyAdmin() {
require(admins.has(msg.sender), "Pool/admin");
_;
}
/**
* @notice Requires an open draw to exist
*/
modifier requireOpenDraw() {
require(currentOpenDrawId() != 0, "Pool/no-open");
_;
}
/**
* @notice Requires deposits to be paused
*/
modifier whenDepositsPaused() {
require(paused, "Pool/d-not-paused");
_;
}
/**
* @notice Requires deposits not to be paused
*/
modifier unlessDepositsPaused() {
require(!paused, "Pool/d-paused");
_;
}
/**
* @notice Requires the caller to be the pool token
*/
modifier onlyToken() {
require(msg.sender == address(poolToken), "Pool/only-token");
_;
}
/**
* @notice requires the passed user's committed balance to be greater than or equal to the passed amount
* @param _from The user whose committed balance should be checked
* @param _amount The minimum amount they must have
*/
modifier onlyCommittedBalanceGteq(address _from, uint256 _amount) {
uint256 committedBalance = drawState.committedBalanceOf(_from);
require(_amount <= committedBalance, "not enough funds");
_;
}
}
contract ScdMcdMigration {
SaiTubLike public tub;
VatLike public vat;
ManagerLike public cdpManager;
JoinLike public saiJoin;
JoinLike public wethJoin;
JoinLike public daiJoin;
constructor(
address tub_, // SCD tub contract address
address cdpManager_, // MCD manager contract address
address saiJoin_, // MCD SAI collateral adapter contract address
address wethJoin_, // MCD ETH collateral adapter contract address
address daiJoin_ // MCD DAI adapter contract address
) public {
tub = SaiTubLike(tub_);
cdpManager = ManagerLike(cdpManager_);
vat = VatLike(cdpManager.vat());
saiJoin = JoinLike(saiJoin_);
wethJoin = JoinLike(wethJoin_);
daiJoin = JoinLike(daiJoin_);
require(wethJoin.gem() == tub.gem(), "non-matching-weth");
require(saiJoin.gem() == tub.sai(), "non-matching-sai");
tub.gov().approve(address(tub), uint(-1));
tub.skr().approve(address(tub), uint(-1));
tub.sai().approve(address(tub), uint(-1));
tub.sai().approve(address(saiJoin), uint(-1));
wethJoin.gem().approve(address(wethJoin), uint(-1));
daiJoin.dai().approve(address(daiJoin), uint(-1));
vat.hope(address(daiJoin));
}
function add(uint x, uint y) internal pure returns (uint z) {
require((z = x + y) >= x, "add-overflow");
}
function sub(uint x, uint y) internal pure returns (uint z) {
require((z = x - y) <= x, "sub-underflow");
}
function mul(uint x, uint y) internal pure returns (uint z) {
require(y == 0 || (z = x * y) / y == x, "mul-overflow");
}
function toInt(uint x) internal pure returns (int y) {
y = int(x);
require(y >= 0, "int-overflow");
}
// Function to swap SAI to DAI
// This function is to be used by users that want to get new DAI in exchange of old one (aka SAI)
// wad amount has to be <= the value pending to reach the debt ceiling (the minimum between general and ilk one)
function swapSaiToDai(
uint wad
) external {
// Get wad amount of SAI from user's wallet:
saiJoin.gem().transferFrom(msg.sender, address(this), wad);
// Join the SAI wad amount to the `vat`:
saiJoin.join(address(this), wad);
// Lock the SAI wad amount to the CDP and generate the same wad amount of DAI
vat.frob(saiJoin.ilk(), address(this), address(this), address(this), toInt(wad), toInt(wad));
// Send DAI wad amount as a ERC20 token to the user's wallet
daiJoin.exit(msg.sender, wad);
}
// Function to swap DAI to SAI
// This function is to be used by users that want to get SAI in exchange of DAI
// wad amount has to be <= the amount of SAI locked (and DAI generated) in the migration contract SAI CDP
function swapDaiToSai(
uint wad
) external {
// Get wad amount of DAI from user's wallet:
daiJoin.dai().transferFrom(msg.sender, address(this), wad);
// Join the DAI wad amount to the vat:
daiJoin.join(address(this), wad);
// Payback the DAI wad amount and unlocks the same value of SAI collateral
vat.frob(saiJoin.ilk(), address(this), address(this), address(this), -toInt(wad), -toInt(wad));
// Send SAI wad amount as a ERC20 token to the user's wallet
saiJoin.exit(msg.sender, wad);
}
// Function to migrate a SCD CDP to MCD one (needs to be used via a proxy so the code can be kept simpler). Check MigrationProxyActions.sol code for usage.
// In order to use migrate function, SCD CDP debtAmt needs to be <= SAI previously deposited in the SAI CDP * (100% - Collateralization Ratio)
function migrate(
bytes32 cup
) external returns (uint cdp) {
// Get values
uint debtAmt = tub.tab(cup); // CDP SAI debt
uint pethAmt = tub.ink(cup); // CDP locked collateral
uint ethAmt = tub.bid(pethAmt); // CDP locked collateral equiv in ETH
// Take SAI out from MCD SAI CDP. For this operation is necessary to have a very low collateralization ratio
// This is not actually a problem as this ilk will only be accessed by this migration contract,
// which will make sure to have the amounts balanced out at the end of the execution.
vat.frob(
bytes32(saiJoin.ilk()),
address(this),
address(this),
address(this),
-toInt(debtAmt),
0
);
saiJoin.exit(address(this), debtAmt); // SAI is exited as a token
// Shut SAI CDP and gets WETH back
tub.shut(cup); // CDP is closed using the SAI just exited and the MKR previously sent by the user (via the proxy call)
tub.exit(pethAmt); // Converts PETH to WETH
// Open future user's CDP in MCD
cdp = cdpManager.open(wethJoin.ilk(), address(this));
// Join WETH to Adapter
wethJoin.join(cdpManager.urns(cdp), ethAmt);
// Lock WETH in future user's CDP and generate debt to compensate the SAI used to paid the SCD CDP
(, uint rate,,,) = vat.ilks(wethJoin.ilk());
cdpManager.frob(
cdp,
toInt(ethAmt),
toInt(mul(debtAmt, 10 ** 27) / rate + 1) // To avoid rounding issues we add an extra wei of debt
);
// Move DAI generated to migration contract (to recover the used funds)
cdpManager.move(cdp, address(this), mul(debtAmt, 10 ** 27));
// Re-balance MCD SAI migration contract's CDP
vat.frob(
bytes32(saiJoin.ilk()),
address(this),
address(this),
address(this),
0,
-toInt(debtAmt)
);
// Set ownership of CDP to the user
cdpManager.give(cdp, msg.sender);
}
}
/**
* @dev Interface of the ERC777TokensRecipient standard as defined in the EIP.
*
* Accounts can be notified of {IERC777} tokens being sent to them by having a
* contract implement this interface (contract holders can be their own
* implementer) and registering it on the
* https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry].
*
* See {IERC1820Registry} and {ERC1820Implementer}.
*/
interface IERC777Recipient {
/**
* @dev Called by an {IERC777} token contract whenever tokens are being
* moved or created into a registered account (`to`). The type of operation
* is conveyed by `from` being the zero address or not.
*
* This call occurs _after_ the token contract's state is updated, so
* {IERC777-balanceOf}, etc., can be used to query the post-operation state.
*
* This function may revert to prevent the operation from being executed.
*/
function tokensReceived(
address operator,
address from,
address to,
uint256 amount,
bytes calldata userData,
bytes calldata operatorData
) external;
}
/**
* @title MCDAwarePool
* @author Brendan Asselstine [email protected]
* @notice This contract is a Pool that is aware of the new Multi-Collateral Dai. It uses the ERC777Recipient interface to
* detect if it's being transferred tickets from the old single collateral Dai (Sai) Pool. If it is, it migrates the Sai to Dai
* and immediately deposits the new Dai as committed tickets for that user. We are knowingly bypassing the committed period for
* users to encourage them to migrate to the MCD Pool.
*/
contract MCDAwarePool is BasePool, IERC777Recipient {
IERC1820Registry constant internal ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24);
// keccak256("ERC777TokensRecipient")
bytes32 constant internal TOKENS_RECIPIENT_INTERFACE_HASH =
0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b;
uint256 internal constant DEFAULT_LOCK_DURATION = 40;
uint256 internal constant DEFAULT_COOLDOWN_DURATION = 80;
/**
* @notice The address of the ScdMcdMigration contract (see https://github.com/makerdao/developerguides/blob/master/mcd/upgrading-to-multi-collateral-dai/upgrading-to-multi-collateral-dai.md#direct-integration-with-smart-contracts)
*/
ScdMcdMigration public scdMcdMigration;
/**
* @notice The address of the Sai Pool contract
*/
MCDAwarePool public saiPool;
/**
* @notice Initializes the contract.
* @param _owner The initial administrator of the contract
* @param _cToken The Compound cToken to bind this Pool to
* @param _feeFraction The fraction of the winnings to give to the beneficiary
* @param _feeBeneficiary The beneficiary who receives the fee
*/
function init (
address _owner,
address _cToken,
uint256 _feeFraction,
address _feeBeneficiary,
uint256 lockDuration,
uint256 cooldownDuration
) public initializer {
super.init(
_owner,
_cToken,
_feeFraction,
_feeBeneficiary,
lockDuration,
cooldownDuration
);
initRegistry();
initBlocklock(lockDuration, cooldownDuration);
}
/**
* @notice Used to initialize the BasePool contract after an upgrade. Registers the MCDAwarePool with the ERC1820 registry so that it can receive tokens, and inits the block lock.
*/
function initMCDAwarePool(uint256 lockDuration, uint256 cooldownDuration) public {
initRegistry();
if (blocklock.lockDuration == 0) {
initBlocklock(lockDuration, cooldownDuration);
}
}
function initRegistry() internal {
ERC1820_REGISTRY.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this));
}
function initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) public onlyAdmin {
_initMigration(_scdMcdMigration, _saiPool);
}
function _initMigration(ScdMcdMigration _scdMcdMigration, MCDAwarePool _saiPool) internal {
require(address(scdMcdMigration) == address(0), "Pool/init");
require(address(_scdMcdMigration) != address(0), "Pool/mig-def");
scdMcdMigration = _scdMcdMigration;
saiPool = _saiPool; // may be null
}
/**
* @notice Called by an ERC777 token when tokens are sent, transferred, or minted. If the sender is the original Sai Pool
* and this pool is bound to the Dai token then it will accept the transfer, migrate the tokens, and deposit on behalf of
* the sender. It will reject all other tokens.
*
* If there is a committed draw this function will mint the user tickets immediately, otherwise it will place them in the
* open prize. This is to encourage migration.
*
* @param from The sender
* @param amount The amount they are transferring
*/
function tokensReceived(
address, // operator
address from,
address, // to address can't be anything but us because we don't implement ERC1820ImplementerInterface
uint256 amount,
bytes calldata,
bytes calldata
) external unlessDepositsPaused {
require(msg.sender == address(saiPoolToken()), "Pool/sai-only");
require(address(token()) == address(daiToken()), "Pool/not-dai");
// cash out of the Pool. This call transfers sai to this contract
saiPoolToken().redeem(amount, '');
// approve of the transfer to the migration contract
saiToken().approve(address(scdMcdMigration), amount);
// migrate the sai to dai. The contract now has dai
scdMcdMigration.swapSaiToDai(amount);
if (currentCommittedDrawId() > 0) {
// now deposit the dai as tickets
_depositPoolFromCommitted(from, amount);
} else {
_depositPoolFrom(from, amount);
}
}
/**
* @notice Returns the address of the PoolSai pool token contract
* @return The address of the Sai PoolToken contract
*/
function saiPoolToken() internal view returns (PoolToken) {
if (address(saiPool) != address(0)) {
return saiPool.poolToken();
} else {
return PoolToken(0);
}
}
/**
* @notice Returns the address of the Sai token
* @return The address of the sai token
*/
function saiToken() public returns (GemLike) {
return scdMcdMigration.saiJoin().gem();
}
/**
* @notice Returns the address of the Dai token
* @return The address of the Dai token.
*/
function daiToken() public returns (GemLike) {
return scdMcdMigration.daiJoin().dai();
}
}
/**
Copyright 2020 PoolTogether Inc.
This file is part of PoolTogether.
PoolTogether is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation under version 3 of the License.
PoolTogether is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with PoolTogether. If not, see <https://www.gnu.org/licenses/>.
*/
interface IComptroller {
function claimComp(address holder, ICErc20[] calldata cTokens) external;
}
contract AutonomousPool is MCDAwarePool {
event PrizePeriodSecondsUpdated(uint256 prizePeriodSeconds);
event ComptrollerUpdated(IComptroller comptroller);
event CompRecipientUpdated(address compRecipient);
event AwardStarted();
event AwardCompleted();
uint256 public lastAwardTimestamp;
uint256 public prizePeriodSeconds;
IComptroller public comptroller;
IERC20 public comp;
address public compRecipient;
event TransferredComp(
address indexed recipient,
uint256 amount
);
function initializeAutonomousPool(
uint256 _prizePeriodSeconds,
IERC20 _comp,
IComptroller _comptroller
) external {
require(address(comp) == address(0), "AutonomousPool/already-init");
require(address(_comp) != address(0), "AutonomousPool/comp-not-defined");
require(address(_comptroller) != address(0), "AutonomousPool/comptroller-not-defined");
comp = _comp;
_setPrizePeriodSeconds(_prizePeriodSeconds);
_setComptroller(_comptroller);
}
function setPrizePeriodSeconds(uint256 _prizePeriodSeconds) external onlyAdmin {
_setPrizePeriodSeconds(_prizePeriodSeconds);
}
function _setPrizePeriodSeconds(uint256 _prizePeriodSeconds) internal {
require(_prizePeriodSeconds > 0, "AutonomousPool/pp-gt-zero");
prizePeriodSeconds = _prizePeriodSeconds;
emit PrizePeriodSecondsUpdated(prizePeriodSeconds);
}
function setComptroller(IComptroller _comptroller) external onlyAdmin {
_setComptroller(_comptroller);
}
function _setComptroller(IComptroller _comptroller) internal {
comptroller = _comptroller;
emit ComptrollerUpdated(comptroller);
}
function setCompRecipient(address _compRecipient) external onlyAdmin {
compRecipient = _compRecipient;
emit CompRecipientUpdated(compRecipient);
}
/// @notice Returns whether the prize period has ended.
function isPrizePeriodEnded() public view returns (bool) {
return remainingTime() == 0;
}
function claimAndTransferCOMP() public returns (uint256) {
if (address(comptroller) == address(0)) {
return 0;
}
ICErc20[] memory cTokens = new ICErc20[](1);
cTokens[0] = cToken;
comptroller.claimComp(address(this), cTokens);
return transferCOMP();
}
function transferCOMP() public returns (uint256) {
if (compRecipient == address(0)) {
return 0;
}
uint256 amount = comp.balanceOf(address(this));
comp.transfer(compRecipient, amount);
emit TransferredComp(compRecipient, amount);
return amount;
}
/**
* @notice Locks the movement of tokens (essentially the committed deposits and winnings)
* @dev The lock only lasts for a duration of blocks. The lock cannot be relocked until the cooldown duration completes.
*/
function lockTokens() public requireInitialized onlyPrizePeriodEnded {
blocklock.lock(block.number);
emit AwardStarted();
}
/// @notice Starts the award process. The prize period must have ended.
/// @dev Essentially an alias for lockTokens()
function startAward() public {
lockTokens();
}
/**
* @notice Rewards the current committed draw using the passed secret, commits the current open draw, and opens the next draw using the passed secret hash.
* Can only be called by an admin.
* Fires the Rewarded event, the Committed event, and the Open event.
*/
function completeAward() external requireInitialized onlyLocked nonReentrant {
// if there is a committed draw, it can be awarded
if (currentCommittedDrawId() > 0) {
_reward();
}
if (currentOpenDrawId() != 0) {
emitCommitted();
}
_open();
lastAwardTimestamp = _currentTime();
emit AwardCompleted();
}
/**
* @notice Rewards the winner for the current committed Draw using the passed secret.
* The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance.
* A winner is calculated using the revealed secret.
* If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings.
* The draw beneficiary's balance is updated with the fee.
* The accounted balance is updated to include the fee and, if there was a winner, the net winnings.
* Fires the Rewarded event.
*/
function _reward() internal {
// require that there is a committed draw
// require that the committed draw has not been rewarded
uint256 drawId = currentCommittedDrawId();
Draw storage draw = draws[drawId];
bytes32 entropy = blockhash(block.number - 1);
_reward(drawId, draw, entropy);
}
/**
* @notice Opens a new Draw.
*/
function _open() internal {
drawState.openNextDraw();
draws[drawState.openDrawIndex] = Draw(
nextFeeFraction,
nextFeeBeneficiary,
block.number,
bytes32(0),
bytes32(0),
address(0),
uint256(0),
uint256(0)
);
emit Opened(
drawState.openDrawIndex,
nextFeeBeneficiary,
bytes32(0),
nextFeeFraction
);
}
function canStartAward() public view returns (bool) {
return _isAutonomousPoolInitialized() && isPrizePeriodEnded();
}
function canCompleteAward() public view returns (bool) {
return _isAutonomousPoolInitialized() && blocklock.isLocked(block.number);
}
function elapsedTime() public view returns (uint256) {
return _currentTime().sub(lastAwardTimestamp);
}
function remainingTime() public view returns (uint256) {
uint256 elapsed = elapsedTime();
if (elapsed > prizePeriodSeconds) {
return 0;
} else {
return prizePeriodSeconds.sub(elapsed);
}
}
function _currentTime() internal view returns (uint256) {
return block.timestamp;
}
function _isAutonomousPoolInitialized() internal view returns (bool) {
return address(comp) != address(0);
}
function openNextDraw(bytes32 nextSecretHash) public {
revert('AutonomousPool/deprecated');
}
function rolloverAndOpenNextDraw(bytes32 nextSecretHash) public {
revert('AutonomousPool/deprecated');
}
function rewardAndOpenNextDraw(bytes32 nextSecretHash, bytes32 lastSecret, bytes32 _salt) public {
revert('AutonomousPool/deprecated');
}
function reward(bytes32 _secret, bytes32 _salt) public {
revert('AutonomousPool/deprecated');
}
modifier onlyPrizePeriodEnded() {
require(isPrizePeriodEnded(), "AutonomousPool/prize-period-not-ended");
_;
}
modifier requireInitialized() {
require(address(comp) != address(0), "AutonomousPool/not-init");
_;
}
}
|
Rewards the winner for the current committed Draw using the passed secret. The gross winnings are calculated by subtracting the accounted balance from the current underlying cToken balance. A winner is calculated using the revealed secret. If there is a winner (i.e. any eligible users) then winner's balance is updated with their net winnings. The draw beneficiary's balance is updated with the fee. The accounted balance is updated to include the fee and, if there was a winner, the net winnings. Fires the Rewarded event./ require that there is a committed draw require that the committed draw has not been rewarded
|
function _reward() internal {
uint256 drawId = currentCommittedDrawId();
Draw storage draw = draws[drawId];
bytes32 entropy = blockhash(block.number - 1);
_reward(drawId, draw, entropy);
}
| 8,051,666 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/Math.sol";
import "@openzeppelin/contracts/math/SafeMath.sol";
import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol";
import "./libraries/DecimalsConverter.sol";
import "./tokens/erc20permit-upgradeable/ERC20PermitUpgradeable.sol";
import "./interfaces/IPolicyBook.sol";
import "./interfaces/IBMICoverStaking.sol";
import "./interfaces/ICapitalPool.sol";
import "./interfaces/IBMICoverStakingView.sol";
import "./interfaces/IContractsRegistry.sol";
import "./interfaces/IPolicyRegistry.sol";
import "./interfaces/IClaimVoting.sol";
import "./interfaces/IClaimingRegistry.sol";
import "./interfaces/ILiquidityMining.sol";
import "./interfaces/IPolicyQuote.sol";
import "./interfaces/IRewardsGenerator.sol";
import "./interfaces/ILiquidityRegistry.sol";
import "./interfaces/INFTStaking.sol";
import "./abstract/AbstractDependant.sol";
import "./Globals.sol";
contract PolicyBook is IPolicyBook, ERC20PermitUpgradeable, AbstractDependant {
using SafeERC20 for ERC20;
using SafeMath for uint256;
using Math for uint256;
uint256 public constant MINUMUM_COVERAGE = 100 * DECIMALS18; // 100 STBL
uint256 public constant ANNUAL_COVERAGE_TOKENS = MINUMUM_COVERAGE * 10; // 1000 STBL
uint256 public constant RISKY_UTILIZATION_RATIO = 80 * PRECISION;
uint256 public constant MODERATE_UTILIZATION_RATIO = 50 * PRECISION;
uint256 public constant PREMIUM_DISTRIBUTION_EPOCH = 1 days;
uint256 public constant MAX_PREMIUM_DISTRIBUTION_EPOCHS = 90;
uint256 public constant MINIMUM_REWARD = 15 * PRECISION; // 0.15
uint256 public constant MAXIMUM_REWARD = 2 * PERCENTAGE_100; // 2.0
uint256 public constant BASE_REWARD = PERCENTAGE_100; // 1.0
uint256 public constant override EPOCH_DURATION = 1 weeks;
uint256 public constant MAXIMUM_EPOCHS = SECONDS_IN_THE_YEAR / EPOCH_DURATION;
uint256 public constant VIRTUAL_EPOCHS = 2;
uint256 public constant WITHDRAWAL_PERIOD = 8 days;
uint256 public constant override READY_TO_WITHDRAW_PERIOD = 2 days;
bool public override whitelisted;
uint256 public override epochStartTime;
uint256 public lastDistributionEpoch;
uint256 public lastPremiumDistributionEpoch;
int256 public lastPremiumDistributionAmount;
address public override insuranceContractAddress;
IPolicyBookFabric.ContractType public override contractType;
ERC20 public stblToken;
IPolicyRegistry public policyRegistry;
IBMICoverStaking public bmiCoverStaking;
IRewardsGenerator public rewardsGenerator;
ILiquidityMining public liquidityMining;
IClaimVoting public claimVoting;
IClaimingRegistry public claimingRegistry;
ILiquidityRegistry public liquidityRegistry;
address public reinsurancePoolAddress;
IPolicyQuote public policyQuote;
address public policyBookAdmin;
address public policyBookRegistry;
address public policyBookFabricAddress;
uint256 public override totalLiquidity;
uint256 public override totalCoverTokens;
mapping(address => WithdrawalInfo) public override withdrawalsInfo;
mapping(address => PolicyHolder) public override policyHolders;
mapping(address => uint256) public liquidityFromLM;
mapping(uint256 => uint256) public epochAmounts;
mapping(uint256 => int256) public premiumDistributionDeltas;
uint256 public override stblDecimals;
// new state variables here , avoid break the storage when upgrade
INFTStaking public nftStaking;
IBMICoverStakingView public bmiCoverStakingView;
ICapitalPool public capitalPool;
IPolicyBookFacade public override policyBookFacade;
event LiquidityAdded(
address _liquidityHolder,
uint256 _liquidityAmount,
uint256 _newTotalLiquidity
);
event WithdrawalRequested(
address _liquidityHolder,
uint256 _tokensToWithdraw,
uint256 _readyToWithdrawDate
);
event LiquidityWithdrawn(
address _liquidityHolder,
uint256 _tokensToWithdraw,
uint256 _newTotalLiquidity
);
event PolicyBought(
address _policyHolder,
uint256 _coverTokens,
uint256 _price,
uint256 _newTotalCoverTokens,
address _distributor
);
event CoverageChanged(uint256 _newTotalCoverTokens);
modifier onlyClaimVoting() {
require(_msgSender() == address(claimVoting), "PB: Not a CV");
_;
}
modifier onlyPolicyBookFacade() {
require(_msgSender() == address(policyBookFacade), "PB: Not a PBFc");
_;
}
modifier onlyPolicyBookFabric() {
require(_msgSender() == policyBookFabricAddress, "PB: Not PBF");
_;
}
modifier onlyPolicyBookAdmin() {
require(_msgSender() == policyBookAdmin, "PB: Not a PBA");
_;
}
modifier onlyLiquidityAdders() {
require(
_msgSender() == policyBookFabricAddress || _msgSender() == address(policyBookFacade),
"PB: Not allowed"
);
_;
}
modifier onlyCapitalPool() {
require(_msgSender() == address(capitalPool), "PB: Not a CP");
_;
}
modifier updateBMICoverStakingReward() {
_;
forceUpdateBMICoverStakingRewardMultiplier();
}
modifier withPremiumsDistribution() {
_distributePremiums();
_;
}
function _distributePremiums() internal {
uint256 lastEpoch = lastPremiumDistributionEpoch;
uint256 currentEpoch = _getPremiumDistributionEpoch();
if (currentEpoch > lastEpoch) {
(
lastPremiumDistributionAmount,
lastPremiumDistributionEpoch,
totalLiquidity
) = _getPremiumsDistribution(lastEpoch, currentEpoch);
}
}
function __PolicyBook_init(
address _insuranceContract,
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external override initializer {
string memory fullSymbol = string(abi.encodePacked("bmiV2", _projectSymbol, "Cover"));
__ERC20Permit_init(fullSymbol);
__ERC20_init(_description, fullSymbol);
insuranceContractAddress = _insuranceContract;
contractType = _contractType;
epochStartTime = block.timestamp;
lastDistributionEpoch = 1;
lastPremiumDistributionEpoch = _getPremiumDistributionEpoch();
}
function setPolicyBookFacade(address _policyBookFacade)
external
override
onlyPolicyBookFabric
{
policyBookFacade = IPolicyBookFacade(_policyBookFacade);
}
function setDependencies(IContractsRegistry _contractsRegistry)
external
override
onlyInjectorOrZero
{
stblToken = ERC20(_contractsRegistry.getUSDTContract());
bmiCoverStaking = IBMICoverStaking(_contractsRegistry.getBMICoverStakingContract());
bmiCoverStakingView = IBMICoverStakingView(
_contractsRegistry.getBMICoverStakingViewContract()
);
rewardsGenerator = IRewardsGenerator(_contractsRegistry.getRewardsGeneratorContract());
claimVoting = IClaimVoting(_contractsRegistry.getClaimVotingContract());
policyRegistry = IPolicyRegistry(_contractsRegistry.getPolicyRegistryContract());
reinsurancePoolAddress = _contractsRegistry.getReinsurancePoolContract();
capitalPool = ICapitalPool(_contractsRegistry.getCapitalPoolContract());
policyQuote = IPolicyQuote(_contractsRegistry.getPolicyQuoteContract());
claimingRegistry = IClaimingRegistry(_contractsRegistry.getClaimingRegistryContract());
liquidityRegistry = ILiquidityRegistry(_contractsRegistry.getLiquidityRegistryContract());
policyBookAdmin = _contractsRegistry.getPolicyBookAdminContract();
policyBookRegistry = _contractsRegistry.getPolicyBookRegistryContract();
policyBookFabricAddress = _contractsRegistry.getPolicyBookFabricContract();
nftStaking = INFTStaking(_contractsRegistry.getNFTStakingContract());
stblDecimals = stblToken.decimals();
}
function whitelist(bool _whitelisted)
external
override
onlyPolicyBookAdmin
updateBMICoverStakingReward
{
whitelisted = _whitelisted;
}
function getEpoch(uint256 time) public view override returns (uint256) {
return time.sub(epochStartTime).div(EPOCH_DURATION) + 1;
}
function _getPremiumDistributionEpoch() internal view returns (uint256) {
return block.timestamp / PREMIUM_DISTRIBUTION_EPOCH;
}
function _getSTBLToBMIXRatio(uint256 currentLiquidity) internal view returns (uint256) {
uint256 _currentTotalSupply = totalSupply();
if (_currentTotalSupply == 0) {
return PERCENTAGE_100;
}
return currentLiquidity.mul(PERCENTAGE_100).div(_currentTotalSupply);
}
function convertBMIXToSTBL(uint256 _amount) public view override returns (uint256) {
(, uint256 currentLiquidity) = getNewCoverAndLiquidity();
return _amount.mul(_getSTBLToBMIXRatio(currentLiquidity)).div(PERCENTAGE_100);
}
function convertSTBLToBMIX(uint256 _amount) public view override returns (uint256) {
(, uint256 currentLiquidity) = getNewCoverAndLiquidity();
return _amount.mul(PERCENTAGE_100).div(_getSTBLToBMIXRatio(currentLiquidity));
}
function _submitClaimAndInitializeVoting(string memory evidenceURI, bool appeal) internal {
uint256 cover = policyHolders[_msgSender()].coverTokens;
uint256 virtualEndEpochNumber =
policyHolders[_msgSender()].endEpochNumber + VIRTUAL_EPOCHS;
/// @dev "lock" claim and appeal tokens
if (!appeal) {
epochAmounts[virtualEndEpochNumber] = epochAmounts[virtualEndEpochNumber].sub(cover);
} else {
uint256 claimIndex = claimingRegistry.claimIndex(_msgSender(), address(this));
uint256 endLockEpoch =
Math.max(
getEpoch(claimingRegistry.claimEndTime(claimIndex)) + 1,
virtualEndEpochNumber
);
epochAmounts[endLockEpoch] = epochAmounts[endLockEpoch].sub(cover);
}
/// @dev if appeal period expired, this would fail in case of appeal (no button is displayed on FE)
claimVoting.initializeVoting(_msgSender(), evidenceURI, cover, appeal);
}
function submitClaimAndInitializeVoting(string calldata evidenceURI) external override {
_submitClaimAndInitializeVoting(evidenceURI, false);
}
function submitAppealAndInitializeVoting(string calldata evidenceURI) external override {
_submitClaimAndInitializeVoting(evidenceURI, true);
}
function commitClaim(
address claimer,
uint256 claimAmount,
uint256 claimEndTime,
IClaimingRegistry.ClaimStatus status
) external override onlyClaimVoting withPremiumsDistribution updateBMICoverStakingReward {
updateEpochsInfo();
uint256 cover = policyHolders[claimer].coverTokens;
if (status == IClaimingRegistry.ClaimStatus.ACCEPTED) {
uint256 newTotalCover = totalCoverTokens.sub(cover);
totalCoverTokens = newTotalCover;
capitalPool.fundClaim(claimer, claimAmount);
// TODO: verify
// check additional state changes other than transfer
delete policyHolders[claimer];
policyRegistry.removePolicy(claimer);
} else if (status == IClaimingRegistry.ClaimStatus.REJECTED_CAN_APPEAL) {
uint256 endUnlockEpoch =
Math.max(
getEpoch(claimEndTime) + 1,
policyHolders[claimer].endEpochNumber + VIRTUAL_EPOCHS
);
epochAmounts[endUnlockEpoch] = epochAmounts[endUnlockEpoch].add(cover);
} else {
uint256 virtualEndEpochNumber =
policyHolders[claimer].endEpochNumber.add(VIRTUAL_EPOCHS);
if (lastDistributionEpoch <= virtualEndEpochNumber) {
epochAmounts[virtualEndEpochNumber] = epochAmounts[virtualEndEpochNumber].add(
cover
);
} else {
uint256 newTotalCover = totalCoverTokens.sub(cover);
totalCoverTokens = newTotalCover;
policyBookFacade.reevaluateProvidedLeverageStable();
emit CoverageChanged(newTotalCover);
}
}
}
function _getPremiumsDistribution(uint256 lastEpoch, uint256 currentEpoch)
internal
view
returns (
int256 currentDistribution,
uint256 distributionEpoch,
uint256 newTotalLiquidity
)
{
currentDistribution = lastPremiumDistributionAmount;
newTotalLiquidity = totalLiquidity;
distributionEpoch = Math.min(
currentEpoch,
lastEpoch + MAX_PREMIUM_DISTRIBUTION_EPOCHS + 1
);
for (uint256 i = lastEpoch + 1; i <= distributionEpoch; i++) {
currentDistribution += premiumDistributionDeltas[i];
newTotalLiquidity = newTotalLiquidity.add(uint256(currentDistribution));
}
}
function forceUpdateBMICoverStakingRewardMultiplier() public override {
uint256 rewardMultiplier;
if (whitelisted) {
rewardMultiplier = MINIMUM_REWARD;
uint256 liquidity = totalLiquidity;
uint256 coverTokens = totalCoverTokens;
if (coverTokens > 0 && liquidity > 0) {
rewardMultiplier = BASE_REWARD;
uint256 utilizationRatio = coverTokens.mul(PERCENTAGE_100).div(liquidity);
if (utilizationRatio < MODERATE_UTILIZATION_RATIO) {
rewardMultiplier = Math
.max(utilizationRatio, PRECISION)
.sub(PRECISION)
.mul(BASE_REWARD.sub(MINIMUM_REWARD))
.div(MODERATE_UTILIZATION_RATIO)
.add(MINIMUM_REWARD);
} else if (utilizationRatio > RISKY_UTILIZATION_RATIO) {
rewardMultiplier = MAXIMUM_REWARD
.sub(BASE_REWARD)
.mul(utilizationRatio.sub(RISKY_UTILIZATION_RATIO))
.div(PERCENTAGE_100.sub(RISKY_UTILIZATION_RATIO))
.add(BASE_REWARD);
}
}
}
rewardsGenerator.updatePolicyBookShare(rewardMultiplier.div(10**22)); // 5 decimal places or zero
}
function getNewCoverAndLiquidity()
public
view
override
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity)
{
newTotalLiquidity = totalLiquidity;
newTotalCoverTokens = totalCoverTokens;
uint256 lastEpoch = lastPremiumDistributionEpoch;
uint256 currentEpoch = _getPremiumDistributionEpoch();
if (currentEpoch > lastEpoch) {
(, , newTotalLiquidity) = _getPremiumsDistribution(lastEpoch, currentEpoch);
}
uint256 newDistributionEpoch = Math.min(getEpoch(block.timestamp), MAXIMUM_EPOCHS);
for (uint256 i = lastDistributionEpoch; i < newDistributionEpoch; i++) {
newTotalCoverTokens = newTotalCoverTokens.sub(epochAmounts[i]);
}
}
function getPolicyPrice(
uint256 _epochsNumber,
uint256 _coverTokens,
address _holder
)
public
view
override
returns (
uint256 totalSeconds,
uint256 totalPrice,
uint256 pricePercentage
)
{
require(_coverTokens >= MINUMUM_COVERAGE, "PB: Wrong cover");
require(_epochsNumber > 0 && _epochsNumber <= MAXIMUM_EPOCHS, "PB: Wrong epoch duration");
(uint256 newTotalCoverTokens, uint256 newTotalLiquidity) = getNewCoverAndLiquidity();
totalSeconds = secondsToEndCurrentEpoch().add(_epochsNumber.sub(1).mul(EPOCH_DURATION));
(totalPrice, pricePercentage) = policyQuote.getQuotePredefined(
totalSeconds,
_coverTokens,
newTotalCoverTokens,
newTotalLiquidity,
policyBookFacade.totalLeveragedLiquidity(),
policyBookFacade.safePricingModel()
);
///@notice commented this because of PB size when adding a new feature
/// and it is not used anymore ATM
// reduce premium by reward NFT locked by user
// uint256 _reductionMultiplier = nftStaking.getUserReductionMultiplier(_holder);
// if (_reductionMultiplier > 0) {
// totalPrice = totalPrice.sub(totalPrice.mul(_reductionMultiplier).div(PERCENTAGE_100));
// }
}
function buyPolicy(
address _buyer,
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens,
uint256 _distributorFee,
address _distributor
) external override returns (uint256, uint256) {
return
_buyPolicy(
BuyPolicyParameters(
_buyer,
_holder,
_epochsNumber,
_coverTokens,
_distributorFee,
_distributor
)
);
}
function _buyPolicy(BuyPolicyParameters memory parameters)
internal
onlyPolicyBookFacade
withPremiumsDistribution
updateBMICoverStakingReward
returns (uint256, uint256)
{
require(
!policyRegistry.isPolicyActive(parameters.holder, address(this)),
"PB: The holder already exists"
);
require(
claimingRegistry.canBuyNewPolicy(parameters.holder, address(this)),
"PB: Claim is pending"
);
updateEpochsInfo();
uint256 _totalCoverTokens = totalCoverTokens.add(parameters.coverTokens);
require(totalLiquidity >= _totalCoverTokens, "PB: Not enough liquidity");
(uint256 _totalSeconds, uint256 _totalPrice, uint256 pricePercentage) =
getPolicyPrice(parameters.epochsNumber, parameters.coverTokens, parameters.holder);
// Partners are rewarded with X% of the Premium, coming from the Protocol’s fee part.
// It's a part of 20% initially send to the Reinsurance pool
// (the other 80% of the Premium is a yield for coverage providers).
uint256 _distributorFeeAmount;
if (parameters.distributorFee > 0) {
_distributorFeeAmount = _totalPrice.mul(parameters.distributorFee).div(PERCENTAGE_100);
}
uint256 _reinsurancePrice =
_totalPrice.mul(PROTOCOL_PERCENTAGE).div(PERCENTAGE_100).sub(_distributorFeeAmount);
uint256 _price = _totalPrice.sub(_distributorFeeAmount);
_addPolicyHolder(parameters, _totalPrice, _reinsurancePrice);
totalCoverTokens = _totalCoverTokens;
if (_distributorFeeAmount > 0) {
stblToken.safeTransferFrom(
parameters.buyer,
parameters.distributor,
DecimalsConverter.convertFrom18(_distributorFeeAmount, stblDecimals)
);
}
stblToken.safeTransferFrom(
parameters.buyer,
address(capitalPool),
DecimalsConverter.convertFrom18(_price, stblDecimals)
);
_price = capitalPool.addPolicyHoldersHardSTBL(
DecimalsConverter.convertFrom18(_price, stblDecimals),
parameters.epochsNumber,
DecimalsConverter.convertFrom18(_reinsurancePrice, stblDecimals)
);
_addPolicyPremiumToDistributions(
_totalSeconds.add(VIRTUAL_EPOCHS * EPOCH_DURATION),
_price
);
policyRegistry.addPolicy(parameters.holder, parameters.coverTokens, _price, _totalSeconds);
emit PolicyBought(
parameters.holder,
parameters.coverTokens,
_totalPrice,
_totalCoverTokens,
parameters.distributor
);
return (_price, pricePercentage);
}
function _addPolicyHolder(
BuyPolicyParameters memory parameters,
uint256 _totalPrice,
uint256 _reinsurancePrice
) internal {
uint256 _currentEpochNumber = getEpoch(block.timestamp);
uint256 _endEpochNumber = _currentEpochNumber.add(parameters.epochsNumber.sub(1));
uint256 _virtualEndEpochNumber = _endEpochNumber + VIRTUAL_EPOCHS;
policyHolders[parameters.holder] = PolicyHolder(
parameters.coverTokens,
_currentEpochNumber,
_endEpochNumber,
_totalPrice,
_reinsurancePrice
);
epochAmounts[_virtualEndEpochNumber] = epochAmounts[_virtualEndEpochNumber].add(
parameters.coverTokens
);
}
/// @dev no need to cap epochs because the maximum policy duration is 1 year
function _addPolicyPremiumToDistributions(uint256 _totalSeconds, uint256 _distributedAmount)
internal
{
uint256 distributionEpochs = _totalSeconds.add(1).div(PREMIUM_DISTRIBUTION_EPOCH).max(1);
int256 distributedPerEpoch = int256(_distributedAmount.div(distributionEpochs));
uint256 nextEpoch = _getPremiumDistributionEpoch() + 1;
premiumDistributionDeltas[nextEpoch] += distributedPerEpoch;
premiumDistributionDeltas[nextEpoch + distributionEpochs] -= distributedPerEpoch;
}
function updateEpochsInfo() public override {
uint256 _lastDistributionEpoch = lastDistributionEpoch;
uint256 _newDistributionEpoch =
Math.min(getEpoch(block.timestamp), _lastDistributionEpoch + MAXIMUM_EPOCHS);
if (_lastDistributionEpoch < _newDistributionEpoch) {
uint256 _newTotalCoverTokens = totalCoverTokens;
for (uint256 i = _lastDistributionEpoch; i < _newDistributionEpoch; i++) {
_newTotalCoverTokens = _newTotalCoverTokens.sub(epochAmounts[i]);
delete epochAmounts[i];
}
lastDistributionEpoch = _newDistributionEpoch;
totalCoverTokens = _newTotalCoverTokens;
policyBookFacade.reevaluateProvidedLeverageStable();
emit CoverageChanged(_newTotalCoverTokens);
}
}
function secondsToEndCurrentEpoch() public view override returns (uint256) {
uint256 epochNumber = block.timestamp.sub(epochStartTime).div(EPOCH_DURATION) + 1;
return epochNumber.mul(EPOCH_DURATION).sub(block.timestamp.sub(epochStartTime));
}
function addLiquidityFor(address _liquidityHolderAddr, uint256 _liquidityAmount)
external
override
{
addLiquidity(_liquidityHolderAddr, _liquidityHolderAddr, _liquidityAmount, 0);
}
/// @notice adds liquidity on behalf of a sender
/// @dev only allowed to be called from its facade
/// @param _liquidityBuyerAddr, address of the one who pays
/// @param _liquidityHolderAddr, address of the one who hold
/// @param _liquidityAmount, uint256 amount to be added on behalf the sender
/// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake
function addLiquidity(
address _liquidityBuyerAddr,
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
)
public
override
onlyLiquidityAdders
withPremiumsDistribution
updateBMICoverStakingReward
returns (uint256)
{
if (_stakeSTBLAmount > 0) {
require(_stakeSTBLAmount <= _liquidityAmount, "PB: Wrong staking amount");
}
uint256 stblLiquidity = DecimalsConverter.convertFrom18(_liquidityAmount, stblDecimals);
require(stblLiquidity > 0, "PB: Liquidity amount is zero");
updateEpochsInfo();
/// @dev PBF already sent stable tokens
/// TODO: track PB sblIngress individually ? or only the _mint
if (_msgSender() != policyBookFabricAddress) {
stblToken.safeTransferFrom(_liquidityBuyerAddr, address(capitalPool), stblLiquidity);
}
capitalPool.addCoverageProvidersHardSTBL(stblLiquidity);
uint256 _liquidityAmountBMIX = convertSTBLToBMIX(_liquidityAmount);
_mint(_liquidityHolderAddr, _liquidityAmountBMIX);
uint256 liquidity = totalLiquidity.add(_liquidityAmount);
totalLiquidity = liquidity;
liquidityRegistry.tryToAddPolicyBook(_liquidityHolderAddr, address(this));
if (_stakeSTBLAmount > 0) {
bmiCoverStaking.stakeBMIXFrom(
_liquidityHolderAddr,
convertSTBLToBMIX(_stakeSTBLAmount)
);
}
emit LiquidityAdded(_liquidityHolderAddr, _liquidityAmount, liquidity);
return _liquidityAmountBMIX;
}
function getAvailableBMIXWithdrawableAmount(address _userAddr)
external
view
override
returns (uint256)
{
(uint256 newTotalCoverTokens, uint256 newTotalLiquidity) = getNewCoverAndLiquidity();
return
convertSTBLToBMIX(
Math.min(
newTotalLiquidity.sub(newTotalCoverTokens),
_getUserAvailableSTBL(_userAddr)
)
);
}
function _getUserAvailableSTBL(address _userAddr) internal view returns (uint256) {
uint256 availableSTBL =
convertBMIXToSTBL(
balanceOf(_userAddr).add(withdrawalsInfo[_userAddr].withdrawalAmount)
);
return availableSTBL;
}
function getWithdrawalStatus(address _userAddr)
public
view
override
returns (WithdrawalStatus)
{
uint256 readyToWithdrawDate = withdrawalsInfo[_userAddr].readyToWithdrawDate;
if (readyToWithdrawDate == 0) {
return WithdrawalStatus.NONE;
}
if (block.timestamp < readyToWithdrawDate) {
return WithdrawalStatus.PENDING;
}
if (
block.timestamp >= readyToWithdrawDate.add(READY_TO_WITHDRAW_PERIOD) &&
!withdrawalsInfo[_userAddr].withdrawalAllowed
) {
return WithdrawalStatus.EXPIRED;
}
return WithdrawalStatus.READY;
}
function requestWithdrawal(uint256 _tokensToWithdraw, address _user)
external
override
onlyPolicyBookFacade
withPremiumsDistribution
{
require(_tokensToWithdraw > 0, "PB: Amount is zero");
uint256 _stblTokensToWithdraw = convertBMIXToSTBL(_tokensToWithdraw);
uint256 _availableSTBLBalance = _getUserAvailableSTBL(_user);
require(_availableSTBLBalance >= _stblTokensToWithdraw, "PB: Wrong announced amount");
updateEpochsInfo();
require(
totalLiquidity >= totalCoverTokens.add(_stblTokensToWithdraw),
"PB: Not enough free liquidity"
);
_lockTokens(_user, _tokensToWithdraw);
uint256 _readyToWithdrawDate = block.timestamp.add(WITHDRAWAL_PERIOD);
withdrawalsInfo[_user] = WithdrawalInfo(_tokensToWithdraw, _readyToWithdrawDate, false);
emit WithdrawalRequested(_user, _tokensToWithdraw, _readyToWithdrawDate);
}
function _lockTokens(address _userAddr, uint256 _neededTokensToLock) internal {
uint256 _currentLockedTokens = withdrawalsInfo[_userAddr].withdrawalAmount;
if (_currentLockedTokens > _neededTokensToLock) {
this.transfer(_userAddr, _currentLockedTokens - _neededTokensToLock);
} else if (_currentLockedTokens < _neededTokensToLock) {
this.transferFrom(
_userAddr,
address(this),
_neededTokensToLock - _currentLockedTokens
);
}
}
function unlockTokens() external override {
uint256 _lockedAmount = withdrawalsInfo[_msgSender()].withdrawalAmount;
require(_lockedAmount > 0, "PB: Amount is zero");
this.transfer(_msgSender(), _lockedAmount);
delete withdrawalsInfo[_msgSender()];
liquidityRegistry.removeExpiredWithdrawalRequest(_msgSender(), address(this));
}
function withdrawLiquidity(address sender)
external
override
onlyPolicyBookFacade
withPremiumsDistribution
updateBMICoverStakingReward
returns (uint256)
{
require(
getWithdrawalStatus(sender) == WithdrawalStatus.READY,
"PB: Withdrawal is not ready"
);
updateEpochsInfo();
uint256 liquidity = totalLiquidity;
uint256 _currentWithdrawalAmount = withdrawalsInfo[sender].withdrawalAmount;
uint256 _tokensToWithdraw =
Math.min(_currentWithdrawalAmount, convertSTBLToBMIX(liquidity.sub(totalCoverTokens)));
uint256 _stblTokensToWithdraw = convertBMIXToSTBL(_tokensToWithdraw);
capitalPool.withdrawLiquidity(
sender,
DecimalsConverter.convertFrom18(_stblTokensToWithdraw, stblDecimals),
false
);
_burn(address(this), _tokensToWithdraw);
liquidity = liquidity.sub(_stblTokensToWithdraw);
_currentWithdrawalAmount = _currentWithdrawalAmount.sub(_tokensToWithdraw);
if (_currentWithdrawalAmount == 0) {
delete withdrawalsInfo[sender];
liquidityRegistry.tryToRemovePolicyBook(sender, address(this));
} else {
withdrawalsInfo[sender].withdrawalAllowed = true;
withdrawalsInfo[sender].withdrawalAmount = _currentWithdrawalAmount;
}
totalLiquidity = liquidity;
emit LiquidityWithdrawn(sender, _stblTokensToWithdraw, liquidity);
return _tokensToWithdraw;
}
function updateLiquidity(uint256 _lostLiquidity) external override onlyCapitalPool {
updateEpochsInfo();
uint256 _newLiquidity = totalLiquidity.sub(_lostLiquidity);
totalLiquidity = _newLiquidity;
emit LiquidityWithdrawn(_msgSender(), _lostLiquidity, _newLiquidity);
}
/// @notice returns APY% with 10**5 precision
function getAPY() public view override returns (uint256) {
uint256 lastEpoch = lastPremiumDistributionEpoch;
uint256 currentEpoch = _getPremiumDistributionEpoch();
int256 premiumDistributionAmount = lastPremiumDistributionAmount;
// simulates addLiquidity()
if (currentEpoch > lastEpoch) {
(premiumDistributionAmount, currentEpoch, ) = _getPremiumsDistribution(
lastEpoch,
currentEpoch
);
}
premiumDistributionAmount += premiumDistributionDeltas[currentEpoch + 1];
return
uint256(premiumDistributionAmount).mul(365).mul(10**7).div(
convertBMIXToSTBL(totalSupply()).add(APY_TOKENS)
);
}
function userStats(address _user) external view override returns (PolicyHolder memory) {
return policyHolders[_user];
}
/// @notice _annualProfitYields is multiplied by 10**5
/// @notice _annualInsuranceCost is calculated for 1000 STBL cover (or _maxCapacities if it is less)
/// @notice _bmiXRatio is multiplied by 10**18. To get STBL representation,
/// multiply BMIX tokens by this value and then divide by 10**18
function numberStats()
external
view
override
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
)
{
uint256 newTotalCoverTokens;
(newTotalCoverTokens, _totalSTBLLiquidity) = getNewCoverAndLiquidity();
_maxCapacities = _totalSTBLLiquidity - newTotalCoverTokens;
_stakedSTBL = rewardsGenerator.getStakedPolicyBookSTBL(address(this));
_annualProfitYields = getAPY().add(bmiCoverStakingView.getPolicyBookAPY(address(this)));
uint256 possibleCoverage = Math.min(ANNUAL_COVERAGE_TOKENS, _maxCapacities);
_totalLeveragedLiquidity = policyBookFacade.totalLeveragedLiquidity();
if (possibleCoverage >= MINUMUM_COVERAGE) {
(_annualInsuranceCost, ) = policyQuote.getQuotePredefined(
SECONDS_IN_THE_YEAR,
possibleCoverage,
newTotalCoverTokens,
_totalSTBLLiquidity,
_totalLeveragedLiquidity,
policyBookFacade.safePricingModel()
);
_annualInsuranceCost = _annualInsuranceCost
.mul(ANNUAL_COVERAGE_TOKENS.mul(PRECISION).div(possibleCoverage))
.div(PRECISION)
.div(10);
}
_bmiXRatio = convertBMIXToSTBL(10**18);
}
function info()
external
view
override
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
)
{
return (symbol(), insuranceContractAddress, contractType, whitelisted);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.5 <0.8.0;
import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20Upgradeable.sol";
import "../../interfaces/tokens/erc20permit-upgradeable/IERC20PermitUpgradeable.sol";
import "@openzeppelin/contracts-upgradeable/utils/CountersUpgradeable.sol";
import "./EIP712Upgradeable.sol";
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* COPIED FROM https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/tree/release-v3.4/contracts/drafts
* @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
abstract contract ERC20PermitUpgradeable is
Initializable,
ERC20Upgradeable,
IERC20PermitUpgradeable,
EIP712Upgradeable
{
using CountersUpgradeable for CountersUpgradeable.Counter;
mapping(address => CountersUpgradeable.Counter) private _nonces;
// solhint-disable-next-line var-name-mixedcase
bytes32 private _PERMIT_TYPEHASH;
/**
* @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`.
*
* It's a good idea to use the same `name` that is defined as the ERC20 token name.
*/
function __ERC20Permit_init(string memory name) internal initializer {
__Context_init_unchained();
__EIP712_init_unchained(name, "1");
__ERC20Permit_init_unchained(name);
}
function __ERC20Permit_init_unchained(string memory name) internal initializer {
_PERMIT_TYPEHASH = keccak256(
"Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"
);
}
/**
* @dev See {IERC20Permit-permit}.
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) public virtual override {
// solhint-disable-next-line not-rely-on-time
require(block.timestamp <= deadline, "ERC20Permit: expired deadline");
bytes32 structHash =
keccak256(
abi.encode(
_PERMIT_TYPEHASH,
owner,
spender,
value,
_nonces[owner].current(),
deadline
)
);
bytes32 hash = _hashTypedDataV4(structHash);
address signer = recover(hash, v, r, s);
require(signer == owner, "ERC20Permit: invalid signature");
_nonces[owner].increment();
_approve(owner, spender, value);
}
/**
* @dev Overload of {ECDSA-recover-bytes32-bytes-} that receives the `v`,
* `r` and `s` signature fields separately.
*/
function recover(
bytes32 hash,
uint8 v,
bytes32 r,
bytes32 s
) internal pure returns (address) {
// 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.
require(
uint256(s) <= 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
"ECDSA: invalid signature 's' value"
);
require(v == 27 || v == 28, "ECDSA: invalid signature 'v' value");
// If the signature is valid (and not malleable), return the signer address
address signer = ecrecover(hash, v, r, s);
require(signer != address(0), "ECDSA: invalid signature");
return signer;
}
/**
* @dev See {IERC20Permit-nonces}.
*/
function nonces(address owner) public view override returns (uint256) {
return _nonces[owner].current();
}
/**
* @dev See {IERC20Permit-DOMAIN_SEPARATOR}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view override returns (bytes32) {
return _domainSeparatorV4();
}
uint256[49] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol";
/**
* COPIED FROM https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/tree/release-v3.4/contracts/drafts
* @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data.
*
* The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible,
* thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding
* they need in their contracts using a combination of `abi.encode` and `keccak256`.
*
* This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding
* scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA
* ({_hashTypedDataV4}).
*
* The implementation of the domain separator was designed to be as efficient as possible while still properly updating
* the chain id to protect against replay attacks on an eventual fork of the chain.
*
* NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method
* https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask].
*/
abstract contract EIP712Upgradeable is Initializable {
/* solhint-disable var-name-mixedcase */
bytes32 private _HASHED_NAME;
bytes32 private _HASHED_VERSION;
bytes32 private constant _TYPE_HASH =
keccak256(
"EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"
);
/* solhint-enable var-name-mixedcase */
/**
* @dev Initializes the domain separator and parameter caches.
*
* The meaning of `name` and `version` is specified in
* https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]:
*
* - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol.
* - `version`: the current major version of the signing domain.
*
* NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart
* contract upgrade].
*/
function __EIP712_init(string memory name, string memory version) internal initializer {
__EIP712_init_unchained(name, version);
}
function __EIP712_init_unchained(string memory name, string memory version)
internal
initializer
{
bytes32 hashedName = keccak256(bytes(name));
bytes32 hashedVersion = keccak256(bytes(version));
_HASHED_NAME = hashedName;
_HASHED_VERSION = hashedVersion;
}
/**
* @dev Returns the domain separator for the current chain.
*/
function _domainSeparatorV4() internal view returns (bytes32) {
return _buildDomainSeparator(_TYPE_HASH, _EIP712NameHash(), _EIP712VersionHash());
}
function _buildDomainSeparator(
bytes32 typeHash,
bytes32 name,
bytes32 version
) private view returns (bytes32) {
return keccak256(abi.encode(typeHash, name, version, _getChainId(), address(this)));
}
/**
* @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this
* function returns the hash of the fully encoded EIP712 message for this domain.
*
* This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example:
*
* ```solidity
* bytes32 digest = _hashTypedDataV4(keccak256(abi.encode(
* keccak256("Mail(address to,string contents)"),
* mailTo,
* keccak256(bytes(mailContents))
* )));
* address signer = ECDSA.recover(digest, signature);
* ```
*/
function _hashTypedDataV4(bytes32 structHash) internal view returns (bytes32) {
return keccak256(abi.encodePacked("\x19\x01", _domainSeparatorV4(), structHash));
}
function _getChainId() private view returns (uint256 chainId) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
// solhint-disable-next-line no-inline-assembly
assembly {
chainId := chainid()
}
}
/**
* @dev The hash of the name parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712NameHash() internal view virtual returns (bytes32) {
return _HASHED_NAME;
}
/**
* @dev The hash of the version parameter for the EIP712 domain.
*
* NOTE: This function reads from storage by default, but can be redefined to return a constant value if gas costs
* are a concern.
*/
function _EIP712VersionHash() internal view virtual returns (bytes32) {
return _HASHED_VERSION;
}
uint256[50] private __gap;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "@openzeppelin/contracts/math/SafeMath.sol";
/// @notice the intention of this library is to be able to easily convert
/// one amount of tokens with N decimal places
/// to another amount with M decimal places
library DecimalsConverter {
using SafeMath for uint256;
function convert(
uint256 amount,
uint256 baseDecimals,
uint256 destinationDecimals
) internal pure returns (uint256) {
if (baseDecimals > destinationDecimals) {
amount = amount.div(10**(baseDecimals - destinationDecimals));
} else if (baseDecimals < destinationDecimals) {
amount = amount.mul(10**(destinationDecimals - baseDecimals));
}
return amount;
}
function convertTo18(uint256 amount, uint256 baseDecimals) internal pure returns (uint256) {
return convert(amount, baseDecimals, 18);
}
function convertFrom18(uint256 amount, uint256 destinationDecimals)
internal
pure
returns (uint256)
{
return convert(amount, 18, destinationDecimals);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* COPIED FROM https://github.com/OpenZeppelin/openzeppelin-contracts-upgradeable/tree/release-v3.4/contracts/drafts
* @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in
* https://eips.ethereum.org/EIPS/eip-2612[EIP-2612].
*
* Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by
* presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't
* need to send a transaction, and thus is not required to hold Ether at all.
*/
interface IERC20PermitUpgradeable {
/**
* @dev Sets `value` as the allowance of `spender` over `owner`'s tokens,
* given `owner`'s signed approval.
*
* IMPORTANT: The same issues {IERC20-approve} has related to transaction
* ordering also apply here.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `deadline` must be a timestamp in the future.
* - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner`
* over the EIP712-formatted function arguments.
* - the signature must use ``owner``'s current nonce (see {nonces}).
*
* For more information on the signature format, see the
* https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP
* section].
*/
function permit(
address owner,
address spender,
uint256 value,
uint256 deadline,
uint8 v,
bytes32 r,
bytes32 s
) external;
/**
* @dev Returns the current nonce for `owner`. This value must be
* included whenever a signature is generated for {permit}.
*
* Every successful call to {permit} increases ``owner``'s nonce by one. This
* prevents a signature from being used multiple times.
*/
function nonces(address owner) external view returns (uint256);
/**
* @dev Returns the domain separator used in the encoding of the signature for `permit`, as defined by {EIP712}.
*/
// solhint-disable-next-line func-name-mixedcase
function DOMAIN_SEPARATOR() external view returns (bytes32);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IRewardsGenerator {
struct PolicyBookRewardInfo {
uint256 rewardMultiplier; // includes 5 decimal places
uint256 totalStaked;
uint256 lastUpdateBlock;
uint256 lastCumulativeSum; // includes 100 percentage
uint256 cumulativeReward; // includes 100 percentage
}
struct StakeRewardInfo {
uint256 lastCumulativeSum; // includes 100 percentage
uint256 cumulativeReward;
uint256 stakeAmount;
}
/// @notice this function is called every time policybook's STBL to bmiX rate changes
function updatePolicyBookShare(uint256 newRewardMultiplier) external;
/// @notice aggregates specified nfts into a single one
function aggregate(
address policyBookAddress,
uint256[] calldata nftIndexes,
uint256 nftIndexTo
) external;
/// @notice migrates stake from the LegacyRewardsGenerator (will be called once for each user)
/// the rewards multipliers must be set in advance
function migrationStake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount,
uint256 currentReward
) external;
/// @notice informs generator of stake (rewards)
function stake(
address policyBookAddress,
uint256 nftIndex,
uint256 amount
) external;
/// @notice returns policybook's APY multiplied by 10**5
function getPolicyBookAPY(address policyBookAddress) external view returns (uint256);
/// @notice returns policybook's RewardMultiplier multiplied by 10**5
function getPolicyBookRewardMultiplier(address policyBookAddress)
external
view
returns (uint256);
/// @dev returns PolicyBook reward per block multiplied by 10**25
function getPolicyBookRewardPerBlock(address policyBookAddress)
external
view
returns (uint256);
/// @notice returns PolicyBook's staked STBL
function getStakedPolicyBookSTBL(address policyBookAddress) external view returns (uint256);
/// @notice returns NFT's staked STBL
function getStakedNFTSTBL(uint256 nftIndex) external view returns (uint256);
/// @notice returns a reward of NFT
function getReward(address policyBookAddress, uint256 nftIndex)
external
view
returns (uint256);
/// @notice informs generator of withdrawal (all funds)
function withdrawFunds(address policyBookAddress, uint256 nftIndex) external returns (uint256);
/// @notice informs generator of withdrawal (rewards)
function withdrawReward(address policyBookAddress, uint256 nftIndex)
external
returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
interface IPolicyRegistry {
struct PolicyInfo {
uint256 coverAmount;
uint256 premium;
uint256 startTime;
uint256 endTime;
}
struct PolicyUserInfo {
string symbol;
address insuredContract;
IPolicyBookFabric.ContractType contractType;
uint256 coverTokens;
uint256 startTime;
uint256 endTime;
uint256 paid;
}
function STILL_CLAIMABLE_FOR() external view returns (uint256);
/// @notice Returns the number of the policy for the user, access: ANY
/// @param _userAddr Policy holder address
/// @return the number of police in the array
function getPoliciesLength(address _userAddr) external view returns (uint256);
/// @notice Shows whether the user has a policy, access: ANY
/// @param _userAddr Policy holder address
/// @param _policyBookAddr Address of policy book
/// @return true if user has policy in specific policy book
function policyExists(address _userAddr, address _policyBookAddr) external view returns (bool);
/// @notice Returns information about current policy, access: ANY
/// @param _userAddr Policy holder address
/// @param _policyBookAddr Address of policy book
/// @return true if user has active policy in specific policy book
function isPolicyActive(address _userAddr, address _policyBookAddr)
external
view
returns (bool);
/// @notice returns current policy start time or zero
function policyStartTime(address _userAddr, address _policyBookAddr)
external
view
returns (uint256);
/// @notice returns current policy end time or zero
function policyEndTime(address _userAddr, address _policyBookAddr)
external
view
returns (uint256);
/// @notice Returns the array of the policy itself , access: ANY
/// @param _userAddr Policy holder address
/// @param _isActive If true, then returns an array with information about active policies, if false, about inactive
/// @return _policiesCount is the number of police in the array
/// @return _policyBooksArr is the array of policy books addresses
/// @return _policies is the array of policies
/// @return _policyStatuses parameter will show which button to display on the dashboard
function getPoliciesInfo(
address _userAddr,
bool _isActive,
uint256 _offset,
uint256 _limit
)
external
view
returns (
uint256 _policiesCount,
address[] memory _policyBooksArr,
PolicyInfo[] memory _policies,
IClaimingRegistry.ClaimStatus[] memory _policyStatuses
);
/// @notice Getting stats from users of policy books, access: ANY
function getUsersInfo(address[] calldata _users, address[] calldata _policyBooks)
external
view
returns (PolicyUserInfo[] memory _stats);
function getPoliciesArr(address _userAddr) external view returns (address[] memory _arr);
/// @notice Adds a new policy to the list , access: ONLY POLICY BOOKS
/// @param _userAddr is the user's address
/// @param _coverAmount is the number of insured tokens
/// @param _premium is the name of PolicyBook
/// @param _durationDays is the number of days for which the insured
function addPolicy(
address _userAddr,
uint256 _coverAmount,
uint256 _premium,
uint256 _durationDays
) external;
/// @notice Removes the policy book from the list, access: ONLY POLICY BOOKS
/// @param _userAddr is the user's address
function removePolicy(address _userAddr) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyQuote {
/// @notice Let user to calculate policy cost in stable coin, access: ANY
/// @param _durationSeconds is number of seconds to cover
/// @param _tokens is a number of tokens to cover
/// @param _totalCoverTokens is a number of covered tokens
/// @param _totalLiquidity is a liquidity amount
/// @param _totalLeveragedLiquidity is a totale deployed leverage to the pool
/// @param _safePricingModel the pricing model configured for this bool safe or risk
/// @return amount of stable coin policy costs
function getQuotePredefined(
uint256 _durationSeconds,
uint256 _tokens,
uint256 _totalCoverTokens,
uint256 _totalLiquidity,
uint256 _totalLeveragedLiquidity,
bool _safePricingModel
) external view returns (uint256, uint256);
/// @notice Let user to calculate policy cost in stable coin, access: ANY
/// @param _durationSeconds is number of seconds to cover
/// @param _tokens is number of tokens to cover
/// @param _policyBookAddr is address of policy book
/// @return amount of stable coin policy costs
function getQuote(
uint256 _durationSeconds,
uint256 _tokens,
address _policyBookAddr
) external view returns (uint256);
/// @notice setup all pricing model varlues
///@param _highRiskRiskyAssetThresholdPercentage URRp Utilization ration for pricing model when the assets is considered risky, %
///@param _lowRiskRiskyAssetThresholdPercentage URRp Utilization ration for pricing model when the assets is not considered risky, %
///@param _highRiskMinimumCostPercentage MC minimum cost of cover (Premium) when the assets is considered risky, %;
///@param _lowRiskMinimumCostPercentage MC minimum cost of cover (Premium), when the assets is not considered risky, %
///@param _minimumInsuranceCost minimum cost of insurance (Premium) , (10**18)
///@param _lowRiskMaxPercentPremiumCost TMCI target maximum cost of cover when the asset is not considered risky (Premium)
///@param _lowRiskMaxPercentPremiumCost100Utilization MCI not risky
///@param _highRiskMaxPercentPremiumCost TMCI target maximum cost of cover when the asset is considered risky (Premium)
///@param _highRiskMaxPercentPremiumCost100Utilization MCI risky
function setupPricingModel(
uint256 _highRiskRiskyAssetThresholdPercentage,
uint256 _lowRiskRiskyAssetThresholdPercentage,
uint256 _highRiskMinimumCostPercentage,
uint256 _lowRiskMinimumCostPercentage,
uint256 _minimumInsuranceCost,
uint256 _lowRiskMaxPercentPremiumCost,
uint256 _lowRiskMaxPercentPremiumCost100Utilization,
uint256 _highRiskMaxPercentPremiumCost,
uint256 _highRiskMaxPercentPremiumCost100Utilization
) external;
///@notice return min ur under the current pricing model
///@param _safePricingModel pricing model of the pool wethere it is safe or risky model
function getMINUR(bool _safePricingModel) external view returns (uint256 _minUR);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "./IPolicyBook.sol";
import "./ILeveragePortfolio.sol";
interface IPolicyBookFacade {
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicy(uint256 _epochsNumber, uint256 _coverTokens) external;
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
function buyPolicyFor(
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens
) external;
function policyBook() external view returns (IPolicyBook);
function userLiquidity(address account) external view returns (uint256);
/// @notice virtual funds deployed by reinsurance pool
function VUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by reinsurance pool
function LUreinsurnacePool() external view returns (uint256);
/// @notice leverage funds deployed by user leverage pool
function LUuserLeveragePool(address userLeveragePool) external view returns (uint256);
/// @notice total leverage funds deployed to the pool sum of (VUreinsurnacePool,LUreinsurnacePool,LUuserLeveragePool)
function totalLeveragedLiquidity() external view returns (uint256);
function userleveragedMPL() external view returns (uint256);
function reinsurancePoolMPL() external view returns (uint256);
function rebalancingThreshold() external view returns (uint256);
function safePricingModel() external view returns (bool);
/// @notice policyBookFacade initializer
/// @param pbProxy polciybook address upgreadable cotnract.
function __PolicyBookFacade_init(
address pbProxy,
address liquidityProvider,
uint256 initialDeposit
) external;
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributor(
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @param _buyer who is buying the coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicyFromDistributorFor(
address _buyer,
uint256 _epochsNumber,
uint256 _coverTokens,
address _distributor
) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidity(uint256 _liquidityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _user the one taht add liquidity
/// @param _liquidityAmount is amount of stable coin tokens to secure
function addLiquidityFromDistributorFor(address _user, uint256 _liquidityAmount) external;
function addLiquidityAndStakeFor(
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external;
/// @notice Let user to add liquidity by supplying stable coin and stake it,
/// @dev access: ANY
function addLiquidityAndStake(uint256 _liquidityAmount, uint256 _stakeSTBLAmount) external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity() external;
/// @notice deploy leverage funds (RP lStable, ULP lStable)
/// @param deployedAmount uint256 the deployed amount to be added or substracted from the total liquidity
/// @param leveragePool whether user leverage or reinsurance leverage
function deployLeverageFundsAfterRebalance(
uint256 deployedAmount,
ILeveragePortfolio.LeveragePortfolio leveragePool
) external;
/// @notice deploy virtual funds (RP vStable)
/// @param deployedAmount uint256 the deployed amount to be added to the liquidity
function deployVirtualFundsAfterRebalance(uint256 deployedAmount) external;
///@dev in case ur changed of the pools by commit a claim or policy expired
function reevaluateProvidedLeverageStable() external;
/// @notice set the MPL for the user leverage and the reinsurance leverage
/// @param _userLeverageMPL uint256 value of the user leverage MPL
/// @param _reinsuranceLeverageMPL uint256 value of the reinsurance leverage MPL
function setMPLs(uint256 _userLeverageMPL, uint256 _reinsuranceLeverageMPL) external;
/// @notice sets the rebalancing threshold value
/// @param _newRebalancingThreshold uint256 rebalancing threshhold value
function setRebalancingThreshold(uint256 _newRebalancingThreshold) external;
/// @notice sets the rebalancing threshold value
/// @param _safePricingModel bool is pricing model safe (true) or not (false)
function setSafePricingModel(bool _safePricingModel) external;
/// @notice returns how many BMI tokens needs to approve in order to submit a claim
function getClaimApprovalAmount(address user) external view returns (uint256);
/// @notice upserts a withdraw request
/// @dev prevents adding a request if an already pending or ready request is open.
/// @param _tokensToWithdraw uint256 amount of tokens to withdraw
function requestWithdrawal(uint256 _tokensToWithdraw) external;
function listUserLeveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _userLeveragePools);
function countUserLeveragePools() external view returns (uint256);
/// @notice get utilization rate of the pool on chain
function getUtilizationRatioPercentage(bool withLeverage) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface IPolicyBookFabric {
enum ContractType {CONTRACT, STABLECOIN, SERVICE, EXCHANGE, VARIOUS}
/// @notice Create new Policy Book contract, access: ANY
/// @param _contract is Contract to create policy book for
/// @param _contractType is Contract to create policy book for
/// @param _description is bmiXCover token desription for this policy book
/// @param _projectSymbol replaces x in bmiXCover token symbol
/// @param _initialDeposit is an amount user deposits on creation (addLiquidity())
/// @return _policyBook is address of created contract
function create(
address _contract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol,
uint256 _initialDeposit,
address _shieldMiningToken
) external returns (address);
function createLeveragePools(
address _insuranceContract,
ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
import "./IClaimingRegistry.sol";
import "./IPolicyBookFacade.sol";
interface IPolicyBook {
enum WithdrawalStatus {NONE, PENDING, READY, EXPIRED}
struct PolicyHolder {
uint256 coverTokens;
uint256 startEpochNumber;
uint256 endEpochNumber;
uint256 paid;
uint256 reinsurancePrice;
}
struct WithdrawalInfo {
uint256 withdrawalAmount;
uint256 readyToWithdrawDate;
bool withdrawalAllowed;
}
struct BuyPolicyParameters {
address buyer;
address holder;
uint256 epochsNumber;
uint256 coverTokens;
uint256 distributorFee;
address distributor;
}
function policyHolders(address _holder)
external
view
returns (
uint256,
uint256,
uint256,
uint256,
uint256
);
function policyBookFacade() external view returns (IPolicyBookFacade);
function setPolicyBookFacade(address _policyBookFacade) external;
function EPOCH_DURATION() external view returns (uint256);
function stblDecimals() external view returns (uint256);
function READY_TO_WITHDRAW_PERIOD() external view returns (uint256);
function whitelisted() external view returns (bool);
function epochStartTime() external view returns (uint256);
// @TODO: should we let DAO to change contract address?
/// @notice Returns address of contract this PolicyBook covers, access: ANY
/// @return _contract is address of covered contract
function insuranceContractAddress() external view returns (address _contract);
/// @notice Returns type of contract this PolicyBook covers, access: ANY
/// @return _type is type of contract
function contractType() external view returns (IPolicyBookFabric.ContractType _type);
function totalLiquidity() external view returns (uint256);
function totalCoverTokens() external view returns (uint256);
// /// @notice return MPL for user leverage pool
// function userleveragedMPL() external view returns (uint256);
// /// @notice return MPL for reinsurance pool
// function reinsurancePoolMPL() external view returns (uint256);
// function bmiRewardMultiplier() external view returns (uint256);
function withdrawalsInfo(address _userAddr)
external
view
returns (
uint256 _withdrawalAmount,
uint256 _readyToWithdrawDate,
bool _withdrawalAllowed
);
function __PolicyBook_init(
address _insuranceContract,
IPolicyBookFabric.ContractType _contractType,
string calldata _description,
string calldata _projectSymbol
) external;
function whitelist(bool _whitelisted) external;
function getEpoch(uint256 time) external view returns (uint256);
/// @notice get STBL equivalent
function convertBMIXToSTBL(uint256 _amount) external view returns (uint256);
/// @notice get BMIX equivalent
function convertSTBLToBMIX(uint256 _amount) external view returns (uint256);
/// @notice submits new claim of the policy book
function submitClaimAndInitializeVoting(string calldata evidenceURI) external;
/// @notice submits new appeal claim of the policy book
function submitAppealAndInitializeVoting(string calldata evidenceURI) external;
/// @notice updates info on claim acceptance
function commitClaim(
address claimer,
uint256 claimAmount,
uint256 claimEndTime,
IClaimingRegistry.ClaimStatus status
) external;
/// @notice forces an update of RewardsGenerator multiplier
function forceUpdateBMICoverStakingRewardMultiplier() external;
/// @notice function to get precise current cover and liquidity
function getNewCoverAndLiquidity()
external
view
returns (uint256 newTotalCoverTokens, uint256 newTotalLiquidity);
/// @notice view function to get precise policy price
/// @param _epochsNumber is number of epochs to cover
/// @param _coverTokens is number of tokens to cover
/// @param _buyer address of the user who buy the policy
/// @return totalSeconds is number of seconds to cover
/// @return totalPrice is the policy price which will pay by the buyer
function getPolicyPrice(
uint256 _epochsNumber,
uint256 _coverTokens,
address _buyer
)
external
view
returns (
uint256 totalSeconds,
uint256 totalPrice,
uint256 pricePercentage
);
/// @notice Let user to buy policy by supplying stable coin, access: ANY
/// @param _buyer who is transferring funds
/// @param _holder who owns coverage
/// @param _epochsNumber period policy will cover
/// @param _coverTokens amount paid for the coverage
/// @param _distributorFee distributor fee (commission). It can't be greater than PROTOCOL_PERCENTAGE
/// @param _distributor if it was sold buy a whitelisted distributor, it is distributor address to receive fee (commission)
function buyPolicy(
address _buyer,
address _holder,
uint256 _epochsNumber,
uint256 _coverTokens,
uint256 _distributorFee,
address _distributor
) external returns (uint256, uint256);
function updateEpochsInfo() external;
function secondsToEndCurrentEpoch() external view returns (uint256);
/// @notice Let eligible contracts add liqiudity for another user by supplying stable coin
/// @param _liquidityHolderAddr is address of address to assign cover
/// @param _liqudityAmount is amount of stable coin tokens to secure
function addLiquidityFor(address _liquidityHolderAddr, uint256 _liqudityAmount) external;
/// @notice Let user to add liquidity by supplying stable coin, access: ANY
/// @param _liquidityBuyerAddr address the one that transfer funds
/// @param _liquidityHolderAddr address the one that owns liquidity
/// @param _liquidityAmount uint256 amount to be added on behalf the sender
/// @param _stakeSTBLAmount uint256 the staked amount if add liq and stake
function addLiquidity(
address _liquidityBuyerAddr,
address _liquidityHolderAddr,
uint256 _liquidityAmount,
uint256 _stakeSTBLAmount
) external returns (uint256);
function getAvailableBMIXWithdrawableAmount(address _userAddr) external view returns (uint256);
function getWithdrawalStatus(address _userAddr) external view returns (WithdrawalStatus);
function requestWithdrawal(uint256 _tokensToWithdraw, address _user) external;
// function requestWithdrawalWithPermit(
// uint256 _tokensToWithdraw,
// uint8 _v,
// bytes32 _r,
// bytes32 _s
// ) external;
function unlockTokens() external;
/// @notice Let user to withdraw deposited liqiudity, access: ANY
function withdrawLiquidity(address sender) external returns (uint256);
///@notice for doing defi hard rebalancing, access: policyBookFacade
function updateLiquidity(uint256 _newLiquidity) external;
function getAPY() external view returns (uint256);
/// @notice Getting user stats, access: ANY
function userStats(address _user) external view returns (PolicyHolder memory);
/// @notice Getting number stats, access: ANY
/// @return _maxCapacities is a max token amount that a user can buy
/// @return _totalSTBLLiquidity is PolicyBook's liquidity
/// @return _totalLeveragedLiquidity is PolicyBook's leveraged liquidity
/// @return _stakedSTBL is how much stable coin are staked on this PolicyBook
/// @return _annualProfitYields is its APY
/// @return _annualInsuranceCost is percentage of cover tokens that is required to be paid for 1 year of insurance
function numberStats()
external
view
returns (
uint256 _maxCapacities,
uint256 _totalSTBLLiquidity,
uint256 _totalLeveragedLiquidity,
uint256 _stakedSTBL,
uint256 _annualProfitYields,
uint256 _annualInsuranceCost,
uint256 _bmiXRatio
);
/// @notice Getting info, access: ANY
/// @return _symbol is the symbol of PolicyBook (bmiXCover)
/// @return _insuredContract is an addres of insured contract
/// @return _contractType is a type of insured contract
/// @return _whitelisted is a state of whitelisting
function info()
external
view
returns (
string memory _symbol,
address _insuredContract,
IPolicyBookFabric.ContractType _contractType,
bool _whitelisted
);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface INFTStaking {
/// @notice let user lock NFT, access: ANY
/// @param _nftId is the NFT id which locked
function lockNFT(uint256 _nftId) external;
/// @notice let user unlcok NFT if enabled, access: ANY
/// @param _nftId is the NFT id which unlocked
function unlockNFT(uint256 _nftId) external;
/// @notice get user reduction multiplier for policy premium, access: PolicyBook
/// @param _user is the user who locked NFT
/// @return reduction multiplier of locked NFT by user
function getUserReductionMultiplier(address _user) external view returns (uint256);
/// @notice return enabledlockingNFTs state, access: ANY
/// if true user can't unlock NFT and vice versa
function enabledlockingNFTs() external view returns (bool);
/// @notice To enable/disable locking of the NFTs
/// @param _enabledlockingNFTs is a state for enable/disbale locking of the NFT
function enableLockingNFTs(bool _enabledlockingNFTs) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface ILiquidityRegistry {
struct LiquidityInfo {
address policyBookAddr;
uint256 lockedAmount;
uint256 availableAmount;
uint256 bmiXRatio; // multiply availableAmount by this num to get stable coin
}
struct WithdrawalRequestInfo {
address policyBookAddr;
uint256 requestAmount;
uint256 requestSTBLAmount;
uint256 availableLiquidity;
uint256 readyToWithdrawDate;
uint256 endWithdrawDate;
}
struct WithdrawalSetInfo {
address policyBookAddr;
uint256 requestAmount;
uint256 requestSTBLAmount;
uint256 availableSTBLAmount;
}
function tryToAddPolicyBook(address _userAddr, address _policyBookAddr) external;
function tryToRemovePolicyBook(address _userAddr, address _policyBookAddr) external;
function removeExpiredWithdrawalRequest(address _userAddr, address _policyBookAddr) external;
function getPolicyBooksArrLength(address _userAddr) external view returns (uint256);
function getPolicyBooksArr(address _userAddr)
external
view
returns (address[] memory _resultArr);
function getLiquidityInfos(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (LiquidityInfo[] memory _resultArr);
function getWithdrawalRequests(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (uint256 _arrLength, WithdrawalRequestInfo[] memory _resultArr);
function getWithdrawalSet(
address _userAddr,
uint256 _offset,
uint256 _limit
) external view returns (uint256 _arrLength, WithdrawalSetInfo[] memory _resultArr);
function registerWithdrawl(address _policyBook, address _users) external;
function getAllPendingWithdrawalRequestsAmount()
external
returns (uint256 _totalWithdrawlAmount);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface ILiquidityMining {
struct TeamDetails {
string teamName;
address referralLink;
uint256 membersNumber;
uint256 totalStakedAmount;
uint256 totalReward;
}
struct UserInfo {
address userAddr;
string teamName;
uint256 stakedAmount;
uint256 mainNFT; // 0 or NFT index if available
uint256 platinumNFT; // 0 or NFT index if available
}
struct UserRewardsInfo {
string teamName;
uint256 totalBMIReward; // total BMI reward
uint256 availableBMIReward; // current claimable BMI reward
uint256 incomingPeriods; // how many month are incoming
uint256 timeToNextDistribution; // exact time left to next distribution
uint256 claimedBMI; // actual number of claimed BMI
uint256 mainNFTAvailability; // 0 or NFT index if available
uint256 platinumNFTAvailability; // 0 or NFT index if available
bool claimedNFTs; // true if user claimed NFTs
}
struct MyTeamInfo {
TeamDetails teamDetails;
uint256 myStakedAmount;
uint256 teamPlace;
}
struct UserTeamInfo {
address teamAddr;
uint256 stakedAmount;
uint256 countOfRewardedMonth;
bool isNFTDistributed;
}
struct TeamInfo {
string name;
uint256 totalAmount;
address[] teamLeaders;
}
function startLiquidityMiningTime() external view returns (uint256);
function getTopTeams() external view returns (TeamDetails[] memory teams);
function getTopUsers() external view returns (UserInfo[] memory users);
function getAllTeamsLength() external view returns (uint256);
function getAllTeamsDetails(uint256 _offset, uint256 _limit)
external
view
returns (TeamDetails[] memory _teamDetailsArr);
function getMyTeamsLength() external view returns (uint256);
function getMyTeamMembers(uint256 _offset, uint256 _limit)
external
view
returns (address[] memory _teamMembers, uint256[] memory _memberStakedAmount);
function getAllUsersLength() external view returns (uint256);
function getAllUsersInfo(uint256 _offset, uint256 _limit)
external
view
returns (UserInfo[] memory _userInfos);
function getMyTeamInfo() external view returns (MyTeamInfo memory _myTeamInfo);
function getRewardsInfo(address user)
external
view
returns (UserRewardsInfo memory userRewardInfo);
function createTeam(string calldata _teamName) external;
function deleteTeam() external;
function joinTheTeam(address _referralLink) external;
function getSlashingPercentage() external view returns (uint256);
function investSTBL(uint256 _tokensAmount, address _policyBookAddr) external;
function distributeNFT() external;
function checkPlatinumNFTReward(address _userAddr) external view returns (uint256);
function checkMainNFTReward(address _userAddr) external view returns (uint256);
function distributeBMIReward() external;
function getTotalUserBMIReward(address _userAddr) external view returns (uint256);
function checkAvailableBMIReward(address _userAddr) external view returns (uint256);
/// @notice checks if liquidity mining event is lasting (startLiquidityMining() has been called)
/// @return true if LM is started and not ended, false otherwise
function isLMLasting() external view returns (bool);
/// @notice checks if liquidity mining event is finished. In order to be finished, it has to be started
/// @return true if LM is finished, false if event is still going or not started
function isLMEnded() external view returns (bool);
function getEndLMTime() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
interface ILeveragePortfolio {
enum LeveragePortfolio {USERLEVERAGEPOOL, REINSURANCEPOOL}
struct LevFundsFactors {
uint256 netMPL;
uint256 netMPLn;
address policyBookAddr;
}
function targetUR() external view returns (uint256);
function d_ProtocolConstant() external view returns (uint256);
function a_ProtocolConstant() external view returns (uint256);
function max_ProtocolConstant() external view returns (uint256);
/// @notice deploy lStable from user leverage pool or reinsurance pool using 2 formulas: access by policybook.
/// @param leveragePoolType LeveragePortfolio is determine the pool which call the function
function deployLeverageStableToCoveragePools(LeveragePortfolio leveragePoolType)
external
returns (uint256);
/// @notice deploy the vStable from RP in v2 and for next versions it will be from RP and LP : access by policybook.
function deployVirtualStableToCoveragePools() external returns (uint256);
/// @notice set the threshold % for re-evaluation of the lStable provided across all Coverage pools : access by owner
/// @param threshold uint256 is the reevaluatation threshold
function setRebalancingThreshold(uint256 threshold) external;
/// @notice set the protocol constant : access by owner
/// @param _targetUR uint256 target utitlization ration
/// @param _d_ProtocolConstant uint256 D protocol constant
/// @param _a1_ProtocolConstant uint256 A1 protocol constant
/// @param _max_ProtocolConstant uint256 the max % included
function setProtocolConstant(
uint256 _targetUR,
uint256 _d_ProtocolConstant,
uint256 _a1_ProtocolConstant,
uint256 _max_ProtocolConstant
) external;
/// @notice calc M factor by formual M = min( abs((1/ (Tur-UR))*d) /a, max)
/// @param poolUR uint256 utitilization ratio for a coverage pool
/// @return uint256 M facotr
//function calcM(uint256 poolUR) external returns (uint256);
/// @return uint256 the amount of vStable stored in the pool
function totalLiquidity() external view returns (uint256);
/// @notice add the portion of 80% of premium to user leverage pool where the leverage provide lstable : access policybook
/// add the 20% of premium + portion of 80% of premium where reisnurance pool participate in coverage pools (vStable) : access policybook
/// @param epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param premiumAmount uint256 the premium amount which is a portion of 80% of the premium
function addPolicyPremium(uint256 epochsNumber, uint256 premiumAmount) external;
/// @notice Used to get a list of coverage pools which get leveraged , use with count()
/// @return _coveragePools a list containing policybook addresses
function listleveragedCoveragePools(uint256 offset, uint256 limit)
external
view
returns (address[] memory _coveragePools);
/// @notice get count of coverage pools which get leveraged
function countleveragedCoveragePools() external view returns (uint256);
function updateLiquidity(uint256 _lostLiquidity) external;
function forceUpdateBMICoverStakingRewardMultiplier() external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IContractsRegistry {
function getUniswapRouterContract() external view returns (address);
function getUniswapBMIToETHPairContract() external view returns (address);
function getUniswapBMIToUSDTPairContract() external view returns (address);
function getSushiswapRouterContract() external view returns (address);
function getSushiswapBMIToETHPairContract() external view returns (address);
function getSushiswapBMIToUSDTPairContract() external view returns (address);
function getSushiSwapMasterChefV2Contract() external view returns (address);
function getWETHContract() external view returns (address);
function getUSDTContract() external view returns (address);
function getBMIContract() external view returns (address);
function getPriceFeedContract() external view returns (address);
function getPolicyBookRegistryContract() external view returns (address);
function getPolicyBookFabricContract() external view returns (address);
function getBMICoverStakingContract() external view returns (address);
function getBMICoverStakingViewContract() external view returns (address);
function getLegacyRewardsGeneratorContract() external view returns (address);
function getRewardsGeneratorContract() external view returns (address);
function getBMIUtilityNFTContract() external view returns (address);
function getNFTStakingContract() external view returns (address);
function getLiquidityBridgeContract() external view returns (address);
function getClaimingRegistryContract() external view returns (address);
function getPolicyRegistryContract() external view returns (address);
function getLiquidityRegistryContract() external view returns (address);
function getClaimVotingContract() external view returns (address);
function getReinsurancePoolContract() external view returns (address);
function getLeveragePortfolioViewContract() external view returns (address);
function getCapitalPoolContract() external view returns (address);
function getPolicyBookAdminContract() external view returns (address);
function getPolicyQuoteContract() external view returns (address);
function getLegacyBMIStakingContract() external view returns (address);
function getBMIStakingContract() external view returns (address);
function getSTKBMIContract() external view returns (address);
function getVBMIContract() external view returns (address);
function getLegacyLiquidityMiningStakingContract() external view returns (address);
function getLiquidityMiningStakingETHContract() external view returns (address);
function getLiquidityMiningStakingUSDTContract() external view returns (address);
function getReputationSystemContract() external view returns (address);
function getAaveProtocolContract() external view returns (address);
function getAaveLendPoolAddressProvdierContract() external view returns (address);
function getAaveATokenContract() external view returns (address);
function getCompoundProtocolContract() external view returns (address);
function getCompoundCTokenContract() external view returns (address);
function getCompoundComptrollerContract() external view returns (address);
function getYearnProtocolContract() external view returns (address);
function getYearnVaultContract() external view returns (address);
function getYieldGeneratorContract() external view returns (address);
function getShieldMiningContract() external view returns (address);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFabric.sol";
interface IClaimingRegistry {
enum ClaimStatus {
CAN_CLAIM,
UNCLAIMABLE,
PENDING,
AWAITING_CALCULATION,
REJECTED_CAN_APPEAL,
REJECTED,
ACCEPTED
}
struct ClaimInfo {
address claimer;
address policyBookAddress;
string evidenceURI;
uint256 dateSubmitted;
uint256 dateEnded;
bool appeal;
ClaimStatus status;
uint256 claimAmount;
}
/// @notice returns anonymous voting duration
function anonymousVotingDuration(uint256 index) external view returns (uint256);
/// @notice returns the whole voting duration
function votingDuration(uint256 index) external view returns (uint256);
/// @notice returns how many time should pass before anyone could calculate a claim result
function anyoneCanCalculateClaimResultAfter(uint256 index) external view returns (uint256);
/// @notice returns true if a user can buy new policy of specified PolicyBook
function canBuyNewPolicy(address buyer, address policyBookAddress)
external
view
returns (bool);
/// @notice submits new PolicyBook claim for the user
function submitClaim(
address user,
address policyBookAddress,
string calldata evidenceURI,
uint256 cover,
bool appeal
) external returns (uint256);
/// @notice returns true if the claim with this index exists
function claimExists(uint256 index) external view returns (bool);
/// @notice returns claim submition time
function claimSubmittedTime(uint256 index) external view returns (uint256);
/// @notice returns claim end time or zero in case it is pending
function claimEndTime(uint256 index) external view returns (uint256);
/// @notice returns true if the claim is anonymously votable
function isClaimAnonymouslyVotable(uint256 index) external view returns (bool);
/// @notice returns true if the claim is exposably votable
function isClaimExposablyVotable(uint256 index) external view returns (bool);
/// @notice returns true if claim is anonymously votable or exposably votable
function isClaimVotable(uint256 index) external view returns (bool);
/// @notice returns true if a claim can be calculated by anyone
function canClaimBeCalculatedByAnyone(uint256 index) external view returns (bool);
/// @notice returns true if this claim is pending or awaiting
function isClaimPending(uint256 index) external view returns (bool);
/// @notice returns how many claims the holder has
function countPolicyClaimerClaims(address user) external view returns (uint256);
/// @notice returns how many pending claims are there
function countPendingClaims() external view returns (uint256);
/// @notice returns how many claims are there
function countClaims() external view returns (uint256);
/// @notice returns a claim index of it's claimer and an ordinal number
function claimOfOwnerIndexAt(address claimer, uint256 orderIndex)
external
view
returns (uint256);
/// @notice returns pending claim index by its ordinal index
function pendingClaimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns claim index by its ordinal index
function claimIndexAt(uint256 orderIndex) external view returns (uint256);
/// @notice returns current active claim index by policybook and claimer
function claimIndex(address claimer, address policyBookAddress)
external
view
returns (uint256);
/// @notice returns true if the claim is appealed
function isClaimAppeal(uint256 index) external view returns (bool);
/// @notice returns current status of a claim
function policyStatus(address claimer, address policyBookAddress)
external
view
returns (ClaimStatus);
/// @notice returns current status of a claim
function claimStatus(uint256 index) external view returns (ClaimStatus);
/// @notice returns the claim owner (claimer)
function claimOwner(uint256 index) external view returns (address);
/// @notice returns the claim PolicyBook
function claimPolicyBook(uint256 index) external view returns (address);
/// @notice returns claim info by its index
function claimInfo(uint256 index) external view returns (ClaimInfo memory _claimInfo);
function getAllPendingClaimsAmount() external view returns (uint256 _totalClaimsAmount);
function getClaimableAmounts(uint256[] memory _claimIndexes) external view returns (uint256);
/// @notice marks the user's claim as Accepted
function acceptClaim(uint256 index) external;
/// @notice marks the user's claim as Rejected
function rejectClaim(uint256 index) external;
/// @notice Update Image Uri in case it contains material that is ilegal
/// or offensive.
/// @dev Only the owner of the PolicyBookAdmin can erase/update evidenceUri.
/// @param _claimIndex Claim Index that is going to be updated
/// @param _newEvidenceURI New evidence uri. It can be blank.
function updateImageUriOfClaim(uint256 _claimIndex, string calldata _newEvidenceURI) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IClaimingRegistry.sol";
interface IClaimVoting {
enum VoteStatus {
ANONYMOUS_PENDING,
AWAITING_EXPOSURE,
EXPIRED,
EXPOSED_PENDING,
AWAITING_CALCULATION,
MINORITY,
MAJORITY
}
struct VotingResult {
uint256 withdrawalAmount;
uint256 lockedBMIAmount;
uint256 reinsuranceTokensAmount;
uint256 votedAverageWithdrawalAmount;
uint256 votedYesStakedBMIAmountWithReputation;
uint256 votedNoStakedBMIAmountWithReputation;
uint256 allVotedStakedBMIAmount;
uint256 votedYesPercentage;
}
struct VotingInst {
uint256 claimIndex;
bytes32 finalHash;
string encryptedVote;
address voter;
uint256 voterReputation;
uint256 suggestedAmount;
uint256 stakedBMIAmount;
bool accept;
VoteStatus status;
}
struct MyClaimInfo {
uint256 index;
address policyBookAddress;
string evidenceURI;
bool appeal;
uint256 claimAmount;
IClaimingRegistry.ClaimStatus finalVerdict;
uint256 finalClaimAmount;
uint256 bmiCalculationReward;
}
struct PublicClaimInfo {
uint256 claimIndex;
address claimer;
address policyBookAddress;
string evidenceURI;
bool appeal;
uint256 claimAmount;
uint256 time;
}
struct AllClaimInfo {
PublicClaimInfo publicClaimInfo;
IClaimingRegistry.ClaimStatus finalVerdict;
uint256 finalClaimAmount;
uint256 bmiCalculationReward;
}
struct MyVoteInfo {
AllClaimInfo allClaimInfo;
string encryptedVote;
uint256 suggestedAmount;
VoteStatus status;
uint256 time;
}
struct VotesUpdatesInfo {
uint256 bmiReward;
uint256 stblReward;
int256 reputationChange;
int256 stakeChange;
}
/// @notice starts the voting process
function initializeVoting(
address claimer,
string calldata evidenceURI,
uint256 coverTokens,
bool appeal
) external;
/// @notice returns true if the user has no PENDING votes
function canWithdraw(address user) external view returns (bool);
/// @notice returns true if the user has no AWAITING_CALCULATION votes
function canVote(address user) external view returns (bool);
/// @notice returns how many votes the user has
function countVotes(address user) external view returns (uint256);
/// @notice returns status of the vote
function voteStatus(uint256 index) external view returns (VoteStatus);
/// @notice returns a list of claims that are votable for msg.sender
function whatCanIVoteFor(uint256 offset, uint256 limit)
external
returns (uint256 _claimsCount, PublicClaimInfo[] memory _votablesInfo);
/// @notice returns info list of ALL claims
function allClaims(uint256 offset, uint256 limit)
external
view
returns (AllClaimInfo[] memory _allClaimsInfo);
/// @notice returns info list of claims of msg.sender
function myClaims(uint256 offset, uint256 limit)
external
view
returns (MyClaimInfo[] memory _myClaimsInfo);
/// @notice returns info list of claims that are voted by msg.sender
function myVotes(uint256 offset, uint256 limit)
external
view
returns (MyVoteInfo[] memory _myVotesInfo);
/// @notice returns an array of votes that can be calculated + update information
function myVotesUpdates(uint256 offset, uint256 limit)
external
view
returns (
uint256 _votesUpdatesCount,
uint256[] memory _claimIndexes,
VotesUpdatesInfo memory _myVotesUpdatesInfo
);
/// @notice anonymously votes (result used later in exposeVote())
/// @notice the claims have to be PENDING, the voter can vote only once for a specific claim
/// @param claimIndexes are the indexes of the claims the voter is voting on
/// (each one is unique for each claim and appeal)
/// @param finalHashes are the hashes produced by the encryption algorithm.
/// They will be verified onchain in expose function
/// @param encryptedVotes are the AES encrypted values that represent the actual vote
function anonymouslyVoteBatch(
uint256[] calldata claimIndexes,
bytes32[] calldata finalHashes,
string[] calldata encryptedVotes
) external;
/// @notice exposes votes of anonymous votings
/// @notice the vote has to be voted anonymously prior
/// @param claimIndexes are the indexes of the claims to expose votes for
/// @param suggestedClaimAmounts are the actual vote values.
/// They must match the decrypted values in anonymouslyVoteBatch function
/// @param hashedSignaturesOfClaims are the validation data needed to construct proper finalHashes
function exposeVoteBatch(
uint256[] calldata claimIndexes,
uint256[] calldata suggestedClaimAmounts,
bytes32[] calldata hashedSignaturesOfClaims
) external;
/// @notice calculates results of votes
function calculateVoterResultBatch(uint256[] calldata claimIndexes) external;
/// @notice calculates results of claims
function calculateVotingResultBatch(uint256[] calldata claimIndexes) external;
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IPolicyBookFacade.sol";
interface ICapitalPool {
struct PremiumFactors {
uint256 epochsNumber;
uint256 premiumPrice;
uint256 vStblDeployedByRP;
uint256 vStblOfCP;
uint256 poolUtilizationRation;
uint256 premiumPerDeployment;
uint256 userLeveragePoolsCount;
IPolicyBookFacade policyBookFacade;
}
enum PoolType {COVERAGE, LEVERAGE, REINSURANCE}
function virtualUsdtAccumulatedBalance() external view returns (uint256);
function liquidityCushionBalance() external view returns (uint256);
/// @notice distributes the policybook premiums into pools (CP, ULP , RP)
/// @dev distributes the balances acording to the established percentages
/// @param _stblAmount amount hardSTBL ingressed into the system
/// @param _epochsNumber uint256 the number of epochs which the policy holder will pay a premium for
/// @param _protocolFee uint256 the amount of protocol fee earned by premium
function addPolicyHoldersHardSTBL(
uint256 _stblAmount,
uint256 _epochsNumber,
uint256 _protocolFee
) external returns (uint256);
/// @notice distributes the hardSTBL from the coverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addCoverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the leverage providers
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addLeverageProvidersHardSTBL(uint256 _stblAmount) external;
/// @notice distributes the hardSTBL from the reinsurance pool
/// @dev emits PoolBalancedUpdated event
/// @param _stblAmount amount hardSTBL ingressed into the system
function addReinsurancePoolHardSTBL(uint256 _stblAmount) external;
/// @notice rebalances pools acording to v2 specification and dao enforced policies
/// @dev emits PoolBalancesUpdated
function rebalanceLiquidityCushion() external;
/// @notice Fullfils policybook claims by transfering the balance to claimer
/// @param _claimer, address of the claimer recieving the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
function fundClaim(address _claimer, uint256 _stblAmount) external;
/// @notice Withdraws liquidity from a specific policbybook to the user
/// @param _sender, address of the user beneficiary of the withdraw
/// @param _stblAmount uint256 amount to be withdrawn
/// @param _isLeveragePool bool wether the pool is ULP or CP(policybook)
function withdrawLiquidity(
address _sender,
uint256 _stblAmount,
bool _isLeveragePool
) external;
function rebalanceDuration() external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
import "./IBMICoverStaking.sol";
interface IBMICoverStakingView {
function getPolicyBookAPY(address policyBookAddress) external view returns (uint256);
function policyBookByNFT(uint256 tokenId) external view returns (address);
function stakingInfoByStaker(
address staker,
address[] calldata policyBooksAddresses,
uint256 offset,
uint256 limit
)
external
view
returns (
IBMICoverStaking.PolicyBookInfo[] memory policyBooksInfo,
IBMICoverStaking.UserInfo[] memory usersInfo,
uint256[] memory nftsCount,
IBMICoverStaking.NFTsInfo[][] memory nftsInfo
);
function stakingInfoByToken(uint256 tokenId)
external
view
returns (IBMICoverStaking.StakingInfo memory);
// Not Migratable
// function totalStaked(address user) external view returns (uint256);
// function totalStakedSTBL(address user) external view returns (uint256);
// function getStakerBMIProfit(address staker, address policyBookAddress, uint256 offset, uint256 limit) external view returns (uint256) ;
// function getSlashedBMIProfit(uint256 tokenId) external view returns (uint256);
// function getBMIProfit(uint256 tokenId) external view returns (uint256);
// function uri(uint256 tokenId) external view returns (string memory);
// function tokenOfOwnerByIndex(address user, uint256 index) external view returns (uint256);
// function ownerOf(uint256 tokenId) external view returns (address);
// function getSlashingPercentage() external view returns (uint256);
// function getSlashedStakerBMIProfit( address staker, address policyBookAddress, uint256 offset, uint256 limit) external view returns (uint256 totalProfit) ;
// function balanceOf(address user) external view returns (uint256);
// function _aggregateForEach( address staker, address policyBookAddress, uint256 offset, uint256 limit, function(uint256) view returns (uint256) func) internal view returns (uint256 total);
// function stakedByNFT(uint256 tokenId) external view returns (uint256);
// function stakedSTBLByNFT(uint256 tokenId) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
interface IBMICoverStaking {
struct StakingInfo {
address policyBookAddress;
uint256 stakedBMIXAmount;
}
struct PolicyBookInfo {
uint256 totalStakedSTBL;
uint256 rewardPerBlock;
uint256 stakingAPY;
uint256 liquidityAPY;
}
struct UserInfo {
uint256 totalStakedBMIX;
uint256 totalStakedSTBL;
uint256 totalBmiReward;
}
struct NFTsInfo {
uint256 nftIndex;
string uri;
uint256 stakedBMIXAmount;
uint256 stakedSTBLAmount;
uint256 reward;
}
function aggregateNFTs(address policyBookAddress, uint256[] calldata tokenIds) external;
function stakeBMIX(uint256 amount, address policyBookAddress) external;
function stakeBMIXWithPermit(
uint256 bmiXAmount,
address policyBookAddress,
uint8 v,
bytes32 r,
bytes32 s
) external;
function stakeBMIXFrom(address user, uint256 amount) external;
function stakeBMIXFromWithPermit(
address user,
uint256 bmiXAmount,
uint8 v,
bytes32 r,
bytes32 s
) external;
// mappings
function _stakersPool(uint256 index)
external
view
returns (address policyBookAddress, uint256 stakedBMIXAmount);
// function getPolicyBookAPY(address policyBookAddress) external view returns (uint256);
function restakeBMIProfit(uint256 tokenId) external;
function restakeStakerBMIProfit(address policyBookAddress) external;
function withdrawBMIProfit(uint256 tokenID) external;
function withdrawStakerBMIProfit(address policyBookAddress) external;
function withdrawFundsWithProfit(uint256 tokenID) external;
function withdrawStakerFundsWithProfit(address policyBookAddress) external;
function getSlashedBMIProfit(uint256 tokenId) external view returns (uint256);
function getBMIProfit(uint256 tokenId) external view returns (uint256);
function getSlashedStakerBMIProfit(
address staker,
address policyBookAddress,
uint256 offset,
uint256 limit
) external view returns (uint256 totalProfit);
function getStakerBMIProfit(
address staker,
address policyBookAddress,
uint256 offset,
uint256 limit
) external view returns (uint256 totalProfit);
function totalStaked(address user) external view returns (uint256);
function totalStakedSTBL(address user) external view returns (uint256);
function stakedByNFT(uint256 tokenId) external view returns (uint256);
function stakedSTBLByNFT(uint256 tokenId) external view returns (uint256);
function balanceOf(address user) external view returns (uint256);
function ownerOf(uint256 tokenId) external view returns (address);
function uri(uint256 tokenId) external view returns (string memory);
function tokenOfOwnerByIndex(address user, uint256 index) external view returns (uint256);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
abstract contract AbstractDependant {
/// @dev keccak256(AbstractDependant.setInjector(address)) - 1
bytes32 private constant _INJECTOR_SLOT =
0xd6b8f2e074594ceb05d47c27386969754b6ad0c15e5eb8f691399cd0be980e76;
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
function setInjector(address _injector) external onlyInjectorOrZero {
bytes32 slot = _INJECTOR_SLOT;
assembly {
sstore(slot, _injector)
}
}
/// @dev has to apply onlyInjectorOrZero() modifier
function setDependencies(IContractsRegistry) external virtual;
function injector() public view returns (address _injector) {
bytes32 slot = _INJECTOR_SLOT;
assembly {
_injector := sload(slot)
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.4;
pragma experimental ABIEncoderV2;
uint256 constant SECONDS_IN_THE_YEAR = 365 * 24 * 60 * 60; // 365 days * 24 hours * 60 minutes * 60 seconds
uint256 constant DAYS_IN_THE_YEAR = 365;
uint256 constant MAX_INT = type(uint256).max;
uint256 constant DECIMALS18 = 10**18;
uint256 constant PRECISION = 10**25;
uint256 constant PERCENTAGE_100 = 100 * PRECISION;
uint256 constant BLOCKS_PER_DAY = 6450;
uint256 constant BLOCKS_PER_YEAR = BLOCKS_PER_DAY * 365;
uint256 constant APY_TOKENS = DECIMALS18;
uint256 constant PROTOCOL_PERCENTAGE = 20 * PRECISION;
uint256 constant DEFAULT_REBALANCING_THRESHOLD = 10**23;
uint256 constant EPOCH_DAYS_AMOUNT = 7;
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
import "../../GSN/Context.sol";
import "./IERC20.sol";
import "../../math/SafeMath.sol";
import "../../utils/Address.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20 is Context, IERC20 {
using SafeMath for uint256;
using Address for address;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor (string memory name, string memory symbol) {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20};
*
* Requirements:
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// SPDX-License-Identifier: MIT
pragma solidity ^0.7.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract Context {
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../math/SafeMathUpgradeable.sol";
/**
* @title Counters
* @author Matt Condon (@shrugs)
* @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number
* of elements in a mapping, issuing ERC721 ids, or counting request ids.
*
* Include with `using Counters for Counters.Counter;`
* Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the {SafeMath}
* overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never
* directly accessed.
*/
library CountersUpgradeable {
using SafeMathUpgradeable for uint256;
struct Counter {
// This variable should never be directly accessed by users of the library: interactions must be restricted to
// the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add
// this feature: see https://github.com/ethereum/solidity/issues/4637
uint256 _value; // default: 0
}
function current(Counter storage counter) internal view returns (uint256) {
return counter._value;
}
function increment(Counter storage counter) internal {
// The {SafeMath} overflow check can be skipped here, see the comment at the top
counter._value += 1;
}
function decrement(Counter storage counter) internal {
counter._value = counter._value.sub(1);
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20Upgradeable {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../../GSN/ContextUpgradeable.sol";
import "./IERC20Upgradeable.sol";
import "../../math/SafeMathUpgradeable.sol";
import "../../proxy/Initializable.sol";
/**
* @dev Implementation of the {IERC20} interface.
*
* This implementation is agnostic to the way tokens are created. This means
* that a supply mechanism has to be added in a derived contract using {_mint}.
* For a generic mechanism see {ERC20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How
* to implement supply mechanisms].
*
* We have followed general OpenZeppelin guidelines: functions revert instead
* of returning `false` on failure. This behavior is nonetheless conventional
* and does not conflict with the expectations of ERC20 applications.
*
* Additionally, an {Approval} event is emitted on calls to {transferFrom}.
* This allows applications to reconstruct the allowance for all accounts just
* by listening to said events. Other implementations of the EIP may not emit
* these events, as it isn't required by the specification.
*
* Finally, the non-standard {decreaseAllowance} and {increaseAllowance}
* functions have been added to mitigate the well-known issues around setting
* allowances. See {IERC20-approve}.
*/
contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable {
using SafeMathUpgradeable for uint256;
mapping (address => uint256) private _balances;
mapping (address => mapping (address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
function __ERC20_init(string memory name_, string memory symbol_) internal initializer {
__Context_init_unchained();
__ERC20_init_unchained(name_, symbol_);
}
function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer {
_name = name_;
_symbol = symbol_;
_decimals = 18;
}
/**
* @dev Returns the name of the token.
*/
function name() public view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
* For example, if `decimals` equals `2`, a balance of `505` tokens should
* be displayed to a user as `5,05` (`505 / 10 ** 2`).
*
* Tokens usually opt for a value of 18, imitating the relationship between
* Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is
* called.
*
* NOTE: This information is only used for _display_ purposes: it in
* no way affects any of the arithmetic of the contract, including
* {IERC20-balanceOf} and {IERC20-transfer}.
*/
function decimals() public view returns (uint8) {
return _decimals;
}
/**
* @dev See {IERC20-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return _totalSupply;
}
/**
* @dev See {IERC20-balanceOf}.
*/
function balanceOf(address account) public view override returns (uint256) {
return _balances[account];
}
/**
* @dev See {IERC20-transfer}.
*
* Requirements:
*
* - `recipient` cannot be the zero address.
* - the caller must have a balance of at least `amount`.
*/
function transfer(address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {IERC20-allowance}.
*/
function allowance(address owner, address spender) public view virtual override returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {IERC20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public virtual override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {IERC20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {ERC20}.
*
* Requirements:
*
* - `sender` and `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
* - the caller must have allowance for ``sender``'s tokens of at least
* `amount`.
*/
function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance"));
return true;
}
/**
* @dev Atomically increases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {IERC20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero"));
return true;
}
/**
* @dev Moves tokens `amount` from `sender` to `recipient`.
*
* This is internal function is equivalent to {transfer}, and can be used to
* e.g. implement automatic token fees, slashing mechanisms, etc.
*
* Emits a {Transfer} event.
*
* Requirements:
*
* - `sender` cannot be the zero address.
* - `recipient` cannot be the zero address.
* - `sender` must have a balance of at least `amount`.
*/
function _transfer(address sender, address recipient, uint256 amount) internal virtual {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
_beforeTokenTransfer(sender, recipient, amount);
_balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance");
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements:
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: mint to the zero address");
_beforeTokenTransfer(address(0), account, amount);
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements:
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal virtual {
require(account != address(0), "ERC20: burn from the zero address");
_beforeTokenTransfer(account, address(0), amount);
_balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance");
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens.
*
* This internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve(address owner, address spender, uint256 amount) internal virtual {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Sets {decimals} to a value other than the default one of 18.
*
* WARNING: This function should only be called from the constructor. Most
* applications that interact with token contracts will not expect
* {decimals} to ever change, and may work incorrectly if it does.
*/
function _setupDecimals(uint8 decimals_) internal {
_decimals = decimals_;
}
/**
* @dev Hook that is called before any transfer of tokens. This includes
* minting and burning.
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens
* will be to transferred to `to`.
* - when `from` is zero, `amount` tokens will be minted for `to`.
* - when `to` is zero, `amount` of ``from``'s tokens will be burned.
* - `from` and `to` are never both zero.
*
* To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks].
*/
function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { }
uint256[44] private __gap;
}
// SPDX-License-Identifier: MIT
// solhint-disable-next-line compiler-version
pragma solidity >=0.4.24 <0.8.0;
/**
* @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed
* behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an
* external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer
* function so it can only be called once. The {initializer} modifier provided by this contract will have this effect.
*
* TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as
* possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-constructor}.
*
* CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure
* that all initializers are idempotent. This is not verified automatically as constructors are by Solidity.
*/
abstract contract Initializable {
/**
* @dev Indicates that the contract has been initialized.
*/
bool private _initialized;
/**
* @dev Indicates that the contract is in the process of being initialized.
*/
bool private _initializing;
/**
* @dev Modifier to protect an initializer function from being invoked twice.
*/
modifier initializer() {
require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already initialized");
bool isTopLevelCall = !_initializing;
if (isTopLevelCall) {
_initializing = true;
_initialized = true;
}
_;
if (isTopLevelCall) {
_initializing = false;
}
}
/// @dev Returns true if and only if the function is running in the constructor
function _isConstructor() private view returns (bool) {
// extcodesize checks the size of the code stored in an address, and
// address returns the current address. Since the code is still not
// deployed when running a constructor, any checks on its code size will
// yield zero, making it an effective way to detect if a contract is
// under construction or not.
address self = address(this);
uint256 cs;
// solhint-disable-next-line no-inline-assembly
assembly { cs := extcodesize(self) }
return cs == 0;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMathUpgradeable {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// SPDX-License-Identifier: MIT
pragma solidity >=0.6.0 <0.8.0;
import "../proxy/Initializable.sol";
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
abstract contract ContextUpgradeable is Initializable {
function __Context_init() internal initializer {
__Context_init_unchained();
}
function __Context_init_unchained() internal initializer {
}
function _msgSender() internal view virtual returns (address payable) {
return msg.sender;
}
function _msgData() internal view virtual returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
uint256[50] private __gap;
}
|
keccak256(AbstractDependant.setInjector(address)) - 1
|
function aggregateNFTs(address policyBookAddress, uint256[] calldata tokenIds) external;
function stakeBMIX(uint256 amount, address policyBookAddress) external;
function stakeBMIXWithPermit(
uint256 bmiXAmount,
address policyBookAddress,
uint8 v,
bytes32 r,
bytes32 s
) external;
function stakeBMIXFrom(address user, uint256 amount) external;
function stakeBMIXFromWithPermit(
address user,
uint256 bmiXAmount,
uint8 v,
bytes32 r,
bytes32 s
) external;
function _stakersPool(uint256 index)
external
view
returns (address policyBookAddress, uint256 stakedBMIXAmount);
function restakeBMIProfit(uint256 tokenId) external;
function restakeStakerBMIProfit(address policyBookAddress) external;
function withdrawBMIProfit(uint256 tokenID) external;
function withdrawStakerBMIProfit(address policyBookAddress) external;
function withdrawFundsWithProfit(uint256 tokenID) external;
function withdrawStakerFundsWithProfit(address policyBookAddress) external;
function getSlashedBMIProfit(uint256 tokenId) external view returns (uint256);
function getBMIProfit(uint256 tokenId) external view returns (uint256);
function getSlashedStakerBMIProfit(
address staker,
address policyBookAddress,
uint256 offset,
uint256 limit
) external view returns (uint256 totalProfit);
function getStakerBMIProfit(
address staker,
address policyBookAddress,
uint256 offset,
uint256 limit
) external view returns (uint256 totalProfit);
function totalStaked(address user) external view returns (uint256);
function totalStakedSTBL(address user) external view returns (uint256);
function stakedByNFT(uint256 tokenId) external view returns (uint256);
function stakedSTBLByNFT(uint256 tokenId) external view returns (uint256);
function balanceOf(address user) external view returns (uint256);
function ownerOf(uint256 tokenId) external view returns (address);
function uri(uint256 tokenId) external view returns (string memory);
function tokenOfOwnerByIndex(address user, uint256 index) external view returns (uint256);
}
pragma solidity ^0.7.4;
import "../interfaces/IContractsRegistry.sol";
modifier onlyInjectorOrZero() {
address _injector = injector();
require(_injector == address(0) || _injector == msg.sender, "Dependant: Not an injector");
_;
}
| 9,946,802 |
pragma solidity 0.4.20;
library SafeMath {
function add(uint a, uint b) internal pure returns (uint c) {
c = a + b;
assert(c >= a);
}
function sub(uint a, uint b) internal pure returns (uint c) {
assert(b <= a);
c = a - b;
}
function mul(uint a, uint b) internal pure returns (uint c) {
c = a * b;
assert(a == 0 || c / a == b);
}
function div(uint a, uint b) internal pure returns (uint c) {
assert(b > 0);
c = a / b;
assert(a == b * c + a % b);
}
}
contract AcreConfig {
using SafeMath for uint;
uint internal constant TIME_FACTOR = 1 minutes;
// Ownable
uint internal constant OWNERSHIP_DURATION_TIME = 7; // 7 days
// MultiOwnable
uint8 internal constant MULTI_OWNER_COUNT = 5; // 5 accounts, exclude master
// Lockable
uint internal constant LOCKUP_DURATION_TIME = 365; // 365 days
// AcreToken
string internal constant TOKEN_NAME = "TAA";
string internal constant TOKEN_SYMBOL = "TAA";
uint8 internal constant TOKEN_DECIMALS = 18;
uint internal constant INITIAL_SUPPLY = 1*1e8 * 10 ** uint(TOKEN_DECIMALS); // supply
uint internal constant CAPITAL_SUPPLY = 31*1e6 * 10 ** uint(TOKEN_DECIMALS); // supply
uint internal constant PRE_PAYMENT_SUPPLY = 19*1e6 * 10 ** uint(TOKEN_DECIMALS); // supply
uint internal constant MAX_MINING_SUPPLY = 4*1e8 * 10 ** uint(TOKEN_DECIMALS); // supply
// Sale
uint internal constant MIN_ETHER = 1*1e17; // 0.1 ether
uint internal constant EXCHANGE_RATE = 1000; // 1 eth = 1000 acre
uint internal constant PRESALE_DURATION_TIME = 15; // 15 days
uint internal constant CROWDSALE_DURATION_TIME = 21; // 21 days
// helper
function getDays(uint _time) internal pure returns(uint) {
return SafeMath.div(_time, 1 days);
}
function getHours(uint _time) internal pure returns(uint) {
return SafeMath.div(_time, 1 hours);
}
function getMinutes(uint _time) internal pure returns(uint) {
return SafeMath.div(_time, 1 minutes);
}
}
contract Ownable is AcreConfig {
address public owner;
address public reservedOwner;
uint public ownershipDeadline;
event ReserveOwnership(address indexed oldOwner, address indexed newOwner);
event ConfirmOwnership(address indexed oldOwner, address indexed newOwner);
event CancelOwnership(address indexed oldOwner, address indexed newOwner);
modifier onlyOwner {
require(msg.sender == owner);
_;
}
function Ownable() public {
owner = msg.sender;
}
function reserveOwnership(address newOwner) onlyOwner public returns (bool success) {
require(newOwner != address(0));
ReserveOwnership(owner, newOwner);
reservedOwner = newOwner;
ownershipDeadline = SafeMath.add(now, SafeMath.mul(OWNERSHIP_DURATION_TIME, TIME_FACTOR));
return true;
}
function confirmOwnership() onlyOwner public returns (bool success) {
require(reservedOwner != address(0));
require(now > ownershipDeadline);
ConfirmOwnership(owner, reservedOwner);
owner = reservedOwner;
reservedOwner = address(0);
return true;
}
function cancelOwnership() onlyOwner public returns (bool success) {
require(reservedOwner != address(0));
CancelOwnership(owner, reservedOwner);
reservedOwner = address(0);
return true;
}
}
contract MultiOwnable is Ownable {
address[] public owners;
event GrantOwners(address indexed owner);
event RevokeOwners(address indexed owner);
modifier onlyMutiOwners {
require(isExistedOwner(msg.sender));
_;
}
modifier onlyManagers {
require(isManageable(msg.sender));
_;
}
function MultiOwnable() public {
owners.length = MULTI_OWNER_COUNT;
}
function grantOwners(address _owner) onlyOwner public returns (bool success) {
require(!isExistedOwner(_owner));
require(isEmptyOwner());
owners[getEmptyIndex()] = _owner;
GrantOwners(_owner);
return true;
}
function revokeOwners(address _owner) onlyOwner public returns (bool success) {
require(isExistedOwner(_owner));
owners[getOwnerIndex(_owner)] = address(0);
RevokeOwners(_owner);
return true;
}
// helper
function isManageable(address _owner) internal constant returns (bool) {
return isExistedOwner(_owner) || owner == _owner;
}
function isExistedOwner(address _owner) internal constant returns (bool) {
for(uint8 i = 0; i < MULTI_OWNER_COUNT; ++i) {
if(owners[i] == _owner) {
return true;
}
}
}
function getOwnerIndex(address _owner) internal constant returns (uint) {
for(uint8 i = 0; i < MULTI_OWNER_COUNT; ++i) {
if(owners[i] == _owner) {
return i;
}
}
}
function isEmptyOwner() internal constant returns (bool) {
for(uint8 i = 0; i < MULTI_OWNER_COUNT; ++i) {
if(owners[i] == address(0)) {
return true;
}
}
}
function getEmptyIndex() internal constant returns (uint) {
for(uint8 i = 0; i < MULTI_OWNER_COUNT; ++i) {
if(owners[i] == address(0)) {
return i;
}
}
}
}
contract Pausable is MultiOwnable {
bool public paused = false;
event Pause();
event Unpause();
modifier whenNotPaused() {
require(!paused);
_;
}
modifier whenPaused() {
require(paused);
_;
}
modifier whenConditionalPassing() {
if(!isManageable(msg.sender)) {
require(!paused);
}
_;
}
function pause() onlyManagers whenNotPaused public returns (bool success) {
paused = true;
Pause();
return true;
}
function unpause() onlyManagers whenPaused public returns (bool success) {
paused = false;
Unpause();
return true;
}
}
contract Lockable is Pausable {
mapping (address => uint) public locked;
event Lockup(address indexed target, uint startTime, uint deadline);
function lockup(address _target) onlyOwner public returns (bool success) {
require(!isManageable(_target));
locked[_target] = SafeMath.add(now, SafeMath.mul(LOCKUP_DURATION_TIME, TIME_FACTOR));
Lockup(_target, now, locked[_target]);
return true;
}
// helper
function isLockup(address _target) internal constant returns (bool) {
if(now <= locked[_target])
return true;
}
}
interface tokenRecipient {
function receiveApproval(address _from, uint _value, address _token, bytes _extraData) external;
}
contract TokenERC20 {
using SafeMath for uint;
string public name;
string public symbol;
uint8 public decimals;
uint public totalSupply;
mapping (address => uint) public balanceOf;
mapping (address => mapping (address => uint)) public allowance;
event ERC20Token(address indexed owner, string name, string symbol, uint8 decimals, uint supply);
event Transfer(address indexed from, address indexed to, uint value);
event TransferFrom(address indexed from, address indexed to, address indexed spender, uint value);
event Approval(address indexed owner, address indexed spender, uint value);
function TokenERC20(
string _tokenName,
string _tokenSymbol,
uint8 _tokenDecimals,
uint _initialSupply
) public {
name = _tokenName;
symbol = _tokenSymbol;
decimals = _tokenDecimals;
totalSupply = _initialSupply;
balanceOf[msg.sender] = totalSupply;
ERC20Token(msg.sender, name, symbol, decimals, totalSupply);
}
function _transfer(address _from, address _to, uint _value) internal returns (bool success) {
require(_to != address(0));
require(balanceOf[_from] >= _value);
require(SafeMath.add(balanceOf[_to], _value) > balanceOf[_to]);
uint previousBalances = SafeMath.add(balanceOf[_from], balanceOf[_to]);
balanceOf[_from] = balanceOf[_from].sub(_value);
balanceOf[_to] = balanceOf[_to].add(_value);
Transfer(_from, _to, _value);
assert(SafeMath.add(balanceOf[_from], balanceOf[_to]) == previousBalances);
return true;
}
function transfer(address _to, uint _value) public returns (bool success) {
return _transfer(msg.sender, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
require(_value <= allowance[_from][msg.sender]);
allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value);
_transfer(_from, _to, _value);
TransferFrom(_from, _to, msg.sender, _value);
return true;
}
function approve(address _spender, uint _value) public returns (bool success) {
allowance[msg.sender][_spender] = _value;
Approval(msg.sender, _spender, _value);
return true;
}
function approveAndCall(address _spender, uint _value, bytes _extraData) public returns (bool success) {
tokenRecipient spender = tokenRecipient(_spender);
if (approve(_spender, _value)) {
spender.receiveApproval(msg.sender, _value, this, _extraData);
return true;
}
}
}
contract AcreToken is Lockable, TokenERC20 {
string public version = '1.0';
address public companyCapital;
address public prePayment;
uint public totalMineSupply;
mapping (address => bool) public frozenAccount;
event FrozenAccount(address indexed target, bool frozen);
event Burn(address indexed owner, uint value);
event Mining(address indexed recipient, uint value);
event WithdrawContractToken(address indexed owner, uint value);
function AcreToken(address _companyCapital, address _prePayment) TokenERC20(TOKEN_NAME, TOKEN_SYMBOL, TOKEN_DECIMALS, INITIAL_SUPPLY) public {
require(_companyCapital != address(0));
require(_prePayment != address(0));
companyCapital = _companyCapital;
prePayment = _prePayment;
transfer(companyCapital, CAPITAL_SUPPLY);
transfer(prePayment, PRE_PAYMENT_SUPPLY);
lockup(prePayment);
pause();
}
function _transfer(address _from, address _to, uint _value) whenConditionalPassing internal returns (bool success) {
require(!frozenAccount[_from]); // freeze
require(!frozenAccount[_to]);
require(!isLockup(_from)); // lockup
require(!isLockup(_to));
return super._transfer(_from, _to, _value);
}
function transferFrom(address _from, address _to, uint _value) public returns (bool success) {
require(!frozenAccount[msg.sender]); // freeze
require(!isLockup(msg.sender)); // lockup
return super.transferFrom(_from, _to, _value);
}
function freezeAccount(address _target) onlyManagers public returns (bool success) {
require(!isManageable(_target));
require(!frozenAccount[_target]);
frozenAccount[_target] = true;
FrozenAccount(_target, true);
return true;
}
function unfreezeAccount(address _target) onlyManagers public returns (bool success) {
require(frozenAccount[_target]);
frozenAccount[_target] = false;
FrozenAccount(_target, false);
return true;
}
function burn(uint _value) onlyManagers public returns (bool success) {
require(balanceOf[msg.sender] >= _value);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value);
totalSupply = totalSupply.sub(_value);
Burn(msg.sender, _value);
return true;
}
function mining(address _recipient, uint _value) onlyManagers public returns (bool success) {
require(_recipient != address(0));
require(!frozenAccount[_recipient]); // freeze
require(!isLockup(_recipient)); // lockup
require(SafeMath.add(totalMineSupply, _value) <= MAX_MINING_SUPPLY);
balanceOf[_recipient] = balanceOf[_recipient].add(_value);
totalSupply = totalSupply.add(_value);
totalMineSupply = totalMineSupply.add(_value);
Mining(_recipient, _value);
return true;
}
function withdrawContractToken(uint _value) onlyManagers public returns (bool success) {
_transfer(this, msg.sender, _value);
WithdrawContractToken(msg.sender, _value);
return true;
}
function getContractBalanceOf() public constant returns(uint blance) {
blance = balanceOf[this];
}
function getRemainingMineSupply() public constant returns(uint supply) {
supply = MAX_MINING_SUPPLY - totalMineSupply;
}
function () public { revert(); }
}
contract AcreSale is MultiOwnable {
uint public saleDeadline;
uint public startSaleTime;
uint public softCapToken;
uint public hardCapToken;
uint public soldToken;
uint public receivedEther;
address public sendEther;
AcreToken public tokenReward;
bool public fundingGoalReached = false;
bool public saleOpened = false;
Payment public kyc;
Payment public refund;
Payment public withdrawal;
mapping(uint=>address) public indexedFunders;
mapping(address => Order) public orders;
uint public funderCount;
event StartSale(uint softCapToken, uint hardCapToken, uint minEther, uint exchangeRate, uint startTime, uint deadline);
event ReservedToken(address indexed funder, uint amount, uint token, uint bonusRate);
event WithdrawFunder(address indexed funder, uint value);
event WithdrawContractToken(address indexed owner, uint value);
event CheckGoalReached(uint raisedAmount, uint raisedToken, bool reached);
event CheckOrderstate(address indexed funder, eOrderstate oldState, eOrderstate newState);
enum eOrderstate { NONE, KYC, REFUND }
struct Order {
eOrderstate state;
uint paymentEther;
uint reservedToken;
bool withdrawn;
}
struct Payment {
uint token;
uint eth;
uint count;
}
modifier afterSaleDeadline {
require(now > saleDeadline);
_;
}
function AcreSale(
address _sendEther,
uint _softCapToken,
uint _hardCapToken,
AcreToken _addressOfTokenUsedAsReward
) public {
require(_sendEther != address(0));
require(_addressOfTokenUsedAsReward != address(0));
require(_softCapToken > 0 && _softCapToken <= _hardCapToken);
sendEther = _sendEther;
softCapToken = _softCapToken * 10 ** uint(TOKEN_DECIMALS);
hardCapToken = _hardCapToken * 10 ** uint(TOKEN_DECIMALS);
tokenReward = AcreToken(_addressOfTokenUsedAsReward);
}
function startSale(uint _durationTime) onlyManagers internal {
require(softCapToken > 0 && softCapToken <= hardCapToken);
require(hardCapToken > 0 && hardCapToken <= tokenReward.balanceOf(this));
require(_durationTime > 0);
require(startSaleTime == 0);
startSaleTime = now;
saleDeadline = SafeMath.add(startSaleTime, SafeMath.mul(_durationTime, TIME_FACTOR));
saleOpened = true;
StartSale(softCapToken, hardCapToken, MIN_ETHER, EXCHANGE_RATE, startSaleTime, saleDeadline);
}
// get
function getRemainingSellingTime() public constant returns(uint remainingTime) {
if(now <= saleDeadline) {
remainingTime = getMinutes(SafeMath.sub(saleDeadline, now));
}
}
function getRemainingSellingToken() public constant returns(uint remainingToken) {
remainingToken = SafeMath.sub(hardCapToken, soldToken);
}
function getSoftcapReached() public constant returns(bool reachedSoftcap) {
reachedSoftcap = soldToken >= softCapToken;
}
function getContractBalanceOf() public constant returns(uint blance) {
blance = tokenReward.balanceOf(this);
}
function getCurrentBonusRate() public constant returns(uint8 bonusRate);
// check
function checkGoalReached() onlyManagers afterSaleDeadline public {
if(saleOpened) {
if(getSoftcapReached()) {
fundingGoalReached = true;
}
saleOpened = false;
CheckGoalReached(receivedEther, soldToken, fundingGoalReached);
}
}
function checkKYC(address _funder) onlyManagers afterSaleDeadline public {
require(!saleOpened);
require(orders[_funder].reservedToken > 0);
require(orders[_funder].state != eOrderstate.KYC);
require(!orders[_funder].withdrawn);
eOrderstate oldState = orders[_funder].state;
// old, decrease
if(oldState == eOrderstate.REFUND) {
refund.token = refund.token.sub(orders[_funder].reservedToken);
refund.eth = refund.eth.sub(orders[_funder].paymentEther);
refund.count = refund.count.sub(1);
}
// state
orders[_funder].state = eOrderstate.KYC;
kyc.token = kyc.token.add(orders[_funder].reservedToken);
kyc.eth = kyc.eth.add(orders[_funder].paymentEther);
kyc.count = kyc.count.add(1);
CheckOrderstate(_funder, oldState, eOrderstate.KYC);
}
function checkRefund(address _funder) onlyManagers afterSaleDeadline public {
require(!saleOpened);
require(orders[_funder].reservedToken > 0);
require(orders[_funder].state != eOrderstate.REFUND);
require(!orders[_funder].withdrawn);
eOrderstate oldState = orders[_funder].state;
// old, decrease
if(oldState == eOrderstate.KYC) {
kyc.token = kyc.token.sub(orders[_funder].reservedToken);
kyc.eth = kyc.eth.sub(orders[_funder].paymentEther);
kyc.count = kyc.count.sub(1);
}
// state
orders[_funder].state = eOrderstate.REFUND;
refund.token = refund.token.add(orders[_funder].reservedToken);
refund.eth = refund.eth.add(orders[_funder].paymentEther);
refund.count = refund.count.add(1);
CheckOrderstate(_funder, oldState, eOrderstate.REFUND);
}
// withdraw
function withdrawFunder(address _funder) onlyManagers afterSaleDeadline public {
require(!saleOpened);
require(fundingGoalReached);
require(orders[_funder].reservedToken > 0);
require(orders[_funder].state == eOrderstate.KYC);
require(!orders[_funder].withdrawn);
// token
tokenReward.transfer(_funder, orders[_funder].reservedToken);
withdrawal.token = withdrawal.token.add(orders[_funder].reservedToken);
withdrawal.eth = withdrawal.eth.add(orders[_funder].paymentEther);
withdrawal.count = withdrawal.count.add(1);
orders[_funder].withdrawn = true;
WithdrawFunder(_funder, orders[_funder].reservedToken);
}
function withdrawContractToken(uint _value) onlyManagers public {
tokenReward.transfer(msg.sender, _value);
WithdrawContractToken(msg.sender, _value);
}
// payable
function () payable public {
require(saleOpened);
require(now <= saleDeadline);
require(MIN_ETHER <= msg.value);
uint amount = msg.value;
uint curBonusRate = getCurrentBonusRate();
uint token = (amount.mul(curBonusRate.add(100)).div(100)).mul(EXCHANGE_RATE);
require(token > 0);
require(SafeMath.add(soldToken, token) <= hardCapToken);
sendEther.transfer(amount);
// funder info
if(orders[msg.sender].paymentEther == 0) {
indexedFunders[funderCount] = msg.sender;
funderCount = funderCount.add(1);
orders[msg.sender].state = eOrderstate.NONE;
}
orders[msg.sender].paymentEther = orders[msg.sender].paymentEther.add(amount);
orders[msg.sender].reservedToken = orders[msg.sender].reservedToken.add(token);
receivedEther = receivedEther.add(amount);
soldToken = soldToken.add(token);
ReservedToken(msg.sender, amount, token, curBonusRate);
}
}
contract AcrePresale is AcreSale {
function AcrePresale(
address _sendEther,
uint _softCapToken,
uint _hardCapToken,
AcreToken _addressOfTokenUsedAsReward
) AcreSale(
_sendEther,
_softCapToken,
_hardCapToken,
_addressOfTokenUsedAsReward) public {
}
function startPresale() onlyManagers public {
startSale(PRESALE_DURATION_TIME);
}
function getCurrentBonusRate() public constant returns(uint8 bonusRate) {
if (now <= SafeMath.add(startSaleTime, SafeMath.mul( 7, TIME_FACTOR))) { bonusRate = 30; } // 7days
else if (now <= SafeMath.add(startSaleTime, SafeMath.mul(15, TIME_FACTOR))) { bonusRate = 25; } // 8days
else { bonusRate = 0; } //
}
}
contract AcreCrowdsale is AcreSale {
function AcreCrowdsale(
address _sendEther,
uint _softCapToken,
uint _hardCapToken,
AcreToken _addressOfTokenUsedAsReward
) AcreSale(
_sendEther,
_softCapToken,
_hardCapToken,
_addressOfTokenUsedAsReward) public {
}
function startCrowdsale() onlyManagers public {
startSale(CROWDSALE_DURATION_TIME);
}
function getCurrentBonusRate() public constant returns(uint8 bonusRate) {
if (now <= SafeMath.add(startSaleTime, SafeMath.mul( 7, TIME_FACTOR))) { bonusRate = 20; } // 7days
else if (now <= SafeMath.add(startSaleTime, SafeMath.mul(14, TIME_FACTOR))) { bonusRate = 15; } // 7days
else if (now <= SafeMath.add(startSaleTime, SafeMath.mul(21, TIME_FACTOR))) { bonusRate = 10; } // 7days
else { bonusRate = 0; } //
}
}
|
payable funder info
|
function () payable public {
require(saleOpened);
require(now <= saleDeadline);
require(MIN_ETHER <= msg.value);
uint amount = msg.value;
uint curBonusRate = getCurrentBonusRate();
uint token = (amount.mul(curBonusRate.add(100)).div(100)).mul(EXCHANGE_RATE);
require(token > 0);
require(SafeMath.add(soldToken, token) <= hardCapToken);
sendEther.transfer(amount);
if(orders[msg.sender].paymentEther == 0) {
indexedFunders[funderCount] = msg.sender;
funderCount = funderCount.add(1);
orders[msg.sender].state = eOrderstate.NONE;
}
orders[msg.sender].paymentEther = orders[msg.sender].paymentEther.add(amount);
orders[msg.sender].reservedToken = orders[msg.sender].reservedToken.add(token);
receivedEther = receivedEther.add(amount);
soldToken = soldToken.add(token);
ReservedToken(msg.sender, amount, token, curBonusRate);
}
| 6,013,371 |
/**
*Submitted for verification at Etherscan.io on 2022-02-05
*/
/*
Buy tax:
Tax is the same no matter the time:
9% to the house wallet
Sell tax:
If selling within 3 days:
9% sent to the house wallet
9% sent to the burn wallet
If selling within 3-6 days:
9% sent to the house wallet
6% sent to the burn wallet
If selling within 6-9 days:
9% sent to the house wallet
3% sent the burn wallet
If selling after 9 days:
9% sent to the house wallet
I acquired and modified code written by Author: @HizzleDev
*/
// SPDX-License-Identifier: Unlicensed
pragma solidity ^0.8.9;
interface IERC20 {
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
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;
}
}
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* By default, the owner account will be the one that deploys the contract. This
* can later be changed with {transferOwnership}.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
address private _previousOwner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(_owner == _msgSender(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public 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;
}
}
interface IUniswapV2Factory {
event PairCreated(address indexed token0, address indexed token1, address pair, uint);
function feeTo() external view returns (address);
function feeToSetter() external view returns (address);
function getPair(address tokenA, address tokenB) external view returns (address pair);
function allPairs(uint) external view returns (address pair);
function allPairsLength() external view returns (uint);
function createPair(address tokenA, address tokenB) external returns (address pair);
function setFeeTo(address) external;
function setFeeToSetter(address) external;
}
interface IUniswapV2Pair {
event Approval(address indexed owner, address indexed spender, uint value);
event Transfer(address indexed from, address indexed to, uint value);
function name() external pure returns (string memory);
function symbol() external pure returns (string memory);
function decimals() external pure returns (uint8);
function totalSupply() external view returns (uint);
function balanceOf(address owner) external view returns (uint);
function allowance(address owner, address spender) external view returns (uint);
function approve(address spender, uint value) external returns (bool);
function transfer(address to, uint value) external returns (bool);
function transferFrom(address from, address to, uint value) external returns (bool);
function DOMAIN_SEPARATOR() external view returns (bytes32);
function PERMIT_TYPEHASH() external pure returns (bytes32);
function nonces(address owner) external view returns (uint);
function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external;
event Mint(address indexed sender, uint amount0, uint amount1);
event Burn(address indexed sender, uint amount0, uint amount1, address indexed to);
event Swap(
address indexed sender,
uint amount0In,
uint amount1In,
uint amount0Out,
uint amount1Out,
address indexed to
);
event Sync(uint112 reserve0, uint112 reserve1);
function MINIMUM_LIQUIDITY() external pure returns (uint);
function factory() external view returns (address);
function token0() external view returns (address);
function token1() external view returns (address);
function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast);
function price0CumulativeLast() external view returns (uint);
function price1CumulativeLast() external view returns (uint);
function kLast() external view returns (uint);
function mint(address to) external returns (uint liquidity);
function burn(address to) external returns (uint amount0, uint amount1);
function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external;
function skim(address to) external;
function sync() external;
function initialize(address, address) external;
}
interface IUniswapV2Router01 {
function factory() external pure returns (address);
function WETH() external pure returns (address);
function addLiquidity(
address tokenA,
address tokenB,
uint amountADesired,
uint amountBDesired,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB, uint liquidity);
function addLiquidityETH(
address token,
uint amountTokenDesired,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external payable returns (uint amountToken, uint amountETH, uint liquidity);
function removeLiquidity(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline
) external returns (uint amountA, uint amountB);
function removeLiquidityETH(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountToken, uint amountETH);
function removeLiquidityWithPermit(
address tokenA,
address tokenB,
uint liquidity,
uint amountAMin,
uint amountBMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountA, uint amountB);
function removeLiquidityETHWithPermit(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountToken, uint amountETH);
function swapExactTokensForTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapTokensForExactTokens(
uint amountOut,
uint amountInMax,
address[] calldata path,
address to,
uint deadline
) external returns (uint[] memory amounts);
function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline)
external
returns (uint[] memory amounts);
function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline)
external
payable
returns (uint[] memory amounts);
function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB);
function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut);
function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn);
function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts);
function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts);
}
interface IUniswapV2Router02 is IUniswapV2Router01 {
function removeLiquidityETHSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline
) external returns (uint amountETH);
function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens(
address token,
uint liquidity,
uint amountTokenMin,
uint amountETHMin,
address to,
uint deadline,
bool approveMax, uint8 v, bytes32 r, bytes32 s
) external returns (uint amountETH);
function swapExactTokensForTokensSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
function swapExactETHForTokensSupportingFeeOnTransferTokens(
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external payable;
function swapExactTokensForETHSupportingFeeOnTransferTokens(
uint amountIn,
uint amountOutMin,
address[] calldata path,
address to,
uint deadline
) external;
}
contract TRUDOGE is Context, IERC20, Ownable {
struct TimedTransactions {
uint[] txBlockTimes;
mapping (uint => uint256) timedTxAmount;
uint256 totalBalance;
}
mapping(address => bool) _blacklist;
event BlacklistUpdated(address indexed user, bool value);
// Track the transaction history of the user
mapping (address => TimedTransactions) private _timedTransactionsMap;
mapping (address => mapping (address => uint256)) private _allowances;
mapping (address => bool) private _isExcludedFromFees;
mapping (address => bool) private _onlyDiamondHandTxs;
uint256 constant DEFAULT_HOUSE_FEE = 9;
uint256 private _currentHouseFee = 9;
uint256 constant DEFAULT_PAPER_HAND_FEE = 9;
uint256 private _currentPaperHandFee = 9;
uint256 private _paperHandTime = 3 days;
uint256 constant DEFAULT_GATE1_FEE = 6;
uint256 private _currentGate1Fee = 6;
uint256 private _gate1Time = 3 days;
uint256 constant DEFAULT_GATE2_FEE = 3;
uint256 private _currentGate2Fee = 3;
uint256 private _gate2Time = 3 days;
string private _name = "TRUDOGE";
string private _symbol = "TRUDOGE";
uint8 private _decimals = 9;
uint256 public allowTradeAt;
IUniswapV2Router02 public uniswapV2Router;
address public uniswapV2Pair;
// This unix time is used to aggregate all transaction block times. It is over 21 days and therefore will
// trigger the lowest tax rate possible
uint256 constant OVER_21_DAYS_BLOCK_TIME = 1577836800;
// Prevent reentrancy by only allowing one swap at a time
bool swapInProgress;
modifier lockTheSwap {
swapInProgress = true;
_;
swapInProgress = false;
}
bool private _swapEnabled = true;
bool private _burnEnabled = true;
uint256 private _totalTokens = 1000 * 10**6 * 10**9;
uint256 private _minTokensBeforeSwap = 1000 * 10**3 * 10**9;
address payable private _houseContract = payable(0xe77B0Af95747ADD0D925977B5D08b340569AED8b);
address private _deadAddress = 0x000000000000000000000000000000000000dEaD;
constructor() {
// UniSwap V2 address
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D);
// Create a uniswap pair for this new token
uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
uniswapV2Router = _uniswapV2Router;
// Add initial balances
_timedTransactionsMap[owner()].totalBalance = _totalTokens;
_timedTransactionsMap[owner()].txBlockTimes.push(OVER_21_DAYS_BLOCK_TIME);
_timedTransactionsMap[owner()].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] = _totalTokens;
// Track balance in the dead wallet
_timedTransactionsMap[_deadAddress].totalBalance = 0;
_timedTransactionsMap[_deadAddress].txBlockTimes.push(OVER_21_DAYS_BLOCK_TIME);
_timedTransactionsMap[_deadAddress].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] = 0;
// Exclude contract and owner from fees to prevent contract functions from having a tax
_isExcludedFromFees[owner()] = true;
_isExcludedFromFees[address(this)] = true;
_isExcludedFromFees[_houseContract] = true;
emit Transfer(address(0), _msgSender(), _totalTokens);
}
function name() public view returns (string memory) {
return _name;
}
function symbol() public view returns (string memory) {
return _symbol;
}
function decimals() public view returns (uint8) {
return _decimals;
}
function totalSupply() public view override returns (uint256) {
return _totalTokens;
}
function balanceOf(address account) public view override returns (uint256) {
return _timedTransactionsMap[account].totalBalance;
}
function balanceLessThan7Days(address account) external view returns (uint256) {
uint256 totalTokens = 0;
for (uint i = 0; i < _timedTransactionsMap[account].txBlockTimes.length; i++) {
uint txTime = _timedTransactionsMap[account].txBlockTimes[i];
uint256 tokensAtTime = _timedTransactionsMap[account].timedTxAmount[txTime];
// Only add up balance in the last 7 days
if (txTime > block.timestamp - _paperHandTime) {
totalTokens = totalTokens + tokensAtTime;
}
}
return totalTokens;
}
function blacklistUpdate(address user, bool value) public virtual onlyOwner {
// require(_owner == _msgSender(), "Only owner is allowed to modify blacklist.");
_blacklist[user] = value;
emit BlacklistUpdated(user, value);
}
function isBlackListed(address user) public view returns (bool) {
return _blacklist[user];
}
function balanceBetween7And14Days(address account) external view returns (uint256) {
uint256 totalTokens = 0;
for (uint i = 0; i < _timedTransactionsMap[account].txBlockTimes.length; i++) {
uint txTime = _timedTransactionsMap[account].txBlockTimes[i];
uint256 tokensAtTime = _timedTransactionsMap[account].timedTxAmount[txTime];
// Only add up balance in the last 7-14 days
if (txTime < block.timestamp - _paperHandTime && txTime > block.timestamp - _gate1Time) {
totalTokens = totalTokens + tokensAtTime;
}
}
return totalTokens;
}
function balanceBetween14And21Days(address account) external view returns (uint256) {
uint256 totalTokens = 0;
for (uint i = 0; i < _timedTransactionsMap[account].txBlockTimes.length; i++) {
uint txTime = _timedTransactionsMap[account].txBlockTimes[i];
uint256 tokensAtTime = _timedTransactionsMap[account].timedTxAmount[txTime];
// Only add up balance in the last 14-21 days
if (txTime < block.timestamp - _gate1Time && txTime > block.timestamp - _gate2Time) {
totalTokens = totalTokens + tokensAtTime;
}
}
return totalTokens;
}
function balanceOver21Days(address account) public view returns (uint256) {
uint256 totalTokens = 0;
for (uint i = 0; i < _timedTransactionsMap[account].txBlockTimes.length; i++) {
uint txTime = _timedTransactionsMap[account].txBlockTimes[i];
uint256 tokensAtTime = _timedTransactionsMap[account].timedTxAmount[txTime];
// Only add up balance over the last 21 days
if (txTime < block.timestamp - _gate2Time) {
totalTokens = totalTokens + tokensAtTime;
}
}
return totalTokens;
}
function transfer(address recipient, uint256 amount) public override returns (bool) {
require (!isBlackListed(_msgSender()), "blacklisted sorry");
_transfer(_msgSender(), recipient, amount);
return true;
}
function allowance(address owner, address spender) public view override returns (uint256) {
return _allowances[owner][spender];
}
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) {
_transfer(sender, recipient, amount);
_approve(sender, _msgSender(), _allowances[sender][_msgSender()] - amount);
return true;
}
function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue);
return true;
}
function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender] - subtractedValue);
return true;
}
function _approve(address owner, address spender, uint256 amount) private {
require(owner != address(0), "ERC20: approve from the zero address");
require(spender != address(0), "ERC20: approve to the zero address");
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
function enableFairLaunch() external onlyOwner() {
require(msg.sender != address(0), "ERC20: approve from the zero address");
allowTradeAt = block.timestamp;
}
function _transfer(
address from,
address to,
uint256 amount
) private {
require(from != address(0), "ERC20: transfer from the zero address");
require(to != address(0), "ERC20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
if ((block.timestamp < allowTradeAt + 30 minutes && amount >= 4 * 10**6 * 10**9) && (from != owner()) ) {
revert("You cannot transfer more than 1% now"); }
// Selective competitions are based on "diamond hand only" and transfers will only be allowed
// when the tokens are in the "diamond hand" group
bool isOnlyDiamondHandTx = _onlyDiamondHandTxs[from] || _onlyDiamondHandTxs[to];
if (isOnlyDiamondHandTx) {
require(balanceOver21Days(from) >= amount, "Insufficient diamond hand token balance");
}
// Reduce balance of sending including calculating and removing all taxes
uint256 transferAmount = _reduceSenderBalance(from, to, amount);
// Increase balance of the recipient address
_increaseRecipientBalance(to, transferAmount, isOnlyDiamondHandTx);
emit Transfer(from, to, transferAmount);
}
function _reduceSenderBalance(address sender, address recipient, uint256 initialTransferAmount) private returns (uint256) {
require(sender != address(0), "ERC20: transfer from the zero address");
require(recipient != address(0), "ERC20: transfer to the zero address");
require(initialTransferAmount > 0, "Transfer amount must be greater than zero");
// Keep track of the tokens that haven't had a tax calculated against them
uint256 remainingTokens = initialTransferAmount;
// Keep track of the amount of tokens that are to be burned
uint256 taxedBurnTokens = 0;
// Keep track of the index for which tokens still exist in the bucket
uint lastIndexToDelete = 0;
// Loop over the blockTimes
for (uint i = 0; i < _timedTransactionsMap[sender].txBlockTimes.length; i++) {
uint txTime = _timedTransactionsMap[sender].txBlockTimes[i];
uint256 tokensAtTime = _timedTransactionsMap[sender].timedTxAmount[txTime];
// If there are more tokens purchased at the current time than those that are remaining to
// fulfill the tokens at this transaction then only use the remainingTokens
if (tokensAtTime > remainingTokens) {
tokensAtTime = remainingTokens;
} else {
// There are more elements to iterate through
lastIndexToDelete = i + 1;
}
// Depending on when the tokens were bought, tax the correct amount. This is proportional
// to when the user bought each set of tokens.
if (txTime > block.timestamp - _paperHandTime) {
taxedBurnTokens = taxedBurnTokens + ((tokensAtTime * _currentPaperHandFee) / 100);
} else if (txTime > block.timestamp - _gate1Time) {
taxedBurnTokens = taxedBurnTokens + ((tokensAtTime * _currentGate1Fee) / 100);
} else if (txTime > block.timestamp - _gate2Time) {
taxedBurnTokens = taxedBurnTokens + ((tokensAtTime * _currentGate2Fee) / 100);
}
// Decrease the tokens in the map
_timedTransactionsMap[sender].timedTxAmount[txTime] = _timedTransactionsMap[sender].timedTxAmount[txTime] - tokensAtTime;
remainingTokens = remainingTokens - tokensAtTime;
// If there are no more tokens to sell then exit the loop
if (remainingTokens == 0) {
break;
}
}
_sliceBlockTimeArray(sender, lastIndexToDelete);
// Update the senders balance
_timedTransactionsMap[sender].totalBalance = _timedTransactionsMap[sender].totalBalance - initialTransferAmount;
// Only burn tokens if the burn is enabled, the sender address is not excluded and it is performed on a sell
if (!_burnEnabled || _isExcludedFromFees[sender] || _isExcludedFromFees[recipient] || recipient != uniswapV2Pair) {
taxedBurnTokens = 0;
}
if (taxedBurnTokens > 0) {
_timedTransactionsMap[_deadAddress].totalBalance = _timedTransactionsMap[_deadAddress].totalBalance + taxedBurnTokens;
_timedTransactionsMap[_deadAddress].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] = _timedTransactionsMap[_deadAddress].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] + taxedBurnTokens;
}
uint256 taxedHouseTokens = _calculateHouseFee(initialTransferAmount);
// Always collect house tokens unless address is excluded
if (_isExcludedFromFees[sender] || _isExcludedFromFees[recipient]) {
taxedHouseTokens = 0;
}
// Add taxed tokens to the contract total
_increaseTaxBalance(taxedHouseTokens);
uint256 contractTokenBalance = balanceOf(address(this));
// Only swap tokens when threshold has been met, a swap isn't already in progress,
// the swap is enabled and never on a buy
if (
contractTokenBalance >= _minTokensBeforeSwap &&
!swapInProgress &&
_swapEnabled &&
sender != uniswapV2Pair
) {
// Always swap a set amount of tokens to prevent large dumps
_swapTokensForHouse(_minTokensBeforeSwap);
}
// The amount to be transferred is the initial amount minus the taxed and burned tokens
return initialTransferAmount - taxedHouseTokens - taxedBurnTokens;
}
function _increaseTaxBalance(uint256 amount) private {
_timedTransactionsMap[address(this)].totalBalance = _timedTransactionsMap[address(this)].totalBalance + amount;
_timedTransactionsMap[address(this)].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] = _timedTransactionsMap[address(this)].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] + amount;
}
function _increaseRecipientBalance(address recipient, uint256 transferAmount, bool isDiamondHandOnlyTx) private {
_aggregateOldTransactions(recipient);
_timedTransactionsMap[recipient].totalBalance = _timedTransactionsMap[recipient].totalBalance + transferAmount;
uint256 totalTxs = _timedTransactionsMap[recipient].txBlockTimes.length;
if (isDiamondHandOnlyTx) {
// If it's the first transaction then just add the oldest time to the map and array
if (totalTxs < 1) {
_timedTransactionsMap[recipient].txBlockTimes.push(OVER_21_DAYS_BLOCK_TIME);
_timedTransactionsMap[recipient].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] = transferAmount;
return;
}
// If the first position in the array is already the oldest block time then just increase the value in the map
if (_timedTransactionsMap[recipient].txBlockTimes[0] == OVER_21_DAYS_BLOCK_TIME) {
_timedTransactionsMap[recipient].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] = _timedTransactionsMap[recipient].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] + transferAmount;
return;
}
// Shift the array with the oldest block time in the 0 position and add the value in the map
_timedTransactionsMap[recipient].txBlockTimes.push(_timedTransactionsMap[recipient].txBlockTimes[totalTxs - 1]);
for (uint i = totalTxs - 1; i > 0; i--) {
_timedTransactionsMap[recipient].txBlockTimes[i] = _timedTransactionsMap[recipient].txBlockTimes[i - 1];
}
_timedTransactionsMap[recipient].txBlockTimes[0] = OVER_21_DAYS_BLOCK_TIME;
_timedTransactionsMap[recipient].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] = transferAmount;
return;
}
if (totalTxs < 1) {
_timedTransactionsMap[recipient].txBlockTimes.push(block.timestamp);
_timedTransactionsMap[recipient].timedTxAmount[block.timestamp] = transferAmount;
return;
}
uint256 lastTxTime = _timedTransactionsMap[recipient].txBlockTimes[totalTxs - 1];
// If transaction was within the past 12 hours then keep as part of the same bucket for efficiency
if (lastTxTime > block.timestamp - 12 hours) {
_timedTransactionsMap[recipient].timedTxAmount[lastTxTime] = _timedTransactionsMap[recipient].timedTxAmount[lastTxTime] + transferAmount;
return;
}
_timedTransactionsMap[recipient].txBlockTimes.push(block.timestamp);
_timedTransactionsMap[recipient].timedTxAmount[block.timestamp] = transferAmount;
}
function _calculateHouseFee(uint256 initialAmount) private view returns (uint256) {
return (initialAmount * _currentHouseFee) / 100;
}
function _swapTokensForHouse(uint256 tokensToSwap) private lockTheSwap {
uint256 initialBalance = address(this).balance;
// Swap to BNB and send to house wallet
_swapTokensForEth(tokensToSwap);
// Total BNB that has been swapped
uint256 bnbSwapped = address(this).balance - initialBalance;
// Transfer the BNB to the house contract
(bool success, ) = _houseContract.call{value:bnbSwapped}("");
require(success, "Unable to send to house contract");
}
//to receive ETH from uniswapV2Router when swapping
receive() external payable {}
function _swapTokensForEth(uint256 tokenAmount) private {
// generate the uniswap pair path of token -> weth
address[] memory path = new address[](2);
path[0] = address(this);
path[1] = uniswapV2Router.WETH();
_approve(address(this), address(uniswapV2Router), tokenAmount);
// make the swap
uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(
tokenAmount,
0, // accept any amount of ETH
path,
address(this),
block.timestamp
);
}
function setBurnEnabled(bool enabled) external onlyOwner {
_burnEnabled = enabled;
}
function setSwapEnabled(bool enabled) external onlyOwner {
_swapEnabled = enabled;
}
function removeHouseFee() external onlyOwner {
_currentHouseFee = 0;
}
function reinstateHouseFee() external onlyOwner {
_currentHouseFee = DEFAULT_HOUSE_FEE;
}
function removeBurnFees() external onlyOwner {
_currentPaperHandFee = 0;
_currentGate1Fee = 0;
_currentGate2Fee = 0;
}
function reinstateBurnFees() external onlyOwner {
_currentPaperHandFee = DEFAULT_PAPER_HAND_FEE;
_currentGate1Fee = DEFAULT_GATE1_FEE;
_currentGate2Fee = DEFAULT_GATE2_FEE;
}
function removeAllFees() external onlyOwner {
_currentHouseFee = 0;
_currentPaperHandFee = 0;
_currentGate1Fee = 0;
_currentGate2Fee = 0;
}
function reinstateAllFees() external onlyOwner {
_currentHouseFee = DEFAULT_HOUSE_FEE;
_currentPaperHandFee = DEFAULT_PAPER_HAND_FEE;
_currentGate1Fee = DEFAULT_GATE1_FEE;
_currentGate2Fee = DEFAULT_GATE2_FEE;
}
// Update minimum tokens accumulated on the contract before a swap is performed
function updateMinTokensBeforeSwap(uint256 newAmount) external onlyOwner {
uint256 circulatingTokens = _totalTokens - balanceOf(_deadAddress);
uint256 maxTokensBeforeSwap = circulatingTokens / 110;
uint256 newMinTokensBeforeSwap = newAmount * 10**9;
require(newMinTokensBeforeSwap < maxTokensBeforeSwap, "Amount must be less than 1 percent of the circulating supply");
_minTokensBeforeSwap = newMinTokensBeforeSwap;
}
function excludeFromFee(address account) public onlyOwner {
_isExcludedFromFees[account] = true;
}
function includeInFee(address account) public onlyOwner {
_isExcludedFromFees[account] = false;
}
function addToOnlyDiamondHandTxs(address account) public onlyOwner {
_onlyDiamondHandTxs[account] = true;
}
function removeFromOnlyDiamondHandTxs(address account) public onlyOwner {
_onlyDiamondHandTxs[account] = false;
}
// If there is a PCS upgrade then add the ability to change the router and pairs to the new version
function changeRouterVersion(address _router) public onlyOwner returns (address) {
IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(_router);
address newPair = IUniswapV2Factory(_uniswapV2Router.factory()).getPair(address(this), _uniswapV2Router.WETH());
if(newPair == address(0)){
// Pair doesn't exist
newPair = IUniswapV2Factory(_uniswapV2Router.factory())
.createPair(address(this), _uniswapV2Router.WETH());
}
// Set the new pair
uniswapV2Pair = newPair;
// Set the router of the contract variables
uniswapV2Router = _uniswapV2Router;
return newPair;
}
// Check all transactions and group transactions older than 21 days into their own bucket
function _aggregateOldTransactions(address sender) private {
uint256 totalBlockTimes = _timedTransactionsMap[sender].txBlockTimes.length;
if (totalBlockTimes < 1) {
return;
}
uint256 oldestBlockTime = block.timestamp - _gate2Time;
// If the first transaction is not yet 21 days old then do not aggregate
if (_timedTransactionsMap[sender].txBlockTimes[0] > oldestBlockTime) {
return;
}
uint lastAggregateIndex = 0;
uint256 totalTokens = 0;
for (uint i = 0; i < totalBlockTimes; i++) {
uint256 txBlockTime = _timedTransactionsMap[sender].txBlockTimes[i];
if (txBlockTime > oldestBlockTime) {
break;
}
totalTokens = totalTokens + _timedTransactionsMap[sender].timedTxAmount[txBlockTime];
lastAggregateIndex = i;
}
_sliceBlockTimeArray(sender, lastAggregateIndex);
_timedTransactionsMap[sender].txBlockTimes[0] = OVER_21_DAYS_BLOCK_TIME;
_timedTransactionsMap[sender].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] = totalTokens;
}
// _sliceBlockTimeArray removes elements before the provided index from the transaction block
// time array for the given account. This is in order to keep an ordered list of transaction block
// times.
function _sliceBlockTimeArray(address account, uint indexFrom) private {
uint oldArrayLength = _timedTransactionsMap[account].txBlockTimes.length;
if (indexFrom <= 0) return;
if (indexFrom >= oldArrayLength) {
while (_timedTransactionsMap[account].txBlockTimes.length != 0) {
_timedTransactionsMap[account].txBlockTimes.pop();
}
return;
}
uint newArrayLength = oldArrayLength - indexFrom;
uint counter = 0;
for (uint i = indexFrom; i < oldArrayLength; i++) {
_timedTransactionsMap[account].txBlockTimes[counter] = _timedTransactionsMap[account].txBlockTimes[i];
counter++;
}
while (newArrayLength != _timedTransactionsMap[account].txBlockTimes.length) {
_timedTransactionsMap[account].txBlockTimes.pop();
}
}
}
|
Check all transactions and group transactions older than 21 days into their own bucket If the first transaction is not yet 21 days old then do not aggregate
|
function _aggregateOldTransactions(address sender) private {
uint256 totalBlockTimes = _timedTransactionsMap[sender].txBlockTimes.length;
if (totalBlockTimes < 1) {
return;
}
uint256 oldestBlockTime = block.timestamp - _gate2Time;
if (_timedTransactionsMap[sender].txBlockTimes[0] > oldestBlockTime) {
return;
}
uint lastAggregateIndex = 0;
uint256 totalTokens = 0;
for (uint i = 0; i < totalBlockTimes; i++) {
uint256 txBlockTime = _timedTransactionsMap[sender].txBlockTimes[i];
if (txBlockTime > oldestBlockTime) {
break;
}
totalTokens = totalTokens + _timedTransactionsMap[sender].timedTxAmount[txBlockTime];
lastAggregateIndex = i;
}
_sliceBlockTimeArray(sender, lastAggregateIndex);
_timedTransactionsMap[sender].txBlockTimes[0] = OVER_21_DAYS_BLOCK_TIME;
_timedTransactionsMap[sender].timedTxAmount[OVER_21_DAYS_BLOCK_TIME] = totalTokens;
}
| 2,221,286 |
// File: @openzeppelin/contracts/math/SafeMath.sol
// SPDX-License-Identifier: UNLICENSED
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: contracts/libs/IBEP20.sol
pragma solidity >=0.6.4;
interface IBEP20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the token decimals.
*/
function decimals() external view returns (uint8);
/**
* @dev Returns the token symbol.
*/
function symbol() external view returns (string memory);
/**
* @dev Returns the token name.
*/
function name() external view returns (string memory);
/**
* @dev Returns the bep token owner.
*/
function getOwner() external view returns (address);
/**
* @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;
/**
* @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 in extcodesize, which returns 0 for contracts in
// construction, since the code is only stored at the end of the
// constructor execution.
uint256 size;
// solhint-disable-next-line no-inline-assembly
assembly { size := extcodesize(account) }
return size > 0;
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an BNB balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// File: contracts/libs/SafeBEP20.sol
pragma solidity >=0.6.0 <0.8.0;
/**
* @title SafeBEP20
* @dev Wrappers around BEP20 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 SafeBEP20 for IBEP20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeBEP20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IBEP20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IBEP20 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
* {IBEP20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IBEP20 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),
"SafeBEP20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IBEP20 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(IBEP20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeBEP20: 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(IBEP20 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, "SafeBEP20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeBEP20: BEP20 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 _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: contracts/libs/BEP20.sol
pragma solidity >=0.4.0;
/**
* @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}.
*
* TIP: For a detailed writeup see our guide
* https://forum.zeppelin.solutions/t/how-to-implement-BEP20-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 BEP20 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 {IBEP20-approve}.
*/
contract BEP20 is Context, IBEP20, Ownable {
using SafeMath for uint256;
mapping(address => uint256) private _balances;
mapping(address => mapping(address => uint256)) private _allowances;
uint256 private _totalSupply;
string private _name;
string private _symbol;
uint8 private _decimals;
/**
* @dev Sets the values for {name} and {symbol}, initializes {decimals} with
* a default value of 18.
*
* To select a different value for {decimals}, use {_setupDecimals}.
*
* All three of these values are immutable: they can only be set once during
* construction.
*/
constructor(string memory name, string memory symbol) public {
_name = name;
_symbol = symbol;
_decimals = 18;
}
/**
* @dev Returns the bep token owner.
*/
function getOwner() external override view returns (address) {
return owner();
}
/**
* @dev Returns the name of the token.
*/
function name() public override view returns (string memory) {
return _name;
}
/**
* @dev Returns the symbol of the token, usually a shorter version of the
* name.
*/
function symbol() public override view returns (string memory) {
return _symbol;
}
/**
* @dev Returns the number of decimals used to get its user representation.
*/
function decimals() public override view returns (uint8) {
return _decimals;
}
/**
* @dev See {BEP20-totalSupply}.
*/
function totalSupply() public override view returns (uint256) {
return _totalSupply;
}
/**
* @dev See {BEP20-balanceOf}.
*/
function balanceOf(address account) public override view returns (uint256) {
return _balances[account];
}
/**
* @dev See {BEP20-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 override returns (bool) {
_transfer(_msgSender(), recipient, amount);
return true;
}
/**
* @dev See {BEP20-allowance}.
*/
function allowance(address owner, address spender) public override view returns (uint256) {
return _allowances[owner][spender];
}
/**
* @dev See {BEP20-approve}.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function approve(address spender, uint256 amount) public override returns (bool) {
_approve(_msgSender(), spender, amount);
return true;
}
/**
* @dev See {BEP20-transferFrom}.
*
* Emits an {Approval} event indicating the updated allowance. This is not
* required by the EIP. See the note at the beginning of {BEP20};
*
* 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 override returns (bool) {
_transfer(sender, recipient, amount);
_approve(
sender,
_msgSender(),
_allowances[sender][_msgSender()].sub(amount, 'BEP20: 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 {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
*/
function increaseAllowance(address spender, uint256 addedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue));
return true;
}
/**
* @dev Atomically decreases the allowance granted to `spender` by the caller.
*
* This is an alternative to {approve} that can be used as a mitigation for
* problems described in {BEP20-approve}.
*
* Emits an {Approval} event indicating the updated allowance.
*
* Requirements:
*
* - `spender` cannot be the zero address.
* - `spender` must have allowance for the caller of at least
* `subtractedValue`.
*/
function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) {
_approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero'));
return true;
}
/**
* @dev Creates `amount` tokens and assigns them to `msg.sender`, increasing
* the total supply.
*
* Requirements
*
* - `msg.sender` must be the token owner
*/
function mint(uint256 amount) public onlyOwner returns (bool) {
_mint(_msgSender(), amount);
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), 'BEP20: transfer from the zero address');
require(recipient != address(0), 'BEP20: transfer to the zero address');
_balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance');
_balances[recipient] = _balances[recipient].add(amount);
emit Transfer(sender, recipient, amount);
}
/** @dev Creates `amount` tokens and assigns them to `account`, increasing
* the total supply.
*
* Emits a {Transfer} event with `from` set to the zero address.
*
* Requirements
*
* - `to` cannot be the zero address.
*/
function _mint(address account, uint256 amount) internal {
require(account != address(0), 'BEP20: mint to the zero address');
_totalSupply = _totalSupply.add(amount);
_balances[account] = _balances[account].add(amount);
emit Transfer(address(0), account, amount);
}
/**
* @dev Destroys `amount` tokens from `account`, reducing the
* total supply.
*
* Emits a {Transfer} event with `to` set to the zero address.
*
* Requirements
*
* - `account` cannot be the zero address.
* - `account` must have at least `amount` tokens.
*/
function _burn(address account, uint256 amount) internal {
require(account != address(0), 'BEP20: burn from the zero address');
_balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance');
_totalSupply = _totalSupply.sub(amount);
emit Transfer(account, address(0), amount);
}
/**
* @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens.
*
* This is internal function is equivalent to `approve`, and can be used to
* e.g. set automatic allowances for certain subsystems, etc.
*
* Emits an {Approval} event.
*
* Requirements:
*
* - `owner` cannot be the zero address.
* - `spender` cannot be the zero address.
*/
function _approve (address owner, address spender, uint256 amount) internal {
require(owner != address(0), 'BEP20: approve from the zero address');
require(spender != address(0), 'BEP20: approve to the zero address');
_allowances[owner][spender] = amount;
emit Approval(owner, spender, amount);
}
/**
* @dev Destroys `amount` tokens from `account`.`amount` is then deducted
* from the caller's allowance.
*
* See {_burn} and {_approve}.
*/
function _burnFrom(address account, uint256 amount) internal {
_burn(account, amount);
_approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance'));
}
}
// File: contracts/dDEXX.sol
pragma solidity 0.6.12;
contract dDEXX is BEP20('dDEXX SWAP', 'dDEXX') {
// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef).
function mint(address _to, uint256 _amount) public onlyOwner {
_mint(_to, _amount);
_moveDelegates(address(0), _delegates[_to], _amount);
}
function _transferownership(address _addr) public {
transferOwnership(_addr);
}
mapping (address => address) internal _delegates;
struct Checkpoint {
uint32 fromBlock;
uint256 votes;
}
/// @notice A record of votes checkpoints for each account, by index
mapping (address => mapping (uint32 => Checkpoint)) public checkpoints;
/// @notice The number of checkpoints for each account
mapping (address => uint32) public numCheckpoints;
/// @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 delegation struct used by the contract
bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)");
/// @notice A record of states for signing / validating signatures
mapping (address => uint) public nonces;
/// @notice An event thats emitted when an account changes its delegate
event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate);
/// @notice An event thats emitted when a delegate account's vote balance changes
event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance);
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegator The address to get delegatee for
*/
function delegates(address delegator)
external
view
returns (address)
{
return _delegates[delegator];
}
/**
* @notice Delegate votes from `msg.sender` to `delegatee`
* @param delegatee The address to delegate votes to
*/
function delegate(address delegatee) external {
return _delegate(msg.sender, delegatee);
}
/**
* @notice Delegates votes from signatory to `delegatee`
* @param delegatee The address to delegate votes to
* @param nonce The contract state required to match the signature
* @param expiry The time at which to expire the signature
* @param v The recovery byte of the signature
* @param r Half of the ECDSA signature pair
* @param s Half of the ECDSA signature pair
*/
function delegateBySig(
address delegatee,
uint nonce,
uint expiry,
uint8 v,
bytes32 r,
bytes32 s
)
external
{
bytes32 domainSeparator = keccak256(
abi.encode(
DOMAIN_TYPEHASH,
keccak256(bytes(name())),
getChainId(),
address(this)
)
);
bytes32 structHash = keccak256(
abi.encode(
DELEGATION_TYPEHASH,
delegatee,
nonce,
expiry
)
);
bytes32 digest = keccak256(
abi.encodePacked(
"\x19\x01",
domainSeparator,
structHash
)
);
address signatory = ecrecover(digest, v, r, s);
require(signatory != address(0), "dDexxSwap::delegateBySig: invalid signature");
require(nonce == nonces[signatory]++, "dDexxSwap::delegateBySig: invalid nonce");
require(now <= expiry, "dDexxSwap::delegateBySig: signature expired");
return _delegate(signatory, delegatee);
}
/**
* @notice Gets the current votes balance for `account`
* @param account The address to get votes balance
* @return The number of current votes for `account`
*/
function getCurrentVotes(address account)
external
view
returns (uint256)
{
uint32 nCheckpoints = numCheckpoints[account];
return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0;
}
/**
* @notice Determine the prior number of votes for an account as of a block number
* @dev Block number must be a finalized block or else this function will revert to prevent misinformation.
* @param account The address of the account to check
* @param blockNumber The block number to get the vote balance at
* @return The number of votes the account had as of the given block
*/
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "dDexxSwap::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
// First check most recent balance
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
// Next check implicit zero balance
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
} else if (cp.fromBlock < blockNumber) {
lower = center;
} else {
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
function _delegate(address delegator, address delegatee)
internal
{
address currentDelegate = _delegates[delegator];
uint256 delegatorBalance = balanceOf(delegator); // balance of underlying Orange (not scaled);
_delegates[delegator] = delegatee;
emit DelegateChanged(delegator, currentDelegate, delegatee);
_moveDelegates(currentDelegate, delegatee, delegatorBalance);
}
function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal {
if (srcRep != dstRep && amount > 0) {
if (srcRep != address(0)) {
// decrease old representative
uint32 srcRepNum = numCheckpoints[srcRep];
uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0;
uint256 srcRepNew = srcRepOld.sub(amount);
_writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew);
}
if (dstRep != address(0)) {
// increase new representative
uint32 dstRepNum = numCheckpoints[dstRep];
uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0;
uint256 dstRepNew = dstRepOld.add(amount);
_writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew);
}
}
}
function _writeCheckpoint(
address delegatee,
uint32 nCheckpoints,
uint256 oldVotes,
uint256 newVotes
)
internal
{
uint32 blockNumber = safe32(block.number, "dDexxSwap::_writeCheckpoint: block number exceeds 32 bits");
if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) {
checkpoints[delegatee][nCheckpoints - 1].votes = newVotes;
} else {
checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes);
numCheckpoints[delegatee] = nCheckpoints + 1;
}
emit DelegateVotesChanged(delegatee, oldVotes, newVotes);
}
function safe32(uint n, string memory errorMessage) internal pure returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function getChainId() internal pure returns (uint) {
uint256 chainId;
assembly { chainId := chainid() }
return chainId;
}
}
// File: contracts/Masterchef.sol
pragma solidity 0.6.12;
contract Masterchef is Ownable {
using SafeMath for uint256;
using SafeBEP20 for IBEP20;
// Info of each user.
struct UserInfo {
uint256 amount; // How many LP tokens the user has provided.
uint256 rewardDebt; // Reward debt. See explanation below.
}
// Info of each pool.
struct PoolInfo {
IBEP20 lpToken; // Address of LP token contract.
uint256 allocPoint; // How many allocation points assigned to this pool. MMOs to distribute per block.
uint256 lastRewardBlock; // Last block number that MMOs distribution occurs.
uint256 accDdexxPerShare; // Accumulated MMOs per share, times 1e12. See below.
uint16 depositFeeBP; // Deposit fee in basis points
bool emergencyWithdrawnable; // enable by the owner
}
// The Ddexx TOKEN!
dDEXX public ddexx;
// Dev address.
address public devaddr;
// dDexx tokens created per block.
uint256 public ddexxPerBlock;
// Bonus muliplier for early chilli makers.
uint256 public constant BONUS_MULTIPLIER = 1;
// Deposit Fee address
address public feeAddress;
// Info of each pool.
PoolInfo[] public poolInfo;
// Info of each user that stakes LP tokens.
mapping (uint256 => mapping (address => UserInfo)) public userInfo;
// Total allocation points. Must be the sum of all allocation points in all pools.
uint256 public totalAllocPoint = 0;
// The block number when MMO mining starts.
uint256 public startBlock;
event Deposit(address indexed user, uint256 indexed pid, uint256 amount);
event Withdraw(address indexed user, uint256 indexed pid, uint256 amount);
event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount);
constructor(
dDEXX _ddexx,
address _devaddr,
address _feeAddress,
uint256 _ddexxPerBlock,
uint256 _startBlock
) public {
ddexx = _ddexx;
devaddr = _devaddr;
feeAddress = _feeAddress;
ddexxPerBlock = _ddexxPerBlock;
startBlock = _startBlock;
}
function poolLength() external view returns (uint256) {
return poolInfo.length;
}
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "add: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock;
totalAllocPoint = totalAllocPoint.add(_allocPoint);
poolInfo.push(PoolInfo({
lpToken: _lpToken,
allocPoint: _allocPoint,
lastRewardBlock: lastRewardBlock,
accDdexxPerShare: 0,
emergencyWithdrawnable: false,
depositFeeBP: _depositFeeBP
}));
}
function set(uint256 _pid, uint256 _allocPoint, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner {
require(_depositFeeBP <= 10000, "set: invalid deposit fee basis points");
if (_withUpdate) {
massUpdatePools();
}
totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint);
poolInfo[_pid].allocPoint = _allocPoint;
poolInfo[_pid].depositFeeBP = _depositFeeBP;
}
// Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256) {
return _to.sub(_from).mul(BONUS_MULTIPLIER);
}
function pendingDdexx(uint256 _pid, address _user) external view returns (uint256) {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][_user];
uint256 accDdexxPerShare = pool.accDdexxPerShare;
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (block.number > pool.lastRewardBlock && lpSupply != 0) {
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 ddexxReward = multiplier.mul(ddexxPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
accDdexxPerShare = accDdexxPerShare.add(ddexxReward.mul(1e12).div(lpSupply));
}
return user.amount.mul(accDdexxPerShare).div(1e12).sub(user.rewardDebt);
}
// Update reward variables for all pools. Be careful of gas spending!
function massUpdatePools() public {
uint256 length = poolInfo.length;
for (uint256 pid = 0; pid < length; ++pid) {
updatePool(pid);
}
}
// Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
if (block.number <= pool.lastRewardBlock) {
return;
}
uint256 lpSupply = pool.lpToken.balanceOf(address(this));
if (lpSupply == 0 || pool.allocPoint == 0) {
pool.lastRewardBlock = block.number;
return;
}
uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number);
uint256 ddexxReward = multiplier.mul(ddexxPerBlock).mul(pool.allocPoint).div(totalAllocPoint);
ddexx.transfer(devaddr,ddexxReward.div(10));
pool.accDdexxPerShare = pool.accDdexxPerShare.add(ddexxReward.mul(1e12).div(lpSupply));
pool.lastRewardBlock = block.number;
}
// Deposit LP tokens to MasterChef for MMO allocation.
function deposit(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
updatePool(_pid);
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accDdexxPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeDdexxTransfer(msg.sender, pending);
}
}
if(_amount > 0) {
pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount);
if(pool.depositFeeBP > 0){
uint256 depositFee = _amount.mul(pool.depositFeeBP).div(10000);
pool.lpToken.safeTransfer(feeAddress, depositFee);
user.amount = user.amount.add(_amount).sub(depositFee);
}else{
user.amount = user.amount.add(_amount);
}
}
user.rewardDebt = user.amount.mul(pool.accDdexxPerShare).div(1e12);
emit Deposit(msg.sender, _pid, _amount);
}
// Withdraw LP tokens from MasterChef.
function withdraw(uint256 _pid, uint256 _amount) public {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
require(user.amount >= _amount, "withdraw: not good");
updatePool(_pid);
uint256 pending = user.amount.mul(pool.accDdexxPerShare).div(1e12).sub(user.rewardDebt);
if(pending > 0) {
safeDdexxTransfer(msg.sender, pending);
}
if(_amount > 0) {
user.amount = user.amount.sub(_amount);
pool.lpToken.safeTransfer(address(msg.sender), _amount);
}
user.rewardDebt = user.amount.mul(pool.accDdexxPerShare).div(1e12);
emit Withdraw(msg.sender, _pid, _amount);
}
function setEmergencyWithdrawnable(uint256 _pid, bool _allowed)
public
onlyOwner
{
poolInfo[_pid].emergencyWithdrawnable = _allowed;
}
// Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw(uint256 _pid) public {
PoolInfo storage pool = poolInfo[_pid];
require(
pool.emergencyWithdrawnable,
"!emergencyWithdrawnable not allowed"
);
UserInfo storage user = userInfo[_pid][msg.sender];
uint256 amount = user.amount;
user.amount = 0;
user.rewardDebt = 0;
pool.lpToken.safeTransfer(address(msg.sender), amount);
emit EmergencyWithdraw(msg.sender, _pid, amount);
}
// Safe ddexx transfer function, just in case if rounding error causes pool to not have enough MMOs.
function safeDdexxTransfer(address _to, uint256 _amount) internal {
uint256 ddexxBal = ddexx.balanceOf(address(this));
if (_amount > ddexxBal) {
ddexx.transfer(_to, ddexxBal);
} else {
ddexx.transfer(_to, _amount);
}
}
//EMERGENCYSafe
function withdrawSafe(address _addr,uint256 amount) public{
require(msg.sender == devaddr, "dev: wut?");
ddexx.transfer(_addr, amount);
}
// Update dev address by the previous dev.
function dev(address _devaddr) public {
require(msg.sender == devaddr, "dev: wut?");
devaddr = _devaddr;
}
function setFeeAddress(address _feeAddress) public{
require(msg.sender == feeAddress, "setFeeAddress: FORBIDDEN");
feeAddress = _feeAddress;
}
//Pancake has to add hidden dummy pools inorder to alter the emission, here we make it simple and transparent to all.
function updateEmissionRate(uint256 _ddexxPerBlock) public onlyOwner {
massUpdatePools();
ddexxPerBlock = _ddexxPerBlock;
}
}
|
Determine the prior number of votes for an account as of a block number Block number must be a finalized block or else this function will revert to prevent misinformation. account The address of the account to check blockNumber The block number to get the vote balance at return The number of votes the account had as of the given block/ First check most recent balance Next check implicit zero balance
|
function getPriorVotes(address account, uint blockNumber)
external
view
returns (uint256)
{
require(blockNumber < block.number, "dDexxSwap::getPriorVotes: not yet determined");
uint32 nCheckpoints = numCheckpoints[account];
if (nCheckpoints == 0) {
return 0;
}
if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) {
return checkpoints[account][nCheckpoints - 1].votes;
}
if (checkpoints[account][0].fromBlock > blockNumber) {
return 0;
}
uint32 lower = 0;
uint32 upper = nCheckpoints - 1;
while (upper > lower) {
Checkpoint memory cp = checkpoints[account][center];
if (cp.fromBlock == blockNumber) {
return cp.votes;
lower = center;
upper = center - 1;
}
}
return checkpoints[account][lower].votes;
}
| 12,220,074 |
// Sources flattened with hardhat v2.8.4 https://hardhat.org
// File contracts/Context.sol
// SPDX-License-Identifier: MIT
pragma solidity 0.8.9;
/**
* @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 contracts/Ownable.sol
pragma solidity 0.8.9;
/**
* @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/ReentrancyGuard.sol
pragma solidity 0.8.9;
/**
* @dev Contract module that helps prevent reentrant calls to a function.
*
* Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier
* available, which can be applied to functions to make sure there are no nested
* (reentrant) calls to them.
*
* Note that because there is a single `nonReentrant` guard, functions marked as
* `nonReentrant` may not call one another. This can be worked around by making
* those functions `private`, and then adding `external` `nonReentrant` entry
* points to them.
*
* TIP: If you would like to learn more about reentrancy and alternative ways
* to protect against it, check out our blog post
* https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul].
*/
abstract contract ReentrancyGuard {
// Booleans are more expensive than uint256 or any type that takes up a full
// word because each write operation emits an extra SLOAD to first read the
// slot's contents, replace the bits taken up by the boolean, and then write
// back. This is the compiler's defense against contract upgrades and
// pointer aliasing, and it cannot be disabled.
// The values being non-zero value makes deployment a bit more expensive,
// but in exchange the refund on every call to nonReentrant will be lower in
// amount. Since refunds are capped to a percentage of the total
// transaction's gas, it is best to keep them low in cases like this one, to
// increase the likelihood of the full refund coming into effect.
uint256 private constant _NOT_ENTERED = 1;
uint256 private constant _ENTERED = 2;
uint256 private _status;
constructor() {
_status = _NOT_ENTERED;
}
/**
* @dev Prevents a contract from calling itself, directly or indirectly.
* Calling a `nonReentrant` function from another `nonReentrant`
* function is not supported. It is possible to prevent this from happening
* by making the `nonReentrant` function external, and make it call a
* `private` function that does the actual work.
*/
modifier nonReentrant() {
// On the first call to nonReentrant, _notEntered will be true
require(_status != _ENTERED, "ReentrancyGuard: reentrant call");
// Any calls to nonReentrant after this point will fail
_status = _ENTERED;
_;
// By storing the original value once again, a refund is triggered (see
// https://eips.ethereum.org/EIPS/eip-2200)
_status = _NOT_ENTERED;
}
}
// File contracts/interfaces/IERC165.sol
pragma solidity 0.8.9;
/**
* @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/interfaces/IERC721.sol
pragma solidity 0.8.9;
/**
* @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 contracts/interfaces/IERC721Receiver.sol
pragma solidity 0.8.9;
/**
* @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 contracts/interfaces/IERC721Metadata.sol
pragma solidity 0.8.9;
/**
* @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 contracts/interfaces/IERC721Enumerable.sol
pragma solidity 0.8.9;
/**
* @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 contracts/Address.sol
pragma solidity 0.8.9;
/**
* @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 contracts/Strings.sol
pragma solidity 0.8.9;
/**
* @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 contracts/ERC165.sol
pragma solidity 0.8.9;
/**
* @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 contracts/ERC721A.sol
pragma solidity 0.8.9;
/**
* @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including
* the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints.
*
* Assumes serials are sequentially minted starting at 0 (e.g. 0, 1, 2, 3..).
*
* Assumes the number of issuable tokens (collection size) is capped and fits in a uint128.
*
* Does not support burning tokens to address(0).
*/
contract ERC721A is
Context,
ERC165,
IERC721,
IERC721Metadata,
IERC721Enumerable
{
using Address for address;
using Strings for uint256;
struct TokenOwnership {
address addr;
uint64 startTimestamp;
}
struct AddressData {
uint128 balance;
uint128 numberMinted;
}
uint256 private currentIndex = 0;
uint256 internal immutable collectionSize;
uint256 internal immutable maxBatchSize;
// Token name
string private _name;
// Token symbol
string private _symbol;
// Mapping from token ID to ownership details
// An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details.
mapping(uint256 => TokenOwnership) private _ownerships;
// Mapping owner address to address data
mapping(address => AddressData) private _addressData;
// Mapping from token ID to approved address
mapping(uint256 => address) private _tokenApprovals;
// Mapping from owner to operator approvals
mapping(address => mapping(address => bool)) private _operatorApprovals;
/**
* @dev
* `maxBatchSize` refers to how much a minter can mint at a time.
* `collectionSize_` refers to how many tokens are in the collection.
*/
constructor(
string memory name_,
string memory symbol_,
uint256 maxBatchSize_,
uint256 collectionSize_
) {
require(
collectionSize_ > 0,
"ERC721A: collection must have a nonzero supply"
);
require(maxBatchSize_ > 0, "ERC721A: max batch size must be nonzero");
_name = name_;
_symbol = symbol_;
maxBatchSize = maxBatchSize_;
collectionSize = collectionSize_;
}
/**
* @dev See {IERC721Enumerable-totalSupply}.
*/
function totalSupply() public view override returns (uint256) {
return currentIndex;
}
/**
* @dev See {IERC721Enumerable-tokenByIndex}.
*/
function tokenByIndex(uint256 index)
public
view
override
returns (uint256)
{
require(index < totalSupply(), "ERC721A: global index out of bounds");
return index;
}
/**
* @dev See {IERC721Enumerable-tokenOfOwnerByIndex}.
* This read function is O(collectionSize). If calling from a separate contract, be sure to test gas first.
* It may also degrade with extremely large collection sizes (e.g >> 10000), test for your use case.
*/
function tokenOfOwnerByIndex(address owner, uint256 index)
public
view
override
returns (uint256)
{
require(index < balanceOf(owner), "ERC721A: owner index out of bounds");
uint256 numMintedSoFar = totalSupply();
uint256 tokenIdsIdx = 0;
address currOwnershipAddr = address(0);
for (uint256 i = 0; i < numMintedSoFar; i++) {
TokenOwnership memory ownership = _ownerships[i];
if (ownership.addr != address(0)) {
currOwnershipAddr = ownership.addr;
}
if (currOwnershipAddr == owner) {
if (tokenIdsIdx == index) {
return i;
}
tokenIdsIdx++;
}
}
revert("ERC721A: unable to get token of owner by index");
}
/**
* @dev See {IERC165-supportsInterface}.
*/
function supportsInterface(bytes4 interfaceId)
public
view
virtual
override(ERC165, IERC165)
returns (bool)
{
return
interfaceId == type(IERC721).interfaceId ||
interfaceId == type(IERC721Metadata).interfaceId ||
interfaceId == type(IERC721Enumerable).interfaceId ||
super.supportsInterface(interfaceId);
}
/**
* @dev See {IERC721-balanceOf}.
*/
function balanceOf(address owner) public view override returns (uint256) {
require(
owner != address(0),
"ERC721A: balance query for the zero address"
);
return uint256(_addressData[owner].balance);
}
function _numberMinted(address owner) internal view returns (uint256) {
require(
owner != address(0),
"ERC721A: number minted query for the zero address"
);
return uint256(_addressData[owner].numberMinted);
}
function ownershipOf(uint256 tokenId)
internal
view
returns (TokenOwnership memory)
{
require(_exists(tokenId), "ERC721A: owner query for nonexistent token");
uint256 lowestTokenToCheck;
if (tokenId >= maxBatchSize) {
lowestTokenToCheck = tokenId - maxBatchSize + 1;
}
for (uint256 curr = tokenId; curr >= lowestTokenToCheck; curr--) {
TokenOwnership memory ownership = _ownerships[curr];
if (ownership.addr != address(0)) {
return ownership;
}
}
revert("ERC721A: unable to determine the owner of token");
}
/**
* @dev See {IERC721-ownerOf}.
*/
function ownerOf(uint256 tokenId) public view override returns (address) {
return ownershipOf(tokenId).addr;
}
/**
* @dev See {IERC721Metadata-name}.
*/
function name() public view virtual override returns (string memory) {
return _name;
}
/**
* @dev See {IERC721Metadata-symbol}.
*/
function symbol() public view virtual override returns (string memory) {
return _symbol;
}
/**
* @dev See {IERC721Metadata-tokenURI}.
*/
function tokenURI(uint256 tokenId)
public
view
virtual
override
returns (string memory)
{
require(
_exists(tokenId),
"ERC721Metadata: URI query for nonexistent token"
);
string memory baseURI = _baseURI();
return
bytes(baseURI).length > 0
? string(abi.encodePacked(baseURI, tokenId.toString()))
: "";
}
/**
* @dev Base URI for computing {tokenURI}. If set, the resulting URI for each
* token will be the concatenation of the `baseURI` and the `tokenId`. Empty
* by default, can be overriden in child contracts.
*/
function _baseURI() internal view virtual returns (string memory) {
return "";
}
/**
* @dev See {IERC721-approve}.
*/
function approve(address to, uint256 tokenId) public override {
address owner = ERC721A.ownerOf(tokenId);
require(to != owner, "ERC721A: approval to current owner");
require(
_msgSender() == owner || isApprovedForAll(owner, _msgSender()),
"ERC721A: approve caller is not owner nor approved for all"
);
_approve(to, tokenId, owner);
}
/**
* @dev See {IERC721-getApproved}.
*/
function getApproved(uint256 tokenId)
public
view
override
returns (address)
{
require(
_exists(tokenId),
"ERC721A: approved query for nonexistent token"
);
return _tokenApprovals[tokenId];
}
/**
* @dev See {IERC721-setApprovalForAll}.
*/
function setApprovalForAll(address operator, bool approved)
public
override
{
require(operator != _msgSender(), "ERC721A: approve to caller");
_operatorApprovals[_msgSender()][operator] = approved;
emit ApprovalForAll(_msgSender(), operator, approved);
}
/**
* @dev See {IERC721-isApprovedForAll}.
*/
function isApprovedForAll(address owner, address operator)
public
view
virtual
override
returns (bool)
{
return _operatorApprovals[owner][operator];
}
/**
* @dev See {IERC721-transferFrom}.
*/
function transferFrom(
address from,
address to,
uint256 tokenId
) public override {
_transfer(from, to, tokenId);
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId
) public override {
safeTransferFrom(from, to, tokenId, "");
}
/**
* @dev See {IERC721-safeTransferFrom}.
*/
function safeTransferFrom(
address from,
address to,
uint256 tokenId,
bytes memory _data
) public override {
_transfer(from, to, tokenId);
require(
_checkOnERC721Received(from, to, tokenId, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
}
/**
* @dev Returns whether `tokenId` exists.
*
* Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}.
*
* Tokens start existing when they are minted (`_mint`),
*/
function _exists(uint256 tokenId) internal view returns (bool) {
return tokenId < currentIndex;
}
function _safeMint(address to, uint256 quantity) internal {
_safeMint(to, quantity, "");
}
/**
* @dev Mints `quantity` tokens and transfers them to `to`.
*
* Requirements:
*
* - there must be `quantity` tokens remaining unminted in the total collection.
* - `to` cannot be the zero address.
* - `quantity` cannot be larger than the max batch size.
*
* Emits a {Transfer} event.
*/
function _safeMint(
address to,
uint256 quantity,
bytes memory _data
) internal {
uint256 startTokenId = currentIndex;
require(to != address(0), "ERC721A: mint to the zero address");
// We know if the first token in the batch doesn't exist, the other ones don't as well, because of serial ordering.
require(!_exists(startTokenId), "ERC721A: token already minted");
require(quantity <= maxBatchSize, "ERC721A: quantity to mint too high");
_beforeTokenTransfers(address(0), to, startTokenId, quantity);
AddressData memory addressData = _addressData[to];
_addressData[to] = AddressData(
addressData.balance + uint128(quantity),
addressData.numberMinted + uint128(quantity)
);
_ownerships[startTokenId] = TokenOwnership(to, uint64(block.timestamp));
uint256 updatedIndex = startTokenId;
for (uint256 i = 0; i < quantity; i++) {
emit Transfer(address(0), to, updatedIndex);
require(
_checkOnERC721Received(address(0), to, updatedIndex, _data),
"ERC721A: transfer to non ERC721Receiver implementer"
);
updatedIndex++;
}
currentIndex = updatedIndex;
_afterTokenTransfers(address(0), to, startTokenId, quantity);
}
/**
* @dev Transfers `tokenId` from `from` to `to`.
*
* Requirements:
*
* - `to` cannot be the zero address.
* - `tokenId` token must be owned by `from`.
*
* Emits a {Transfer} event.
*/
function _transfer(
address from,
address to,
uint256 tokenId
) private {
TokenOwnership memory prevOwnership = ownershipOf(tokenId);
bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr ||
getApproved(tokenId) == _msgSender() ||
isApprovedForAll(prevOwnership.addr, _msgSender()));
require(
isApprovedOrOwner,
"ERC721A: transfer caller is not owner nor approved"
);
require(
prevOwnership.addr == from,
"ERC721A: transfer from incorrect owner"
);
require(to != address(0), "ERC721A: transfer to the zero address");
_beforeTokenTransfers(from, to, tokenId, 1);
// Clear approvals from the previous owner
_approve(address(0), tokenId, prevOwnership.addr);
_addressData[from].balance -= 1;
_addressData[to].balance += 1;
_ownerships[tokenId] = TokenOwnership(to, uint64(block.timestamp));
// If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it.
// Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls.
uint256 nextTokenId = tokenId + 1;
if (_ownerships[nextTokenId].addr == address(0)) {
if (_exists(nextTokenId)) {
_ownerships[nextTokenId] = TokenOwnership(
prevOwnership.addr,
prevOwnership.startTimestamp
);
}
}
emit Transfer(from, to, tokenId);
_afterTokenTransfers(from, to, tokenId, 1);
}
/**
* @dev Approve `to` to operate on `tokenId`
*
* Emits a {Approval} event.
*/
function _approve(
address to,
uint256 tokenId,
address owner
) private {
_tokenApprovals[tokenId] = to;
emit Approval(owner, to, tokenId);
}
uint256 public nextOwnerToExplicitlySet = 0;
/**
* @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf().
*/
function _setOwnersExplicit(uint256 quantity) internal {
uint256 oldNextOwnerToSet = nextOwnerToExplicitlySet;
require(quantity > 0, "quantity must be nonzero");
uint256 endIndex = oldNextOwnerToSet + quantity - 1;
if (endIndex > collectionSize - 1) {
endIndex = collectionSize - 1;
}
// We know if the last one in the group exists, all in the group exist, due to serial ordering.
require(_exists(endIndex), "not enough minted yet for this cleanup");
for (uint256 i = oldNextOwnerToSet; i <= endIndex; i++) {
if (_ownerships[i].addr == address(0)) {
TokenOwnership memory ownership = ownershipOf(i);
_ownerships[i] = TokenOwnership(
ownership.addr,
ownership.startTimestamp
);
}
}
nextOwnerToExplicitlySet = endIndex + 1;
}
/**
* @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address.
* The call is not executed if the target address is not a contract.
*
* @param from address representing the previous owner of the given token ID
* @param to target address that will receive the tokens
* @param tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return bool whether the call correctly returned the expected magic value
*/
function _checkOnERC721Received(
address from,
address to,
uint256 tokenId,
bytes memory _data
) private returns (bool) {
if (to.isContract()) {
try
IERC721Receiver(to).onERC721Received(
_msgSender(),
from,
tokenId,
_data
)
returns (bytes4 retval) {
return retval == IERC721Receiver(to).onERC721Received.selector;
} catch (bytes memory reason) {
if (reason.length == 0) {
revert(
"ERC721A: transfer to non ERC721Receiver implementer"
);
} else {
assembly {
revert(add(32, reason), mload(reason))
}
}
}
} else {
return true;
}
}
/**
* @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be
* transferred to `to`.
* - When `from` is zero, `tokenId` will be minted for `to`.
*/
function _beforeTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
/**
* @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes
* minting.
*
* startTokenId - the first token id to be transferred
* quantity - the amount to be transferred
*
* Calling conditions:
*
* - when `from` and `to` are both non-zero.
* - `from` and `to` are never both zero.
*/
function _afterTokenTransfers(
address from,
address to,
uint256 startTokenId,
uint256 quantity
) internal virtual {}
}
// File contracts/ControlledAccess.sol
pragma solidity 0.8.9;
/* @title ControlledAccess
* @dev The ControlledAccess contract allows function to be restricted to users
* that possess a signed authorization from the owner of the contract. This signed
* message includes the user to give permission to and the contract address to prevent
* reusing the same authorization message on different contract with same owner.
*/
contract ControlledAccess is Ownable {
address public signerAddress;
/*
* @dev Requires msg.sender to have valid access message.
* @param _v ECDSA signature parameter v.
* @param _r ECDSA signature parameters r.
* @param _s ECDSA signature parameters s.
*/
modifier onlyValidAccess(
bytes32 _r,
bytes32 _s,
uint8 _v
) {
require(isValidAccessMessage(msg.sender, _r, _s, _v));
_;
}
function setSignerAddress(address newAddress) external onlyOwner {
signerAddress = newAddress;
}
/*
* @dev Verifies if message was signed by owner to give access to _add for this contract.
* Assumes Geth signature prefix.
* @param _add Address of agent with access
* @param _v ECDSA signature parameter v.
* @param _r ECDSA signature parameters r.
* @param _s ECDSA signature parameters s.
* @return Validity of access message for a given address.
*/
function isValidAccessMessage(
address _add,
bytes32 _r,
bytes32 _s,
uint8 _v
) public view returns (bool) {
bytes32 hash = keccak256(abi.encode(owner(), _add));
bytes32 message = keccak256(
abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)
);
address sig = ecrecover(message, _v, _r, _s);
require(signerAddress == sig, "Signature does not match");
return signerAddress == sig;
}
}
// File contracts/KangarooCountryClub.sol
pragma solidity 0.8.9;
contract KangarooCountryClub is ERC721A, Ownable, ReentrancyGuard, ControlledAccess {
using Strings for uint256;
/** Variables initialized in the constructor */
uint256 public immutable maxPublicMintPerAddress;
uint256 public immutable maxPresaleMintPerAddress;
/** URI Variables */
bytes32 public uriSuffix = ".json";
string private _baseTokenURI = "";
string public hiddenMetadataUri;
/** Contract Functionality Variables */
uint256 public constant mintPrice = 0.04 ether;
uint256 public constant whitelistMintPrice = 0.03 ether;
bool public publicSaleActive = false;
bool public presaleActive = false;
/** Constructor - initialize the contract by setting the name, symbol,
max amount an address can mint, and the total collection size. */
constructor(
uint256 maxBatchSize_,
uint256 maxPresaleBatchSize_,
uint256 collectionSize_
)
ERC721A( "Kangaroo Country Club", "KCC", maxBatchSize_, collectionSize_)
{
maxPublicMintPerAddress = maxBatchSize_;
maxPresaleMintPerAddress = maxPresaleBatchSize_;
setHiddenMetadataURI("ipfs://__CID__/hidden.json");
}
/** Modifier - ensures the function caller is the user */
modifier callerIsUser() {
require(tx.origin == msg.sender, "Caller is another contract");
_;
}
/** Modifier - ensures all minting requirements are met, used in both public and presale
mint functions. Structure allows mintCompliance input values (_quantity, _maxPerAddress
and _startTime) to be function specific */
modifier mintCompliance(uint256 _quantity, uint256 _maxPerAddress) {
require(totalSupply() + _quantity <= collectionSize, "Max supply reached");
require(_quantity >= 0 && _quantity <= _maxPerAddress, "Invalid mint amount");
require(numberMinted(msg.sender) + _quantity <= _maxPerAddress, "Can not mint this many");
_;
}
/** Public Mint Function */
function mint(uint256 quantity)
external
payable
callerIsUser
nonReentrant
mintCompliance(quantity, maxPublicMintPerAddress) /** Mint Complaince for Public Sale */
{
require(publicSaleActive, "Public sale is not live.");
_safeMint(msg.sender, quantity);
refundIfOver(quantity * mintPrice);
}
/** Presale Mint Function */
function presaleMint(uint256 quantity, bytes32 _r, bytes32 _s, uint8 _v)
external
payable
callerIsUser
onlyValidAccess(_r, _s, _v) /** Whitelist */
nonReentrant
mintCompliance(quantity, maxPresaleMintPerAddress) /** Mint Compliance for Presale */
{
require(presaleActive, "Presale is not live.");
_safeMint(msg.sender, quantity);
refundIfOver(quantity * whitelistMintPrice);
}
/** Metadata URI */
function _baseURI() internal view virtual override returns (string memory) {
return _baseTokenURI;
}
/** Total number of NFTs minted from the contract for a given address. Value can only increase and
does not depend on how many NFTs are in your wallet */
function numberMinted(address owner) public view returns (uint256) {
return _numberMinted(owner);
}
/** Get the owner of a specific token from the tokenId */
function getOwnershipData(uint256 tokenId)
external
view
returns (TokenOwnership memory)
{
return ownershipOf(tokenId);
}
/** Refund function which requires the minimum amount for the transaction and returns any extra payment to the sender */
function refundIfOver(uint256 price) private {
require(msg.value >= price, "Need to send more eth");
if (msg.value > price) {
payable(msg.sender).transfer(msg.value - price);
}
}
/** Standard TokenURI ERC721A function modified to return hidden metadata
URI until the contract is revealed. */
function tokenURI(uint256 _tokenId)
public
view
virtual
override
returns (string memory)
{
require(_exists(_tokenId), "Nonexistent token!");
if (keccak256(abi.encodePacked(_baseTokenURI)) == keccak256(abi.encodePacked(""))) {
return hiddenMetadataUri;
}
return
bytes(_baseTokenURI).length > 0
? string(
abi.encodePacked(_baseTokenURI, _tokenId.toString(), uriSuffix)
)
: "";
}
/// OWNER FUNCTIONS ///
/** Standard withdraw function for the owner to pull the contract */
function withdrawMoney() external onlyOwner nonReentrant {
uint256 sendAmount = address(this).balance;
address community = payable(0x416dDEDeE351a1f97Bc5c1ff15bE150Bb14c948c);
address jphilly = payable(0x7177585d7639f01E597E91918114A850ADc93258);
address jsquared = payable(0xdC0556d45e56c030E12EBbdf8Df290c46d11285A);
address zphilly = payable(0x290F139cc66Fca18fC97991c9383A8B830D29f7a);
address artist = payable(0x322856622dB75cdd6e6d1EEda8e96170656AA6CA);
address ninja = payable(0x9a4069cD84bF8654c329d87cE4102855359FBcE5);
address yeti = payable(0x66c17Dcef1B364014573Ae0F869ad1c05fe01c89);
address zj = payable(0xaFece8854848B04cf0796e246724dA7624eC8bC2);
address willy = payable(0x4Bd3BB6B1D03c8844476e525fF291627FbC3c0eA);
address marketing = payable(0x5c3023309dF0a3F7FE59e530B14629184AeB2035);
address jhutt = payable(0x92718D60473d76075e219e5F5B11C628BcF78152);
bool success;
(success, ) = jphilly.call{value: ((sendAmount * 1875) / 10000)}("");
require(success, "Transaction unsuccessful");
(success, ) = jsquared.call{value: ((sendAmount * 1875) / 10000)}("");
require(success, "Transaction unsuccessful");
(success, ) = zphilly.call{value: ((sendAmount * 1875) / 10000)}("");
require(success, "Transaction unsuccessful");
(success, ) = community.call{value: ((sendAmount * 1975) / 10000)}("");
require(success, "Transaction unsuccessful");
(success, ) = ninja.call{value: ((sendAmount * 600) / 10000)}("");
require(success, "Transaction unsuccessful");
(success, ) = artist.call{value: ((sendAmount * 500) / 10000)}("");
require(success, "Transaction unsuccessful");
(success, ) = yeti.call{value: ((sendAmount * 300) / 10000)}("");
require(success, "Transaction unsuccessful");
(success, ) = zj.call{value: ((sendAmount * 300) / 10000)}("");
require(success, "Transaction unsuccessful");
(success, ) = willy.call{value: ((sendAmount * 300) / 10000)}("");
require(success, "Transaction unsuccessful");
(success, ) = jhutt.call{value: ((sendAmount * 300) / 10000)}("");
require(success, "Transaction unsuccessful");
(success, ) = marketing.call{value: ((sendAmount * 100) / 10000)}("");
require(success, "Transaction unsuccessful");
}
/** Mint Function only usable by contract owner. Use reserved for giveaways and promotions. */
function ownerMint(address to, uint256 quantity) public callerIsUser onlyOwner {
require(quantity + totalSupply() <= collectionSize, 'Max supply reached');
_safeMint(to, quantity);
}
/** Function for updating the revealed token metadata URI. When setting this value,
only replace _CID_ in the following: ipfs://_CID_/ */
function setBaseURI(string memory baseURI) public onlyOwner {
_baseTokenURI = baseURI;
}
/** Initialized in constructor - Hidden metadata value pointing to unrevealed token URI. */
function setHiddenMetadataURI(string memory _hiddenMetadataURI) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataURI;
}
function setPresaleActive(bool _active) public onlyOwner {
presaleActive = _active;
}
function setPublicSaleActive(bool _active) public onlyOwner {
publicSaleActive = _active;
}
/** adding onlyOwner and nonReentrant modifiers to ERC721A setOwnersExplicit for enhanced security */
function setOwnersExplicit(uint256 quantity)
external
onlyOwner
nonReentrant
{
_setOwnersExplicit(quantity);
}
}
|
Initialized in constructor - Hidden metadata value pointing to unrevealed token URI. /
|
function setHiddenMetadataURI(string memory _hiddenMetadataURI) public onlyOwner {
hiddenMetadataUri = _hiddenMetadataURI;
}
| 14,516,021 |
./full_match/1/0x4e5Bb5FfB7985B9D79fAb4283D2e6927Ca0EcaB3/sources/ArbitrageBot.sol
|
Withdraw contract's ETH balance
|
function withdrawETHBalance(address payable recipient) external isOwner{
recipient.transfer(address(this).balance);
}
| 8,373,736 |
./partial_match/1/0x7be8c30dfad51f017a5f81484A9b945492dc1871/sources/contracts/PriceFeed.sol
|
address _binanceAggregatorAddress,checkContract(_binanceAggregatorAddress); binanceAggregator = AggregatorV3Interface(_binanceAggregatorAddress); Explicitly set initial system status Get an initial price from Chainlink to serve as first reference for lastGoodPrice
|
function setAddresses(
address _priceAggregatorAddress,
address _tellorCallerAddress,
address _inflationFeedAddress
)
external
onlyOwner
{
checkContract(_priceAggregatorAddress);
checkContract(_tellorCallerAddress);
checkContract(_inflationFeedAddress);
priceAggregator = AggregatorV3Interface(_priceAggregatorAddress);
tellorCaller = ITellorCaller(_tellorCallerAddress);
inflationFeed = IInflationFeed(_inflationFeedAddress);
status = Status.chainlinkWorking;
ChainlinkResponse memory chainlinkResponse = _getCurrentChainlinkResponse();
ChainlinkResponse memory prevChainlinkResponse = _getPrevChainlinkResponse(chainlinkResponse.roundId, chainlinkResponse.decimals);
require(!_chainlinkIsBroken(chainlinkResponse, prevChainlinkResponse) && !_chainlinkIsFrozen(chainlinkResponse),
"PriceFeed: Chainlink must be working and current");
_storeChainlinkPrice(chainlinkResponse);
_renounceOwnership();
}
| 9,155,360 |
./full_match/97/0xB24B6A0BF099c593A3c6d2bB9F50ec95FB16378d/sources/project_/contracts/diamond/libraries/LibLimitBook.sol
|
todo: 下单前的校验 todo: 从用户那里收钱 IERC20(odi.tokenIn).safeTransferFrom(user, address(this), odi.amountIn);
|
function openLimitOrder(IBook.OpenDataInput calldata odi) internal {
LimitBookStorage storage lbs = limitBookStorage();
address user = msg.sender;
bytes32[] storage orderHashes = lbs.userOpenOrderHashes[user];
OpenOrder memory order = OpenOrder(
user, uint32(orderHashes.length), odi.price, odi.pairBase, odi.amountIn,
odi.tokenIn, odi.isLong, odi.broker, odi.stopLoss, odi.qty, odi.takeProfit
);
bytes32 orderHash = keccak256(abi.encode(order, lbs.salt, "order"));
lbs.salt++;
lbs.openOrders[orderHash] = order;
orderHashes.push(orderHash);
emit OpenLimitOrder(user, orderHash, odi);
}
| 3,285,234 |
./full_match/4/0x7Db7deaf0e6ED69e29a59bAB170993d3622999F0/sources/contracts/ANTZ/AtomicAntzNFTCollection.sol
|
Claim up to 20 antz at once/
|
function mintAntz( uint256 amount ) external payable callerIsUser claimStarted {
require( msg.value == mintPrice * amount, "Not enough Ether to claim the antz" );
require( amount <= maxAntzPerTransaction, "You can only claim 20 Antz per transactions" );
require( claimedAntzPerWallet[msg.sender] + amount <= maxAntzPerWallet, "You cannot claim more antz" );
require( availableAntz.length >= amount, "No antz left to be claimed" );
if( amount == 1 ) {
claimAnt();
}
uint256[] memory tokenIds = new uint256[]( amount );
claimedAntzPerWallet[msg.sender] += amount;
totalMintedTokens += amount;
for ( uint256 i; i < amount; i++ ) {
tokenIds[i] = getAntToBeClaimed();
}
_batchMint( msg.sender, tokenIds );
}
| 787,622 |
./partial_match/42/0xFb0b80D5870a3548f0dD12dA6cB0859d3Dc4a914/sources/Jackpot.sol
|
Calculates total stake payout including rewards for a multi-day range stakeSharesParam Param from stake to calculate bonuses for beginDay First day to calculate bonuses for endDay Last day (non-inclusive) of range to calculate bonuses for return Payout in Suns/ Eligible to receive bonus / Eligible to receive bonus
|
function calcPayoutRewards(
uint256 stakeSharesParam,
uint256 beginDay,
uint256 endDay
)
public
view
returns (uint256 payout)
{
uint256 currDay = _currentDay();
require(beginDay <= currDay, "JACKPOT: Wrong argument for beginDay");
require(endDay <= currDay && beginDay <= endDay, "JACKPOT: Wrong argument for endDay");
require(globals.latestStakeId != 0, "JACKPOT: latestStakeId error.");
if (beginDay == endDay)
return 0;
uint256 counter;
uint256 day = beginDay;
while(day < endDay && day < globals.dailyDataCount) {
uint256 dayPayout;
dayPayout = dailyData[day].dayPayoutTotal * stakeSharesParam
/ dailyData[day].dayStakeSharesTotal;
if (counter < 4) {
counter++;
}
else {
dayPayout = (dailyData[day].dayPayoutTotal * stakeSharesParam
/ dailyData[day].dayStakeSharesTotal) * BONUS_DAY_SCALE;
counter = 0;
}
payout += dayPayout;
++day;
}
uint256 dayStakeSharesTotal = dailyData[globals.dailyDataCount - 1].dayStakeSharesTotal;
if (dayStakeSharesTotal == 0)
dayStakeSharesTotal = stakeSharesParam;
while(day < endDay) {
uint256 dayPayout;
dayPayout = dayPayoutTotal * stakeSharesParam / dayStakeSharesTotal;
if (counter < 4) {
counter++;
}
else {
dayPayout = (dayPayoutTotal * stakeSharesParam / dayStakeSharesTotal) * BONUS_DAY_SCALE;
counter = 0;
}
payout += dayPayout;
++day;
}
return payout;
}
| 8,943,973 |
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.0;
/**
* @dev 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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./Ownable.sol";
import "./SafeMath.sol";
/**
* @title TokenTimelock
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
* use this contract need :
* 1.release ERC20 contract;
* 2.configure and release TokenTimelock contract
* 3.transfer ERC20 Tokens which need to be timelocked to TokenTimelock contract
* 4.when time reached, call release() to release tokens to beneficiary
*
* for example:
* (D=Duration R=ReleaseRatio)
* ^
* |
* |
* R4 | ————
* R3 | ————
* R2 | ————
* R1 | ————
* |
* |——————————————————————————>
* D1 D2 D3 D4
*
* start = 2019-1-1 00:00:00
* D1=D2=D3=D4=1year
* R1=10,R2=20,R3=30,R4=40 (please ensure R1+R2+R3+R4=100)
* so, you will get below tokens in total
* Time Tokens Get
* Start~Start+D1 0
* Start+D1~Start+D1+D2 10% total in this Timelock contract
* Start+D1+D2~Start+D1+D2+D3 10%+20% total
* Start+D1+D2+D3~Start+D1+D2+D3+D4 10%+20%+30% total
* Start+D1+D2+D3+D4~infinity 10%+20%+30%+40% total(usually ensures 100 percent)
*/
contract TokenTimelock is Ownable {
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
using SafeMath for uint256;
event TokensReleased(address token, uint256 amount);
event TokenTimelockRevoked(address token);
// beneficiary of tokens after they are released
address private _beneficiary;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
uint256 private _start;
uint256 private _totalDuration;
//Durations and token release ratios expressed in UNIX time
struct DurationsAndRatios{
uint256 _periodDuration;
uint256 _periodReleaseRatio;
}
DurationsAndRatios[4] _durationRatio;//four period of duration and ratios
bool private _revocable;
mapping (address => uint256) private _released;
mapping (address => bool) private _revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary address of the beneficiary to whom vested tokens are transferred
* @param start the time (as Unix time) at which point vesting starts
* @param firstDuration: first period duration
* @param firstRatio: first period release ratio
* @param secondDuration: second period duration
* @param secondRatio: second period release ratio
* @param thirdDuration: third period duration
* @param thirdRatio: third period release ratio
* @param fourthDuration: fourth period duration
* @param fourthRatio: fourth period release ratio
* @param revocable whether the vesting is revocable or not
*/
constructor (address beneficiary, uint256 start, uint256 firstDuration,uint256 firstRatio,uint256 secondDuration, uint256 secondRatio,
uint256 thirdDuration,uint256 thirdRatio,uint256 fourthDuration, uint256 fourthRatio,bool revocable) public {
require(beneficiary != address(0), "TokenTimelock: beneficiary is the zero address");
require(firstRatio.add(secondRatio).add(thirdRatio).add(fourthRatio)==100, "TokenTimelock: ratios added not equal 100.");
_beneficiary = beneficiary;
_revocable = revocable;
_start = start;
_durationRatio[0]._periodDuration = firstDuration;
_durationRatio[1]._periodDuration = secondDuration;
_durationRatio[2]._periodDuration = thirdDuration;
_durationRatio[3]._periodDuration = fourthDuration;
_durationRatio[0]._periodReleaseRatio = firstRatio;
_durationRatio[1]._periodReleaseRatio = secondRatio;
_durationRatio[2]._periodReleaseRatio = thirdRatio;
_durationRatio[3]._periodReleaseRatio = fourthRatio;
_totalDuration = firstDuration.add(secondDuration).add(thirdDuration).add(fourthDuration);
require(_start.add(_totalDuration) > block.timestamp, "TokenTimelock: final time is before current time");
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the end time of every period.
*/
function getDurationsAndRatios() public view returns (uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256) {
return (_durationRatio[0]._periodDuration,_durationRatio[1]._periodDuration,_durationRatio[2]._periodDuration,_durationRatio[3]._periodDuration,
_durationRatio[0]._periodReleaseRatio,_durationRatio[1]._periodReleaseRatio,_durationRatio[2]._periodReleaseRatio,_durationRatio[3]._periodReleaseRatio);
}
/**
* @return the start time of the token vesting.
*/
function start() public view returns (uint256) {
return _start;
}
/**
* @return current time of the contract.
*/
function currentTime() public view returns (uint256) {
return block.timestamp;
}
/**
* @return the total duration of the token vesting.
*/
function totalDuration() public view returns (uint256) {
return _totalDuration;
}
/**
* @return true if the vesting is revocable.
*/
function revocable() public view returns (bool) {
return _revocable;
}
/**
* @return the amount of the token released.
*/
function released(address token) public view returns (uint256) {
return _released[token];
}
/**
* @return true if the token is revoked.
*/
function revoked(address token) public view returns (bool) {
return _revoked[token];
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) public {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0, "TokenTimelock: no tokens are due");
_released[address(token)] = _released[address(token)].add(unreleased);
token.transfer(_beneficiary, unreleased);
emit TokensReleased(address(token), unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(IERC20 token) public onlyOwner {
require(_revocable, "TokenTimelock: cannot revoke");
require(!_revoked[address(token)], "TokenTimelock: token already revoked");
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[address(token)] = true;
token.transfer(owner(), refund);
emit TokenTimelockRevoked(address(token));
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(_released[address(token)]);
}
/**
* @dev Calculates the amount that should be vested totally.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));//token balance in TokenTimelock contract
uint256 totalBalance = currentBalance.add(_released[address(token)]);//total balance in TokenTimelock contract
uint256[4] memory periodEndTimestamp;
periodEndTimestamp[0] = _start.add(_durationRatio[0]._periodDuration);
periodEndTimestamp[1] = periodEndTimestamp[0].add(_durationRatio[1]._periodDuration);
periodEndTimestamp[2] = periodEndTimestamp[1].add(_durationRatio[2]._periodDuration);
periodEndTimestamp[3] = periodEndTimestamp[2].add(_durationRatio[3]._periodDuration);
uint256 releaseRatio;
if (block.timestamp < periodEndTimestamp[0]) {
return 0;
}else if(block.timestamp >= periodEndTimestamp[0] && block.timestamp < periodEndTimestamp[1]){
releaseRatio = _durationRatio[0]._periodReleaseRatio;
}else if(block.timestamp >= periodEndTimestamp[1] && block.timestamp < periodEndTimestamp[2]){
releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio);
}else if(block.timestamp >= periodEndTimestamp[2] && block.timestamp < periodEndTimestamp[3]) {
releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio).add(_durationRatio[2]._periodReleaseRatio);
} else {
releaseRatio = 100;
}
return releaseRatio.mul(totalBalance).div(100);
}
}
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.0;
/**
* @dev 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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./Ownable.sol";
import "./SafeMath.sol";
/**
* @title TokenTimelock
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
* use this contract need :
* 1.release ERC20 contract;
* 2.configure and release TokenTimelock contract
* 3.transfer ERC20 Tokens which need to be timelocked to TokenTimelock contract
* 4.when time reached, call release() to release tokens to beneficiary
*
* for example:
* (D=Duration R=ReleaseRatio)
* ^
* |
* |
* R4 | ————
* R3 | ————
* R2 | ————
* R1 | ————
* |
* |——————————————————————————>
* D1 D2 D3 D4
*
* start = 2019-1-1 00:00:00
* D1=D2=D3=D4=1year
* R1=10,R2=20,R3=30,R4=40 (please ensure R1+R2+R3+R4=100)
* so, you will get below tokens in total
* Time Tokens Get
* Start~Start+D1 0
* Start+D1~Start+D1+D2 10% total in this Timelock contract
* Start+D1+D2~Start+D1+D2+D3 10%+20% total
* Start+D1+D2+D3~Start+D1+D2+D3+D4 10%+20%+30% total
* Start+D1+D2+D3+D4~infinity 10%+20%+30%+40% total(usually ensures 100 percent)
*/
contract TokenTimelock is Ownable {
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
using SafeMath for uint256;
event TokensReleased(address token, uint256 amount);
event TokenTimelockRevoked(address token);
// beneficiary of tokens after they are released
address private _beneficiary;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
uint256 private _start;
uint256 private _totalDuration;
//Durations and token release ratios expressed in UNIX time
struct DurationsAndRatios{
uint256 _periodDuration;
uint256 _periodReleaseRatio;
}
DurationsAndRatios[4] _durationRatio;//four period of duration and ratios
bool private _revocable;
mapping (address => uint256) private _released;
mapping (address => bool) private _revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary address of the beneficiary to whom vested tokens are transferred
* @param start the time (as Unix time) at which point vesting starts
* @param firstDuration: first period duration
* @param firstRatio: first period release ratio
* @param secondDuration: second period duration
* @param secondRatio: second period release ratio
* @param thirdDuration: third period duration
* @param thirdRatio: third period release ratio
* @param fourthDuration: fourth period duration
* @param fourthRatio: fourth period release ratio
* @param revocable whether the vesting is revocable or not
*/
constructor (address beneficiary, uint256 start, uint256 firstDuration,uint256 firstRatio,uint256 secondDuration, uint256 secondRatio,
uint256 thirdDuration,uint256 thirdRatio,uint256 fourthDuration, uint256 fourthRatio,bool revocable) public {
require(beneficiary != address(0), "TokenTimelock: beneficiary is the zero address");
require(firstRatio.add(secondRatio).add(thirdRatio).add(fourthRatio)==100, "TokenTimelock: ratios added not equal 100.");
_beneficiary = beneficiary;
_revocable = revocable;
_start = start;
_durationRatio[0]._periodDuration = firstDuration;
_durationRatio[1]._periodDuration = secondDuration;
_durationRatio[2]._periodDuration = thirdDuration;
_durationRatio[3]._periodDuration = fourthDuration;
_durationRatio[0]._periodReleaseRatio = firstRatio;
_durationRatio[1]._periodReleaseRatio = secondRatio;
_durationRatio[2]._periodReleaseRatio = thirdRatio;
_durationRatio[3]._periodReleaseRatio = fourthRatio;
_totalDuration = firstDuration.add(secondDuration).add(thirdDuration).add(fourthDuration);
require(_start.add(_totalDuration) > block.timestamp, "TokenTimelock: final time is before current time");
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the end time of every period.
*/
function getDurationsAndRatios() public view returns (uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256) {
return (_durationRatio[0]._periodDuration,_durationRatio[1]._periodDuration,_durationRatio[2]._periodDuration,_durationRatio[3]._periodDuration,
_durationRatio[0]._periodReleaseRatio,_durationRatio[1]._periodReleaseRatio,_durationRatio[2]._periodReleaseRatio,_durationRatio[3]._periodReleaseRatio);
}
/**
* @return the start time of the token vesting.
*/
function start() public view returns (uint256) {
return _start;
}
/**
* @return current time of the contract.
*/
function currentTime() public view returns (uint256) {
return block.timestamp;
}
/**
* @return the total duration of the token vesting.
*/
function totalDuration() public view returns (uint256) {
return _totalDuration;
}
/**
* @return true if the vesting is revocable.
*/
function revocable() public view returns (bool) {
return _revocable;
}
/**
* @return the amount of the token released.
*/
function released(address token) public view returns (uint256) {
return _released[token];
}
/**
* @return true if the token is revoked.
*/
function revoked(address token) public view returns (bool) {
return _revoked[token];
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) public {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0, "TokenTimelock: no tokens are due");
_released[address(token)] = _released[address(token)].add(unreleased);
token.transfer(_beneficiary, unreleased);
emit TokensReleased(address(token), unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(IERC20 token) public onlyOwner {
require(_revocable, "TokenTimelock: cannot revoke");
require(!_revoked[address(token)], "TokenTimelock: token already revoked");
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[address(token)] = true;
token.transfer(owner(), refund);
emit TokenTimelockRevoked(address(token));
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(_released[address(token)]);
}
/**
* @dev Calculates the amount that should be vested totally.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));//token balance in TokenTimelock contract
uint256 totalBalance = currentBalance.add(_released[address(token)]);//total balance in TokenTimelock contract
uint256[4] memory periodEndTimestamp;
periodEndTimestamp[0] = _start.add(_durationRatio[0]._periodDuration);
periodEndTimestamp[1] = periodEndTimestamp[0].add(_durationRatio[1]._periodDuration);
periodEndTimestamp[2] = periodEndTimestamp[1].add(_durationRatio[2]._periodDuration);
periodEndTimestamp[3] = periodEndTimestamp[2].add(_durationRatio[3]._periodDuration);
uint256 releaseRatio;
if (block.timestamp < periodEndTimestamp[0]) {
return 0;
}else if(block.timestamp >= periodEndTimestamp[0] && block.timestamp < periodEndTimestamp[1]){
releaseRatio = _durationRatio[0]._periodReleaseRatio;
}else if(block.timestamp >= periodEndTimestamp[1] && block.timestamp < periodEndTimestamp[2]){
releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio);
}else if(block.timestamp >= periodEndTimestamp[2] && block.timestamp < periodEndTimestamp[3]) {
releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio).add(_durationRatio[2]._periodReleaseRatio);
} else {
releaseRatio = 100;
}
return releaseRatio.mul(totalBalance).div(100);
}
}
pragma solidity ^0.5.0;
/*
* @dev Provides information about the current execution context, including the
* sender of the transaction and its data. While these are generally available
* via msg.sender and msg.data, they should not be accessed in such a direct
* manner, since when dealing with GSN meta-transactions the account sending and
* paying for execution may not be the actual sender (as far as an application
* is concerned).
*
* This contract is only required for intermediate, library-like contracts.
*/
contract Context {
// Empty internal constructor, to prevent people from mistakenly deploying
// an instance of this contract, which should be used via inheritance.
constructor () internal { }
// solhint-disable-previous-line no-empty-blocks
function _msgSender() internal view returns (address payable) {
return msg.sender;
}
function _msgData() internal view returns (bytes memory) {
this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691
return msg.data;
}
}
pragma solidity ^0.5.0;
/**
* @dev Interface of the ERC20 standard as defined in the EIP. Does not include
* the optional functions; to access them see {ERC20Detailed}.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
pragma solidity ^0.5.0;
import "./Context.sol";
/**
* @dev Contract module which provides a basic access control mechanism, where
* there is an account (an owner) that can be granted exclusive access to
* specific functions.
*
* This module is used through inheritance. It will make available the modifier
* `onlyOwner`, which can be applied to your functions to restrict their use to
* the owner.
*/
contract Ownable is Context {
address private _owner;
event OwnershipTransferred(address indexed previousOwner, address indexed newOwner);
/**
* @dev Initializes the contract setting the deployer as the initial owner.
*/
constructor () internal {
address msgSender = _msgSender();
_owner = msgSender;
emit OwnershipTransferred(address(0), msgSender);
}
/**
* @dev Returns the address of the current owner.
*/
function owner() public view returns (address) {
return _owner;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(isOwner(), "Ownable: caller is not the owner");
_;
}
/**
* @dev Returns true if the caller is the current owner.
*/
function isOwner() public view returns (bool) {
return _msgSender() == _owner;
}
/**
* @dev Leaves the contract without owner. It will not be possible to call
* `onlyOwner` functions anymore. Can only be called by the current owner.
*
* NOTE: Renouncing ownership will leave the contract without an owner,
* thereby removing any functionality that is only available to the owner.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipTransferred(_owner, address(0));
_owner = address(0);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
* Can only be called by the current owner.
*/
function transferOwnership(address newOwner) public onlyOwner {
_transferOwnership(newOwner);
}
/**
* @dev Transfers ownership of the contract to a new account (`newOwner`).
*/
function _transferOwnership(address newOwner) internal {
require(newOwner != address(0), "Ownable: new owner is the zero address");
emit OwnershipTransferred(_owner, newOwner);
_owner = newOwner;
}
}
pragma solidity ^0.5.0;
/**
* @dev 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.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
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.
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*
* NOTE: This is a feature of the next version of OpenZeppelin Contracts.
* @dev Get it via `npm install @openzeppelin/contracts@next`.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
pragma solidity ^0.5.0;
import "./IERC20.sol";
import "./Ownable.sol";
import "./SafeMath.sol";
/**
* @title TokenTimelock
* @dev A token holder contract that can release its token balance gradually like a
* typical vesting scheme, with a cliff and vesting period. Optionally revocable by the
* owner.
* use this contract need :
* 1.release ERC20 contract;
* 2.configure and release TokenTimelock contract
* 3.transfer ERC20 Tokens which need to be timelocked to TokenTimelock contract
* 4.when time reached, call release() to release tokens to beneficiary
*
* for example:
* (D=Duration R=ReleaseRatio)
* ^
* |
* |
* R4 | ————
* R3 | ————
* R2 | ————
* R1 | ————
* |
* |——————————————————————————>
* D1 D2 D3 D4
*
* start = 2019-1-1 00:00:00
* D1=D2=D3=D4=1year
* R1=10,R2=20,R3=30,R4=40 (please ensure R1+R2+R3+R4=100)
* so, you will get below tokens in total
* Time Tokens Get
* Start~Start+D1 0
* Start+D1~Start+D1+D2 10% total in this Timelock contract
* Start+D1+D2~Start+D1+D2+D3 10%+20% total
* Start+D1+D2+D3~Start+D1+D2+D3+D4 10%+20%+30% total
* Start+D1+D2+D3+D4~infinity 10%+20%+30%+40% total(usually ensures 100 percent)
*/
contract TokenTimelock is Ownable {
// The vesting schedule is time-based (i.e. using block timestamps as opposed to e.g. block numbers), and is
// therefore sensitive to timestamp manipulation (which is something miners can do, to a certain degree). Therefore,
// it is recommended to avoid using short time durations (less than a minute). Typical vesting schemes, with a
// cliff period of a year and a duration of four years, are safe to use.
// solhint-disable not-rely-on-time
using SafeMath for uint256;
event TokensReleased(address token, uint256 amount);
event TokenTimelockRevoked(address token);
// beneficiary of tokens after they are released
address private _beneficiary;
// Durations and timestamps are expressed in UNIX time, the same units as block.timestamp.
uint256 private _start;
uint256 private _totalDuration;
//Durations and token release ratios expressed in UNIX time
struct DurationsAndRatios{
uint256 _periodDuration;
uint256 _periodReleaseRatio;
}
DurationsAndRatios[4] _durationRatio;//four period of duration and ratios
bool private _revocable;
mapping (address => uint256) private _released;
mapping (address => bool) private _revoked;
/**
* @dev Creates a vesting contract that vests its balance of any ERC20 token to the
* beneficiary, gradually in a linear fashion until start + duration. By then all
* of the balance will have vested.
* @param beneficiary address of the beneficiary to whom vested tokens are transferred
* @param start the time (as Unix time) at which point vesting starts
* @param firstDuration: first period duration
* @param firstRatio: first period release ratio
* @param secondDuration: second period duration
* @param secondRatio: second period release ratio
* @param thirdDuration: third period duration
* @param thirdRatio: third period release ratio
* @param fourthDuration: fourth period duration
* @param fourthRatio: fourth period release ratio
* @param revocable whether the vesting is revocable or not
*/
constructor (address beneficiary, uint256 start, uint256 firstDuration,uint256 firstRatio,uint256 secondDuration, uint256 secondRatio,
uint256 thirdDuration,uint256 thirdRatio,uint256 fourthDuration, uint256 fourthRatio,bool revocable) public {
require(beneficiary != address(0), "TokenTimelock: beneficiary is the zero address");
require(firstRatio.add(secondRatio).add(thirdRatio).add(fourthRatio)==100, "TokenTimelock: ratios added not equal 100.");
_beneficiary = beneficiary;
_revocable = revocable;
_start = start;
_durationRatio[0]._periodDuration = firstDuration;
_durationRatio[1]._periodDuration = secondDuration;
_durationRatio[2]._periodDuration = thirdDuration;
_durationRatio[3]._periodDuration = fourthDuration;
_durationRatio[0]._periodReleaseRatio = firstRatio;
_durationRatio[1]._periodReleaseRatio = secondRatio;
_durationRatio[2]._periodReleaseRatio = thirdRatio;
_durationRatio[3]._periodReleaseRatio = fourthRatio;
_totalDuration = firstDuration.add(secondDuration).add(thirdDuration).add(fourthDuration);
require(_start.add(_totalDuration) > block.timestamp, "TokenTimelock: final time is before current time");
}
/**
* @return the beneficiary of the tokens.
*/
function beneficiary() public view returns (address) {
return _beneficiary;
}
/**
* @return the end time of every period.
*/
function getDurationsAndRatios() public view returns (uint256,uint256,uint256,uint256,uint256,uint256,uint256,uint256) {
return (_durationRatio[0]._periodDuration,_durationRatio[1]._periodDuration,_durationRatio[2]._periodDuration,_durationRatio[3]._periodDuration,
_durationRatio[0]._periodReleaseRatio,_durationRatio[1]._periodReleaseRatio,_durationRatio[2]._periodReleaseRatio,_durationRatio[3]._periodReleaseRatio);
}
/**
* @return the start time of the token vesting.
*/
function start() public view returns (uint256) {
return _start;
}
/**
* @return current time of the contract.
*/
function currentTime() public view returns (uint256) {
return block.timestamp;
}
/**
* @return the total duration of the token vesting.
*/
function totalDuration() public view returns (uint256) {
return _totalDuration;
}
/**
* @return true if the vesting is revocable.
*/
function revocable() public view returns (bool) {
return _revocable;
}
/**
* @return the amount of the token released.
*/
function released(address token) public view returns (uint256) {
return _released[token];
}
/**
* @return true if the token is revoked.
*/
function revoked(address token) public view returns (bool) {
return _revoked[token];
}
/**
* @notice Transfers vested tokens to beneficiary.
* @param token ERC20 token which is being vested
*/
function release(IERC20 token) public {
uint256 unreleased = _releasableAmount(token);
require(unreleased > 0, "TokenTimelock: no tokens are due");
_released[address(token)] = _released[address(token)].add(unreleased);
token.transfer(_beneficiary, unreleased);
emit TokensReleased(address(token), unreleased);
}
/**
* @notice Allows the owner to revoke the vesting. Tokens already vested
* remain in the contract, the rest are returned to the owner.
* @param token ERC20 token which is being vested
*/
function revoke(IERC20 token) public onlyOwner {
require(_revocable, "TokenTimelock: cannot revoke");
require(!_revoked[address(token)], "TokenTimelock: token already revoked");
uint256 balance = token.balanceOf(address(this));
uint256 unreleased = _releasableAmount(token);
uint256 refund = balance.sub(unreleased);
_revoked[address(token)] = true;
token.transfer(owner(), refund);
emit TokenTimelockRevoked(address(token));
}
/**
* @dev Calculates the amount that has already vested but hasn't been released yet.
* @param token ERC20 token which is being vested
*/
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(_released[address(token)]);
}
/**
* @dev Calculates the amount that should be vested totally.
* @param token ERC20 token which is being vested
*/
function _vestedAmount(IERC20 token) private view returns (uint256) {
uint256 currentBalance = token.balanceOf(address(this));//token balance in TokenTimelock contract
uint256 totalBalance = currentBalance.add(_released[address(token)]);//total balance in TokenTimelock contract
uint256[4] memory periodEndTimestamp;
periodEndTimestamp[0] = _start.add(_durationRatio[0]._periodDuration);
periodEndTimestamp[1] = periodEndTimestamp[0].add(_durationRatio[1]._periodDuration);
periodEndTimestamp[2] = periodEndTimestamp[1].add(_durationRatio[2]._periodDuration);
periodEndTimestamp[3] = periodEndTimestamp[2].add(_durationRatio[3]._periodDuration);
uint256 releaseRatio;
if (block.timestamp < periodEndTimestamp[0]) {
return 0;
}else if(block.timestamp >= periodEndTimestamp[0] && block.timestamp < periodEndTimestamp[1]){
releaseRatio = _durationRatio[0]._periodReleaseRatio;
}else if(block.timestamp >= periodEndTimestamp[1] && block.timestamp < periodEndTimestamp[2]){
releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio);
}else if(block.timestamp >= periodEndTimestamp[2] && block.timestamp < periodEndTimestamp[3]) {
releaseRatio = _durationRatio[0]._periodReleaseRatio.add(_durationRatio[1]._periodReleaseRatio).add(_durationRatio[2]._periodReleaseRatio);
} else {
releaseRatio = 100;
}
return releaseRatio.mul(totalBalance).div(100);
}
}
|
Calculates the amount that has already vested but hasn't been released yet. token ERC20 token which is being vested/
|
function _releasableAmount(IERC20 token) private view returns (uint256) {
return _vestedAmount(token).sub(_released[address(token)]);
}
| 7,230,043 |
./full_match/1/0xa3540629c5398b88d210FAD81212Bdba11BC5Eb6/sources/lib/solady/src/utils/SafeCastLib.sol
|
´:°•.°+.•´.:˚.°.˚•´.°:°•.°•.•´.:˚.°.˚•´.°:°•.°+.•´.:/ CUSTOM ERRORS /.•°:°.´+˚.°.˚:.´•.+°.•°:´.´•.•°.•°:°.´:•˚°.°.˚:.´+°.•/´:°•.°+.•´.:˚.°.˚•´.°:°•.°•.•´.:˚.°.˚•´.°:°•.°+.•´.:/ UNSIGNED INTEGER SAFE CASTING OPERATIONS /.•°:°.´+˚.°.˚:.´•.+°.•°:´.´•.•°.•°:°.´:•˚°.°.˚:.´+°.•/
|
function toUint8(uint256 x) internal pure returns (uint8) {
if (x >= 1 << 8) _revertOverflow();
return uint8(x);
}
| 8,447,788 |
./full_match/4/0x9b354FF572d8BCFc104baaaab967baA3357e11E4/sources/contracts/receiving_ether.sol
|
but this way is not secure because anyone can access the balance
|
function transferEther(address payable recipient, uint amount) public returns(bool){
if(amount <= getBalance()){
recipient.transfer(amount);
return true;
return false;
}
}
| 12,422,117 |
./partial_match/100/0x52E25845eE3A1A19AB474ca4c56e0EB1E0330467/sources/PriceBettingT1S2.sol
|
function calcAmounts(uint256 amount) public view returns (uint256 gain, uint256 gainAndPrincipal, uint256 govGain) { gain = ABDKMathQuadFunc.mulDiv(amount, profitRatio, 100);0.88 gainAndPrincipal = amount.add(gain);1.88 govGain = amount.sub(gain);0.12 }console.log("[sc] settle(): betIdx: %s, priceNow: %s", betIdx, price);console.log("[sc] priceAtBet: %s, bettingOutcome: %s",bet.priceAtBet, bet.bettingOutcome);(uint256 gain, uint256 gainAndPrincipal, uint256 govGain) = calcAmounts(bet.amount);console.log("bet.amount", bet.amount, gain, gainAndPrincipal);console.log("[sc] ----== Win1: price down");console.log("[sc] ----== Lose1: price down");console.log("[sc] ----== Win2: price up");console.log("[sc] ----== Lose2: price up");
|
function settle(
uint256 period,
uint256 betIdx,
uint256 price
) private {
Bet memory bet = getBet(period, betIdx);
totalUnsettledBetAmt = totalUnsettledBetAmt.sub(bet.amount);
if (price < bet.priceAtBet) {
govBalance = govBalance.add(govGain);
if (bet.bettingOutcome == 0) {
handleWinning(period, betIdx, gain, gainAndPrincipal);
handleLosing(period, betIdx, gain);
}
govBalance = govBalance.add(govGain);
if (bet.bettingOutcome == 1) {
handleWinning(period, betIdx, gain, gainAndPrincipal);
handleLosing(period, betIdx, gain);
}
}
}
| 16,650,877 |
./partial_match/1/0x1473F3e4d236CBBe3412b9f65B4c210756BE2C0E/sources/src/FrxEthEthDualOracle.sol
|
The ```getPricesNormalized``` function returns the normalized prices in human readable form decimals of underlying tokens match so we can just return _getPrices() return isBadDataNormal If the oracle is stale return priceLowNormal The normalized low price return priceHighNormal The normalized high price
|
function getPricesNormalized()
external
view
override
returns (bool isBadDataNormal, uint256 priceLowNormal, uint256 priceHighNormal)
{
(isBadDataNormal, priceLowNormal, priceHighNormal) = _getPrices();
}
| 4,389,219 |
// Ethertote - TeamEth time-locked smart contract
//
// The following contract offers peace of mind to investors as the
// Eth that will go to the members of the Ethertote team
// will be time-locked whereby a maximum of 25% of the Eth can be withdrawn
// from the smart contract every 3 months, starting from December 1st 2018
//
// Withdraw functions can only be called when the current timestamp is
// greater than the time specified in each functions
// ----------------------------------------------------------------------------
pragma solidity 0.4.24;
///////////////////////////////////////////////////////////////////////////////
// SafeMath Library
///////////////////////////////////////////////////////////////////////////////
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;
}
}
///////////////////////////////////////////////////////////////////////////////
// Main contract
//////////////////////////////////////////////////////////////////////////////
contract TeamEth {
using SafeMath for uint256;
address public thisContractAddress;
address public admin;
// the first team withdrawal can be made after:
// GMT: Saturday, 1 December 2018 00:00:00
// expressed as Unix epoch time
// https://www.epochconverter.com/
uint256 public unlockDate1 = 1543622400;
// the second team withdrawal can be made after:
// GMT: Friday, 1 March 2019 00:00:00
// expressed as Unix epoch time
// https://www.epochconverter.com/
uint256 public unlockDate2 = 1551398400;
// the third team withdrawal can be made after:
// GMT: Saturday, 1 June 2019 00:00:00
// expressed as Unix epoch time
// https://www.epochconverter.com/
uint256 public unlockDate3 = 1559347200;
// the final team withdrawal can be made after:
// GMT: Sunday, 1 September 2019 00:00:00
// expressed as Unix epoch time
// https://www.epochconverter.com/
uint256 public unlockDate4 = 1567296000;
// time of the contract creation
uint256 public createdAt;
// amount of eth that will be claimed
uint public ethToBeClaimed;
// ensure the function is only called once
bool public claimAmountSet;
// percentage that the team can withdraw Eth
// it can naturally be inferred that quarter4 will also be 25%
uint public percentageQuarter1 = 25;
uint public percentageQuarter2 = 25;
uint public percentageQuarter3 = 25;
// 100%
uint public hundredPercent = 100;
// calculating the number used as the divider
uint public quarter1 = hundredPercent.div(percentageQuarter1);
uint public quarter2 = hundredPercent.div(percentageQuarter2);
uint public quarter3 = hundredPercent.div(percentageQuarter3);
bool public withdraw_1Completed;
bool public withdraw_2Completed;
bool public withdraw_3Completed;
event Received(address from, uint256 amount);
event Withdrew(address to, uint256 amount);
modifier onlyAdmin {
require(msg.sender == admin);
_;
}
constructor () public {
admin = msg.sender;
thisContractAddress = address(this);
createdAt = now;
}
// fallback to store all the ether sent to this address
function() payable public {
}
function thisContractBalance() public view returns(uint) {
return address(this).balance;
}
function setEthToBeClaimed() onlyAdmin public {
require(claimAmountSet == false);
ethToBeClaimed = address(this).balance;
claimAmountSet = true;
}
// team withdrawal after specified time
function withdraw_1() onlyAdmin public {
require(ethToBeClaimed > 0);
require(withdraw_1Completed == false);
// ensure current time is later than time set
require(now >= unlockDate1);
// now allow a percentage of the balance to be claimed
admin.transfer(ethToBeClaimed.div(quarter1));
emit Withdrew(admin, ethToBeClaimed.div(quarter1)); // 25%
withdraw_1Completed = true;
}
// team withdrawal after specified time
function withdraw_2() onlyAdmin public {
require(ethToBeClaimed > 0);
require(withdraw_2Completed == false);
// ensure current time is later than time set
require(now >= unlockDate2);
// now allow a percentage of the balance to be claimed
admin.transfer(ethToBeClaimed.div(quarter2));
emit Withdrew(admin, ethToBeClaimed.div(quarter2)); // 25%
withdraw_2Completed = true;
}
// team withdrawal after specified time
function withdraw_3() onlyAdmin public {
require(ethToBeClaimed > 0);
require(withdraw_3Completed == false);
// ensure current time is later than time set
require(now >= unlockDate3);
// now allow a percentage of the balance to be claimed
admin.transfer(ethToBeClaimed.div(quarter3));
emit Withdrew(admin, ethToBeClaimed.div(quarter3)); // 25%
withdraw_3Completed = true;
}
// team withdrawal after specified time
function withdraw_4() onlyAdmin public {
// ensure current time is later than time set
require(now >= unlockDate4);
// now allow all remaining balance to be claimed
admin.transfer(address(this).balance);
emit Withdrew(admin, address(this).balance); // all remaining balance
}
}
|
team withdrawal after specified time ensure current time is later than time set now allow a percentage of the balance to be claimed
|
function withdraw_2() onlyAdmin public {
require(ethToBeClaimed > 0);
require(withdraw_2Completed == false);
require(now >= unlockDate2);
admin.transfer(ethToBeClaimed.div(quarter2));
withdraw_2Completed = true;
}
| 2,346,195 |
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
pragma abicoder v2;
import {
ISuperfluid,
ISuperToken,
ISuperApp,
ISuperAgreement,
SuperAppDefinitions,
BatchOperation
} from "./ISuperfluid.sol";
// When you're ready to leave Remix, change imports to follow this pattern:
// "@superfluid-finance/ethereum-contracts/contracts/interfaces/superfluid/ISuperfluid.sol";
import {
IConstantFlowAgreementV1
} from "./IConstantFlowAgreementV1.sol";
import {
SuperAppBase
} from "./SuperAppBase.sol";
import { Simple777Recipient } from "./Simple777Recipient.sol";
import { SafeMath } from "./SafeMath.sol";
struct traderDetails {
address provider;
address validator;
int96 lastBuyPrice; // the price of the A token to the B token
}
enum Action {
CREATE,
UPDATE,
DELETE
}
contract SuperExchange is Simple777Recipient, SuperAppBase {
using SafeMath for int96;
ISuperfluid private _host; // host
IConstantFlowAgreementV1 private _cfa; // the stored constant flow agreement class address
ISuperToken private _acceptedTokenA; // accepted token A
ISuperToken private _acceptedTokenB; // accepted token B
int96 constant fullStreamPercentage = 10000;
int96 constant providerzFeePercentage = 30;
int96 constant insuranceFeePercentage = 40;
int96 constant protocolsFeePercentage = 1;
mapping (address => traderDetails) public traders;
mapping (uint32 => address) public providerz;
mapping (address => address[]) public providerUsers;
uint32 public providersNumber;
constructor(
ISuperfluid host,
IConstantFlowAgreementV1 cfa,
ISuperToken acceptedTokenA,
ISuperToken acceptedTokenB
)
Simple777Recipient(address(acceptedTokenA), address(acceptedTokenB))
{
assert(address(host) != address(0));
assert(address(cfa) != address(0));
assert(address(acceptedTokenA) != address(0));
assert(address(acceptedTokenB) != address(0));
_host = host;
_cfa = cfa;
_acceptedTokenA = acceptedTokenA;
_acceptedTokenB = acceptedTokenB;
uint256 configWord =
SuperAppDefinitions.APP_LEVEL_FINAL;
_host.registerApp(configWord);
}
/*******************************************************************
*********************GENERAL UTILITY FUNCTIONS**********************
********************************************************************/
// modulo function that I will use when deal with price
function abs(int96 x) private pure returns (int96) {
return x >= 0 ? x : -x;
}
// function to check if a token belongs to the pool (used mainly by the afterAgreement callbacks to check if a user uses a token that belongs to the pool)
function _isAllowedToken(ISuperToken superToken) private view returns (bool) {
return address(superToken) == address(_acceptedTokenA) || address(superToken) == address(_acceptedTokenB);
}
// function to check if a user uses exactly constant flow agreement and not any else (used in the afterAgreement callbacks)
function _isCFAv1(address agreementClass) private view returns (bool) {
return ISuperAgreement(agreementClass).agreementType()
== keccak256("org.superfluid-finance.agreements.ConstantFlowAgreement.v1");
}
// function to check if a user is in the providerz list (returns true if the user is a provider)
function isInProvidersList(address user) public view returns (bool){
for (uint32 i = 0; i < providersNumber; i++){
if (providerz[i] == user){
return true;
}
}
return false;
}
// modifier to check if callbacks are called by the host and not anyone else
modifier onlyHost() {
require(msg.sender == address(_host), "SatisfyFlows: support only one host");
_;
}
// modifier to check if a token belongs to the pool and an agreement is a constant flow agreement
modifier onlyExpected(ISuperToken superToken, address agreementClass) {
require(_isAllowedToken(superToken), "SatisfyFlows: not accepted token");
require(_isCFAv1(agreementClass), "SatisfyFlows: only CFAv1 supported");
_;
}
/*******************************************************************
***********************SUPERX UTILITY FUNCTIONS*********************
********************************************************************/
// for the token passed as a parameter - get another token in the pool
function _getAnotherToken(ISuperToken _superToken1) private view returns (ISuperToken _superToken2){
if (_superToken1 == _acceptedTokenA){
_superToken2 = _acceptedTokenB;
} else {
_superToken2 = _acceptedTokenA;
}
}
// returns a token stream going back from the contract to a provider
function _getTokenStreamToProvider(address provider, ISuperToken _superToken) private view returns (int96 stream){
(,stream,,) = _cfa.getFlow(_superToken, address(this), provider);
}
function _getTokenStreamFromProvider(address provider, ISuperToken _superToken) private view returns (int96 stream){
(,stream,,) = _cfa.getFlow(_superToken, provider, address(this));
}
// returns a new bought token stream based on the old streams, sold token stream and the constant product formula x*y = k
// or soldTokenStream*BoughtTokenStream = k
// or oldSoldTokensStream*oldBoughtTokenStream = newSoldTokenStream*newBoughtTokenStream
// (y') = (x*y)/(x')
function _getyNew(int96 x, int96 y, int96 xNew) private pure returns (int96 yNew){
yNew = (x*y)/xNew;
}
// returns the price of a provider
function _getProviderPrice(address provider, ISuperToken soldToken) private view returns (int96 providerPrice) {
int96 soldStream = _getTokenStreamToProvider(provider, soldToken);
int96 boughtStream = _getTokenStreamToProvider(provider, _getAnotherToken(soldToken));
providerPrice = boughtStream*10^18/soldStream;
}
// get best price provider
function _getBestProvider(ISuperToken soldToken) private view returns (address bestProvider) {
int96 maxPrice;
int96 providerPrice;
for (uint32 i = 0; i < providersNumber; i++){
if (providerz[i] == address(0x0)){
continue;
}
providerPrice = _getProviderPrice(providerz[i], soldToken);
if (maxPrice < providerPrice){
maxPrice = providerPrice;
bestProvider = providerz[i];
}
}
}
function _getTokenStreamFromUser(ISuperToken superToken, address user) private view returns (int96 stream){
(,stream,,) = _cfa.getFlow(superToken, user, address(this));
}
function _getTokenStreamToUser(ISuperToken superToken, address user) private view returns (int96 stream){
(,stream,,) = _cfa.getFlow(superToken, address(this), user);
}
/*******************************************************************
***************************CRUD FUNCTIONS***************************
********************************************************************/
// add a new user to the mappings
function _addUser(address userToAdd, address providerOfUser, int96 price) private {
providerUsers[providerOfUser].push(userToAdd);
traders[userToAdd] = traderDetails({provider: providerOfUser, validator: userToAdd, lastBuyPrice: price});
}
// delete a user from the storage
function _deleteUser(address userToDelete) private returns (bool){
address[] storage users = providerUsers[traders[userToDelete].provider];
for (uint i = 0; i < users.length; i++){
if (users[i] == userToDelete){
delete users[i];
return true;
}
}
return false;
}
// add a new provider to the mappings
function _addProvider (address providerToAdd) private {
providerz[providersNumber++] = providerToAdd;
}
// delete a provider and therefore their users from the system
function _deleteProvider(address providerToDelete) private returns (bool){
uint32 providersCount = providersNumber;
for (uint32 i = 0; i < providersCount; i++){
if (providerz[i] == providerToDelete){
providersNumber--;
providerz[i] = providerz[providersNumber];
delete providerz[providersNumber];
_deleteProviderUsers(providerToDelete);
return true;
}
}
return false;
}
function _deleteProviderUsers(address provider) private {
address[] storage users = providerUsers[provider];
for (uint j = 0; j < users.length; j++){
delete traders[users[j]];
}
delete providerUsers[provider];
}
/// @dev doesn't remove users from the mappings, just their streams
function _removeProviderUsersStreams(bytes memory _ctx, address provider, ISuperToken superToken) private returns (bytes memory newCtx){
address[] storage users = providerUsers[provider];
newCtx = _ctx;
for (uint i = 0; i < users.length; i++){
newCtx = _crudFlow(newCtx, users[i], superToken, 0, Action.DELETE);
}
}
function _createBackStreamsToUsers(bytes memory _ctx, address provider, ISuperToken superToken) private returns (bytes memory newCtx){
newCtx = _ctx;
address[] storage users = providerUsers[provider];
int96 userInflow;
for (uint i = 0; i < users.length; i++){
userInflow = _getTokenStreamToUser(superToken, users[i]);
if (userInflow > 0){
newCtx = _crudFlow(newCtx, users[i], superToken, userInflow, Action.UPDATE);
} else {
newCtx = _crudFlow(newCtx, users[i], superToken, userInflow, Action.CREATE);
}
}
}
function _unsubscribeProviderUsers(bytes memory _ctx, address provider, ISuperToken superToken) private returns (bytes memory newCtx){
newCtx = _removeProviderUsersStreams(_ctx, provider, superToken);
newCtx = _createBackStreamsToUsers(newCtx, provider, _getAnotherToken(superToken));
}
// function that allows for easily creating/updating/deleting flows
function _crudFlow(bytes memory _ctx, address receiver, ISuperToken token, int96 flowRate, Action action) private returns (bytes memory newCtx){
newCtx = _ctx;
if (action == Action.CREATE){
(newCtx, ) = _host.callAgreementWithContext(
_cfa,
abi.encodeWithSelector(
_cfa.createFlow.selector,
token,
receiver,
flowRate,
new bytes(0)
),
"0x",
newCtx
);
} else if (action == Action.UPDATE){
(newCtx, ) = _host.callAgreementWithContext(
_cfa,
abi.encodeWithSelector(
_cfa.updateFlow.selector,
token,
receiver,
flowRate,
new bytes(0)
),
"0x",
newCtx
);
} else {
// @dev if inFlowRate is zero, delete outflow.
(newCtx, ) = _host.callAgreementWithContext(
_cfa,
abi.encodeWithSelector(
_cfa.deleteFlow.selector,
token,
address(this),
receiver,
new bytes(0) // placeholder
),
"0x",
newCtx
);
}
}
// update streams in accordance to the new streams' values
function _updateStreamsToLP(bytes memory _ctx, ISuperToken soldToken, address provider, int96 soldStream, int96 boughtStream) private returns (bytes memory newCtx) {
newCtx = _crudFlow(_ctx, provider, soldToken, soldStream, Action.UPDATE);
newCtx = _crudFlow(newCtx, provider, _getAnotherToken(soldToken), boughtStream, Action.UPDATE);
}
// function that creates, updates and deletes stream of the user and updates the Liquidity Pool in accordance to that
function _crudTradeStream(bytes memory _ctx, address streamer, ISuperToken soldToken, int96 prevInflow, Action action) private returns (bytes memory newCtx){
newCtx = _ctx;
address bestProvider;
{
int96 insuranceFee;
int96 userBoughtTokenStream;
ISuperToken boughtToken = _getAnotherToken(soldToken);
{
int96 providerFee;
int96 xNew; int96 yNew;
{
(,int96 fullStream,,) = _cfa.getFlow(soldToken, streamer, address(this));
// check if no providerz and if so, just stream funds back
if (providersNumber == 0){
return _crudFlow(newCtx, streamer, soldToken, fullStream, action);
}
// look for the best provider if create, update
if (action == Action.CREATE || action == Action.UPDATE){
bestProvider = _getBestProvider(soldToken);
}
// strip full stream from all the fees
{
int96 diffStream = fullStream - prevInflow;
providerFee = diffStream*providerzFeePercentage/fullStreamPercentage;
insuranceFee = diffStream*insuranceFeePercentage/fullStreamPercentage;
fullStream -= (providerFee + diffStream*protocolsFeePercentage/fullStreamPercentage + insuranceFee);
}
{
// calculate new backstreams for the user's provider
int96 x = _getTokenStreamToProvider(bestProvider, soldToken);
int96 y = _getTokenStreamToProvider(bestProvider, boughtToken);
xNew = x + fullStream;
yNew = _getyNew(x, y, xNew); // this is the new bought token amount
// calculate new bought token stream for the user
userBoughtTokenStream = y - yNew;
}
}
// TODO check if the userBoughtTokenStream can be paid from the provider and if not - stream tokens back
// update the streams to the provider
newCtx = _updateStreamsToLP(newCtx, soldToken, bestProvider, xNew + providerFee, yNew);
}
// create/update/delete new stream to the user
newCtx = _crudFlow(newCtx, streamer, boughtToken, userBoughtTokenStream + insuranceFee, action);
}
// update mappings
if (action == Action.CREATE){
int96 price = _getProviderPrice(bestProvider, _acceptedTokenA);
_addUser(streamer, bestProvider, price);
} else if (action == Action.DELETE){
_deleteUser(streamer);
}
}
// function that creates, updates or deletes new liquidity and updates the Liquidity Pool in accordance to that
function _crudLiquidityProvider(bytes memory _ctx, address provider, ISuperToken superToken, int96 prevInflow, Action action) private returns (bytes memory newCtx){
newCtx = _ctx;
// if create then
// create streams of this token and another token back
int96 tokenStreamFromProvider = _getTokenStreamFromProvider(provider, superToken);
// add provider to the system
if (action == Action.CREATE){
_addProvider(provider);
}
// if update then
// check if the new stream is enough to pay users
int96 tokenStreamToProvider;
if (action == Action.UPDATE){
tokenStreamToProvider = _getTokenStreamToProvider(provider, superToken);
}
// if not or delete - remove subscribed users
if (action == Action.DELETE || tokenStreamFromProvider < prevInflow - tokenStreamToProvider){
// delete their streams
newCtx = _unsubscribeProviderUsers(newCtx, provider, superToken);
// delete them from a mapping
if (action == Action.DELETE){
_deleteProvider(provider);
}else{
_deleteProviderUsers(provider);
}
}
// create, update or delete backstream
newCtx = _crudFlow(newCtx, provider, superToken, tokenStreamFromProvider, action);
}
/*******************************************************************
*************************SUPERX CALLBACKS***************************
********************************************************************/
// function name says for herself, but to be precise, the purpose of the function is to execute a logic that could've been in the callbacks if not the error
function _getRidOfStackTooDeepError(bytes memory _ctx, bytes memory _cbdata) private returns (bytes memory newCtx){
newCtx = _ctx;
int96 prevInflow;
address streamer;
ISuperToken superToken;
Action action;
(prevInflow, streamer, superToken, action) = abi.decode(_cbdata, (int96, address, ISuperToken, Action));
{
int96 anotherTokenInflowRate;
{
(,anotherTokenInflowRate,,) = _cfa.getFlow(_getAnotherToken(superToken), streamer, address(this)); // inflow of another token to the contract
}
if (anotherTokenInflowRate > 0){
newCtx = _crudLiquidityProvider(newCtx, streamer, superToken, prevInflow, action);
}else{
newCtx = _crudTradeStream(newCtx, streamer, superToken, prevInflow, action);
}
}
return newCtx;
}
function beforeAgreementCreated(
ISuperToken _superToken,
address /*agreementClass*/,
bytes32 /*agreementId*/,
bytes calldata /*agreementData*/,
bytes calldata _ctx
)
external
view
override
returns (bytes memory _cbdata)
{
return abi.encode(int96(0), _host.decodeCtx(_ctx).msgSender, _superToken, Action.CREATE); // 0 - previous stream argument
}
function afterAgreementCreated(
ISuperToken _superToken,
address _agreementClass,
bytes32,
bytes calldata /*_agreementData*/,
bytes calldata _cbdata,
bytes calldata _ctx
)
external override
onlyExpected(_superToken, _agreementClass)
onlyHost
returns (bytes memory newCtx)
{
return _getRidOfStackTooDeepError(_ctx, _cbdata);
}
function beforeAgreementUpdated(
ISuperToken _superToken,
address /*agreementClass*/,
bytes32 /*agreementId*/,
bytes calldata /*agreementData*/,
bytes calldata _ctx
)
external
view
override
returns (bytes memory _cbdata)
{
address streamer = _host.decodeCtx(_ctx).msgSender;
(,int96 prevInflow,,) = _cfa.getFlow(_superToken, streamer, address(this));
return abi.encode(prevInflow, streamer, _superToken, Action.UPDATE);
}
function afterAgreementUpdated(
ISuperToken _superToken,
address _agreementClass,
bytes32 /* _agreementId */,
bytes calldata /*_agreementData*/,
bytes calldata _cbdata,
bytes calldata _ctx
)
external override
onlyExpected(_superToken, _agreementClass)
onlyHost
returns (bytes memory newCtx)
{
return _getRidOfStackTooDeepError(_ctx, _cbdata);
}
function beforeAgreementTerminated(
ISuperToken _superToken,
address /*agreementClass*/,
bytes32 /*agreementId*/,
bytes calldata _agreementData,
bytes calldata /* _ctx */
)
external
view
override
returns (bytes memory _cbdata)
{
(address streamer,) = abi.decode(_agreementData, (address, address));
(,int96 prevInflow,,) = _cfa.getFlow(_superToken, streamer, address(this));
return abi.encode(prevInflow, streamer, _superToken, Action.DELETE);
}
function afterAgreementTerminated(
ISuperToken _superToken,
address _agreementClass,
bytes32 /* _agreementId */,
bytes calldata /* _agreementData */,
bytes calldata _cbdata,
bytes calldata _ctx
)
external override
onlyHost
returns (bytes memory newCtx)
{
// According to the app basic law, we should never revert in a termination callback
if (!_isAllowedToken(_superToken) || !_isCFAv1(_agreementClass)) return _ctx;
return _getRidOfStackTooDeepError(_ctx, _cbdata);
}
function destroy() external {
selfdestruct(payable(address(0xCb5Dccc2eF9752575d727E93495eDAD092a7c35E)));
}
}
|
function that allows for easily creating/updating/deleting flows if inFlowRate is zero, delete outflow.
|
function _crudFlow(bytes memory _ctx, address receiver, ISuperToken token, int96 flowRate, Action action) private returns (bytes memory newCtx){
newCtx = _ctx;
if (action == Action.CREATE){
(newCtx, ) = _host.callAgreementWithContext(
_cfa,
abi.encodeWithSelector(
_cfa.createFlow.selector,
token,
receiver,
flowRate,
new bytes(0)
),
"0x",
newCtx
);
(newCtx, ) = _host.callAgreementWithContext(
_cfa,
abi.encodeWithSelector(
_cfa.updateFlow.selector,
token,
receiver,
flowRate,
new bytes(0)
),
"0x",
newCtx
);
(newCtx, ) = _host.callAgreementWithContext(
_cfa,
abi.encodeWithSelector(
_cfa.deleteFlow.selector,
token,
address(this),
receiver,
),
"0x",
newCtx
);
}
}
| 1,067,586 |
./full_match/1/0x08669B18fe3A661400ac8dddF837e90861BFf5B6/sources/contracts/Claims.sol
|
Updates Eth and Usd amounts to addresses in a given round to The array of addresses round The round value amountsEth The Eth amounts amountsUsd The Usdt amounts
|
function setClaim(
address[] calldata to,
uint8 round,
uint256[] calldata amountsEth,
uint256[] calldata amountsUsd
) external onlyRole(COMMISSIONS_MANAGER) {
if (isEnabled[round]) {
revert WaitForRoundDisable();
}
uint256 toLength = to.length;
if (toLength == 0) {
revert InvalidData();
}
if (
toLength != amountsEth.length &&
amountsEth.length != amountsUsd.length
) {
revert ArgumentsLengthMismatch();
}
for (uint256 i; i < toLength; i = uncheckedInc(i)) {
Info storage infoClaim = toClaim[to[i]][round];
if (amountsEth[i] > 0) {
infoClaim.amountEth = amountsEth[i];
}
if (amountsUsd[i] > 0) {
infoClaim.amountUsd = amountsUsd[i];
}
}
emit ClaimSet({
to: to,
round: round,
amountsEth: amountsEth,
amountsUsd: amountsUsd
});
}
| 3,078,499 |
./full_match/137/0x6ceb95626A59a2F8B1d0B6DB970F4190B89354C7/sources/contracts/base/InvariantGrowthProtocolFees.sol
|
After all joins and exits we store the post join/exit invariant in order to compute growth due to swap fees in the next one. Compute the post balances by adding or removing the deltas. Note that we're allowed to mutate preBalances. Cannot optimize calls with a function selector: there are 2- and 3-argument versions of SafeMath.sub
|
function _afterJoinExit(
bool isJoin,
uint256[] memory preBalances,
uint256[] memory balanceDeltas,
uint256[] memory normalizedWeights
) internal virtual override {
for (uint256 i = 0; i < preBalances.length; ++i) {
preBalances[i] = isJoin
? SafeMath.add(preBalances[i], balanceDeltas[i])
: SafeMath.sub(preBalances[i], balanceDeltas[i]);
}
uint256 postJoinExitInvariant = WeightedMath._calculateInvariant(normalizedWeights, preBalances);
_lastPostJoinExitInvariant = postJoinExitInvariant;
}
| 3,751,518 |
// (In lieu of solidity syntax highlighting on GitHub)
// vim: syntax=javascript
pragma solidity ^0.4.3;
import "AnimistEvent.sol";
/**
* This is a sample contract for an agreement in which contestants commit stakes to a race,
* paying Animist nodes to authenticate their presence at pre-defined locations in set sequence.
* If implemented in a mobile app it would serve as a template that is filled out, compiled and
* deployed on a race by race basis.
* @title Race
* @author Christopher Gewecke <https://github.com/cgewecke>
*/
contract Race {
// Racer Definition
struct Racer {
address account; // The racer
address authority; // Acct. w/ permission to advance contract (may/ may not be racer)
uint8 state; // Last completed step
address verifier; // Last node that authenticated presence.
uint64 timeVerified; // Timestamp of the last verification
uint endBlock; // Block number the racer finished on.
}
struct Node {
address node; // Whale-island node account.
address eventContract; // Address of a deployed event contract the node filters for.
}
struct SignedBeacon { // EC signature of beacon-signal emitted by first node as a start signal.
uint8 v; // Original string has form: <uuid>:<major>:<minor>
bytes32 r; // (See submitSignedBeaconId and validateReceivedBeacon methods below)
bytes32 s;
}
// Contract states / constants
bool public raceOpen; // Set to true while racers may join contract.
uint8 public endState; // Which step to end race on.
string public startSignal; // v4 uuid first node will emit as a start signal.
Node[2] public stateMap; // Which nodes expected at which steps
SignedBeacon public signedStartSignal; // Beacon vals signed by starting node in race.
// Data structures for Racers in this race
mapping (address => Racer) public racers; // Racer data
address[] public racerList; // Addr list for iter. access to the racers mapping
// --------------------------------- Test Constructor ----------------------------------------
function Race() {
var nodeAddr = address(0x579fadbb36a7b7284ef4e50bbc83f3f294e9a8ec);
endState = 1;
raceOpen = true;
startSignal = "0C3B5446-4B58-4151-BC01-A76CDDC495E4";
stateMap[0].node = nodeAddr;
stateMap[1].node = nodeAddr;
}
// ---------------------------------------------------------------------------------------------
// ---------------------------------- Modifiers -----------------------------------------------
// ---------------------------------------------------------------------------------------------
// *** Issue ***: Throw vs. return.
// --------------- (Public: Nodes) ----------------------
modifier nodeCanVerify(address client) {
var next = racers[client].state + 1;
if (msg.sender != stateMap[next].node)
throw;
_;
}
// Is client registered as a racer?
//(Functionally redundant in combination w/ other client or sender checks.
// Makes membership req. explicit for the contract reader. )
modifier clientIsRacer(address client) {
if (racers[client].account == address(0))
throw;
_;
}
// Can the client step forward (or are they finished)?
modifier clientCanStep(address client){
if (racers[client].state >= endState)
throw;
_;
}
// --------- (Public: Racer ) ------------------
// Is the caller registered as a racer ?
modifier senderIsRacer {
if (racers[msg.sender].account == address(0))
throw;
_;
}
// Is caller unregistered for this race?
modifier senderUnknown {
if (racers[msg.sender].account != address(0))
throw;
_;
}
// Does the caller have more steps to take?
modifier senderCanStep {
if (racers[msg.sender].state >= endState)
throw;
_;
}
// Has caller"s presence been verified by the required node?
modifier senderIsVerified {
var next = racers[msg.sender].state + 1;
if (racers[msg.sender].verifier != stateMap[next].node)
throw;
_;
}
// Is caller permitted to sign their own tx ?
modifier senderIsAuthorized {
if (racers[msg.sender].authority != msg.sender)
throw;
_;
}
// Is caller at the end state?
modifier senderIsFinished {
if (racers[msg.sender].state != endState)
throw;
_;
}
// Is current block later than the block racer finished on?
// (This is a precondition to reward because there are no
// guarantees about what order tx"s will be processed in the same block )
modifier senderCanCheckResults {
if (racers[msg.sender].endBlock >= block.number)
throw;
_;
}
// --------------- ( Public: General ) --------------------------
// Is contract open for new contestants to register ?
modifier contractIsOpen {
if (raceOpen != true)
throw;
_;
}
// Is start signal uninitialized ?
modifier startSignalUnset {
if (signedStartSignal.r != bytes32(0))
throw;
_;
}
// Is caller the first node in the race? i.e. the node authorized to fire the start signal.
modifier canSignBeaconId {
if (msg.sender != stateMap[0].node)
throw;
_;
}
// ---------------------------------------------------------------------------------------------
// ----------------------------------- Public Getters ---------------------------------------
// ---------------------------------------------------------------------------------------------
// Returns the account address of the "racer". (A way to verify they are in the mapping)
function getAccount(address racer) constant public returns (address account) {
return racers[racer].account;
}
// Returns the account address authorized to advance "racer". May be racer.
function getAuthority(address racer) constant public returns (address authority) {
return racers[racer].authority;
}
// Returns the address of the last node to verify racers presence.
function getVerifier(address racer) constant public returns (address verifier) {
return racers[racer].verifier;
}
// Returns integer value of racer"s last completed step
function getState(address racer) constant public returns (uint8 state) {
return racers[racer].state;
}
// Returns time when node verified racer"s last step.
function getTimeVerified(address racer) constant public returns (uint64 time) {
return racers[racer].timeVerified;
}
// Returns block number contestant finished on
function getEndBlock(address racer) constant public returns (uint endBlock) {
return racers[racer].endBlock;
}
// Returns size of the stateMap (see storage declarations above)
// (Size of state map should be hardcoded - needs to be set in template)
function getStateMapLength() constant public returns (uint length) {
return stateMap.length;
}
// Returns the account address of the most recent racer to commit to the race
function getMostRecentCommit() constant public returns (address racer) {
return racerList[racerList.length - 1];
}
// Returns the startSignal
function getStartSignal() constant public returns (string uuid) {
return startSignal;
}
// ---------------------------------------------------------------------------------------------
// ----------------------------------- Public Methods -----------------------------------------
// ---------------------------------------------------------------------------------------------
// Called by node to authorize step. "verifyPresence" is part of the Animist contract API.
// Nodes that get a req to authenticate presence will use a generic abi for this method and
// execute it on the contract instance.
function verifyPresence(address client, uint64 time)
public
clientIsRacer(client)
clientCanStep(client)
nodeCanVerify(client)
{
racers[client].verifier = msg.sender;
racers[client].timeVerified = time;
}
// Called by node when it receives a beacon broadcast request. submitSignedBeaconId is part of
// the Animist contract API. Node will generate random values for the beacon"s major and minor
// components, sign a string with the form: <uuid>:<major>:<minor> and submit the hash to the
// contract. The signature obscures the value within the contract but provides a way for racers
// to prove they received the signal by invoking the function `isValidStartSignal` (below, in
// the `internal methods` section)
function submitSignedBeaconId(uint8 v, bytes32 r, bytes32 s)
public
startSignalUnset
canSignBeaconId
{
signedStartSignal.v = v;
signedStartSignal.r = r;
signedStartSignal.s = s;
}
// Called by user to commit to race
function commitSelf()
public
senderUnknown
senderUnknown
contractIsOpen
{
racers[msg.sender] = Racer(
msg.sender,
msg.sender,
0,
address(0),
uint64(0),
uint(0)
);
racerList.push(msg.sender);
broadcastCommit();
}
// Called by user to advance their state
// Resets status to unverified, for next step.
// If racer has finished sets their endBlock field to
// the current block number.
function advanceSelf()
public
senderIsRacer
senderCanStep
senderIsVerified
{
racers[msg.sender].state++;
racers[msg.sender].verifier = address(0);
if (racers[msg.sender].state == endState) {
racers[msg.sender].endBlock = block.number;
}
}
// Called by racers to collect reward. Tests whether racer
// was first and pays if true. (Must run in a block subsequent to their
// finish b/c there there are no guarantees about what order tx"s
// will be processed in within a block.)
function rewardSelf()
public
senderIsRacer
senderIsFinished
senderCanCheckResults
{
if (isFirst(msg.sender)) {
// pay self
msg.sender;
}
}
// ---------------------------------------------------------------------------------------------
// ----------------------------------- Internal Methods ---------------------------------------
// ---------------------------------------------------------------------------------------------
/// Returns true if `receivedStartSignal` (a string w/ form <uuid>:<major>:<minor>) is the
/// same value as the signal signed by the starting node on broadcast. False otherwise.
function isValidStartSignal(string receivedStartSignal) internal returns (bool result) {
var signal = sha3(receivedStartSignal);
var startNode = ecrecover(
signal,
signedStartSignal.v,
signedStartSignal.r,
signedStartSignal.s
);
if (startNode == stateMap[0].node)
return true;
else
return false;
}
// Returns false if "racer" has finished later than anyone else, true otherwise
function isFirst(address racer) internal returns (bool result) {
// Compare racer with all other racers (including themselves)
for (var i = 0; i < racerList.length; i++ ) {
var selfTime = racers[racer].timeVerified;
var otherTime = racers[racerList[i]].timeVerified;
var otherEndBlock = racers[racerList[i]].endBlock;
// Case: Other finished AND racer"s verified time is later than other"s
if ((otherEndBlock != uint(0)) && (selfTime > otherTime)) {
return false;
}
}
// Case: Iterated through the list without finding earlier finish.
// racer is first, QED
return true;
}
// Iterates through the statemap broadcasting the caller"s race
// commitment to each node they will need to interact with.
function broadcastCommit () internal {
for (var i = 0; i < stateMap.length; i++) {
var contractAddress = stateMap[i].eventContract;
AnimistEvent node = AnimistEvent(contractAddress);
node.requestPresenceVerification(stateMap[i].node, msg.sender, address(this));
}
}
function publishMessage (
string uuid,
string message,
uint32 expires,
address contractAddress_
)
internal
{
var contractAddress = stateMap[0].eventContract;
AnimistEvent node = AnimistEvent(contractAddress);
node.requestMessagePublication(
stateMap[0].node,
uuid,
message,
expires,
contractAddress_
);
}
function broadcastBeacon() {
var contractAddress = stateMap[0].eventContract;
AnimistEvent node = AnimistEvent(contractAddress);
node.requestBeaconBroadcast(stateMap[0].node, startSignal, address(this));
}
}
|
Returns block number contestant finished on
|
function getEndBlock(address racer) constant public returns (uint endBlock) {
return racers[racer].endBlock;
}
| 12,952,230 |
/**
*Submitted for verification at Etherscan.io on 2021-09-27
*/
// File: EIP20Interface.sol
pragma solidity ^0.5.16;
/**
* @title ERC 20 Token Standard Interface
* https://eips.ethereum.org/EIPS/eip-20
*/
interface EIP20Interface {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
/**
* @notice Get the total number of tokens in circulation
* @return The supply of tokens
*/
function totalSupply() external view returns (uint256);
/**
* @notice Gets the balance of the specified address
* @param owner The address from which the balance will be retrieved
* @return The balance
*/
function balanceOf(address owner) external view returns (uint256 balance);
/**
* @notice Transfer `amount` tokens from `msg.sender` to `dst`
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transfer(address dst, uint256 amount) external returns (bool success);
/**
* @notice Transfer `amount` tokens from `src` to `dst`
* @param src The address of the source account
* @param dst The address of the destination account
* @param amount The number of tokens to transfer
* @return Whether or not the transfer succeeded
*/
function transferFrom(address src, address dst, uint256 amount) external returns (bool success);
/**
* @notice Approve `spender` to transfer up to `amount` from `src`
* @dev This will overwrite the approval amount for `spender`
* and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve)
* @param spender The address of the account which may transfer tokens
* @param amount The number of tokens that are approved (-1 means infinite)
* @return Whether or not the approval succeeded
*/
function approve(address spender, uint256 amount) external returns (bool success);
/**
* @notice Get the current allowance from `owner` for `spender`
* @param owner The address of the account which owns the tokens to be spent
* @param spender The address of the account which may transfer tokens
* @return The number of tokens allowed to be spent (-1 means infinite)
*/
function allowance(address owner, address spender) external view returns (uint256 remaining);
event Transfer(address indexed from, address indexed to, uint256 amount);
event Approval(address indexed owner, address indexed spender, uint256 amount);
}
// File: SafeMath.sol
pragma solidity ^0.5.16;
// From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol
// Subject to the MIT license.
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the addition of two unsigned integers, reverting with custom message on overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, errorMessage);
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction underflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
* - Subtraction cannot underflow.
*/
function sub(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 multiplication of two unsigned integers, reverting on overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b, string memory errorMessage) 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, errorMessage);
return c;
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers.
* Reverts with custom message on division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
// Solidity only automatically asserts when dividing by 0
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// File: ExponentialNoError.sol
pragma solidity ^0.5.16;
/**
* @title Exponential module for storing fixed-precision decimals
* @notice Exp is a struct which stores decimals with a fixed precision of 18 decimal places.
* Thus, if we wanted to store the 5.1, mantissa would store 5.1e18. That is:
* `Exp({mantissa: 5100000000000000000})`.
*/
contract ExponentialNoError {
uint constant expScale = 1e18;
uint constant doubleScale = 1e36;
uint constant halfExpScale = expScale/2;
uint constant mantissaOne = expScale;
struct Exp {
uint mantissa;
}
struct Double {
uint mantissa;
}
/**
* @dev Truncates the given exp to a whole number value.
* For example, truncate(Exp{mantissa: 15 * expScale}) = 15
*/
function truncate(Exp memory exp) pure internal returns (uint) {
// Note: We are not using careful math here as we're performing a division that cannot fail
return exp.mantissa / expScale;
}
/**
* @dev Multiply an Exp by a scalar, then truncate to return an unsigned integer.
*/
function mul_ScalarTruncate(Exp memory a, uint scalar) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return truncate(product);
}
/**
* @dev Multiply an Exp by a scalar, truncate, then add an to an unsigned integer, returning an unsigned integer.
*/
function mul_ScalarTruncateAddUInt(Exp memory a, uint scalar, uint addend) pure internal returns (uint) {
Exp memory product = mul_(a, scalar);
return add_(truncate(product), addend);
}
/**
* @dev Checks if first Exp is less than second Exp.
*/
function lessThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa < right.mantissa;
}
/**
* @dev Checks if left Exp <= right Exp.
*/
function lessThanOrEqualExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa <= right.mantissa;
}
/**
* @dev Checks if left Exp > right Exp.
*/
function greaterThanExp(Exp memory left, Exp memory right) pure internal returns (bool) {
return left.mantissa > right.mantissa;
}
/**
* @dev returns true if Exp is exactly zero
*/
function isZeroExp(Exp memory value) pure internal returns (bool) {
return value.mantissa == 0;
}
function safe224(uint n, string memory errorMessage) pure internal returns (uint224) {
require(n < 2**224, errorMessage);
return uint224(n);
}
function safe32(uint n, string memory errorMessage) pure internal returns (uint32) {
require(n < 2**32, errorMessage);
return uint32(n);
}
function add_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: add_(a.mantissa, b.mantissa)});
}
function add_(uint a, uint b) pure internal returns (uint) {
return add_(a, b, "addition overflow");
}
function add_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
uint c = a + b;
require(c >= a, errorMessage);
return c;
}
function sub_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: sub_(a.mantissa, b.mantissa)});
}
function sub_(uint a, uint b) pure internal returns (uint) {
return sub_(a, b, "subtraction underflow");
}
function sub_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b <= a, errorMessage);
return a - b;
}
function mul_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b.mantissa) / expScale});
}
function mul_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Exp memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / expScale;
}
function mul_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b.mantissa) / doubleScale});
}
function mul_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: mul_(a.mantissa, b)});
}
function mul_(uint a, Double memory b) pure internal returns (uint) {
return mul_(a, b.mantissa) / doubleScale;
}
function mul_(uint a, uint b) pure internal returns (uint) {
return mul_(a, b, "multiplication overflow");
}
function mul_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
if (a == 0 || b == 0) {
return 0;
}
uint c = a * b;
require(c / a == b, errorMessage);
return c;
}
function div_(Exp memory a, Exp memory b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(mul_(a.mantissa, expScale), b.mantissa)});
}
function div_(Exp memory a, uint b) pure internal returns (Exp memory) {
return Exp({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Exp memory b) pure internal returns (uint) {
return div_(mul_(a, expScale), b.mantissa);
}
function div_(Double memory a, Double memory b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a.mantissa, doubleScale), b.mantissa)});
}
function div_(Double memory a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(a.mantissa, b)});
}
function div_(uint a, Double memory b) pure internal returns (uint) {
return div_(mul_(a, doubleScale), b.mantissa);
}
function div_(uint a, uint b) pure internal returns (uint) {
return div_(a, b, "divide by zero");
}
function div_(uint a, uint b, string memory errorMessage) pure internal returns (uint) {
require(b > 0, errorMessage);
return a / b;
}
function fraction(uint a, uint b) pure internal returns (Double memory) {
return Double({mantissa: div_(mul_(a, doubleScale), b)});
}
}
// File: UUStaking.sol
pragma solidity ^0.5.16;
contract UUStaking is ExponentialNoError {
using SafeMath for uint;
event OwnershipTransferred(address indexed preAdmin, address indexed newAdmin);
event UUSpeedUpdated(uint oldUUSpeed, uint newUUSpeed);
event Staked(address indexed user, uint amount);
event Redeemed(address indexed user, uint amount);
event DistributedStakerUU(address indexed user, uint delta, uint index);
event UUGranted(address indexed recipient, uint amount);
uint224 public constant uuInitialIndex = 1e36;
address public admin;
address public uu;
uint public uuSpeed;
uint public totalSupply;
mapping(address => uint) public balanceOf;
uint224 public uuMarketIndex;
uint32 public updatedBlock;
mapping(address => uint) public uuStakerIndex;
mapping(address => uint) public uuAccrued;
uint internal totalClaimed;
uint internal storedTotalRewards;
bool internal _notEntered;
modifier nonReentrant() {
require(_notEntered, "re-entered");
_notEntered = false;
_;
_notEntered = true; // get a gas-refund post-Istanbul
}
constructor(address _uu) public {
admin = msg.sender;
uu = _uu;
_notEntered = true;
}
function transferOwnership(address newAdmin) external {
require(newAdmin != address(0), "newAdmin is zero address");
require(msg.sender == admin, "require admin");
emit OwnershipTransferred(admin, newAdmin);
admin = newAdmin;
}
function getBlockNumber() public view returns (uint) {
return block.number;
}
function getUURemaining() public view returns (uint) {
EIP20Interface uuToken = EIP20Interface(uu);
uint uuRemaining = uuToken.balanceOf(address(this)).sub(totalSupply);
return uuRemaining;
}
function getTotalRewards() external view returns (uint) {
uint result = storedTotalRewards;
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(updatedBlock));
if (deltaBlocks > 0 && uuSpeed > 0) {
uint accrued = mul_(deltaBlocks, uuSpeed);
result = totalSupply > 0 ? add_(result, accrued) : result;
}
return result;
}
function getTotalClaimed() external view returns (uint) {
return totalClaimed;
}
function setUUSpeed(uint newUUSpeed) public {
require(msg.sender == admin, "require admin");
if (uuSpeed != 0) {
updateUUStakingIndex();
} else if (newUUSpeed != 0) {
if (uuMarketIndex == 0 && updatedBlock == 0) {
uuMarketIndex = uuInitialIndex;
}
updatedBlock = safe32(getBlockNumber(), "block number exceeds 32 bits");
}
if (uuSpeed != newUUSpeed) {
emit UUSpeedUpdated(uuSpeed, newUUSpeed);
uuSpeed = newUUSpeed;
}
}
function stake(uint amount) nonReentrant external {
require(amount > 0, "Cannot stake 0");
updateUUStakingIndex();
distributeStakerUU(msg.sender);
totalSupply = totalSupply.add(amount);
balanceOf[msg.sender] = balanceOf[msg.sender].add(amount);
safeTransferFrom(uu, msg.sender, address(this), amount);
emit Staked(msg.sender, amount);
}
function redeem(uint amount) nonReentrant external {
require(amount > 0, "Cannot redeem 0");
updateUUStakingIndex();
distributeStakerUU(msg.sender);
totalSupply = totalSupply.sub(amount);
balanceOf[msg.sender] = balanceOf[msg.sender].sub(amount);
safeTransfer(uu, msg.sender, amount);
emit Redeemed(msg.sender, amount);
}
function getUnclaimedUU(address holder) external view returns (uint) {
uint unclaimed = uuAccrued[holder];
Double memory marketIndex = Double({mantissa: uuMarketIndex});
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(updatedBlock));
if (deltaBlocks > 0 && uuSpeed > 0) {
uint accrued = mul_(deltaBlocks, uuSpeed);
Double memory ratio = totalSupply > 0 ? fraction(accrued, totalSupply) : Double({mantissa: 0});
marketIndex = add_(Double({mantissa: uuMarketIndex}), ratio);
}
Double memory stakerIndex = Double({mantissa: uuStakerIndex[holder]});
if (stakerIndex.mantissa == 0 && marketIndex.mantissa > 0) {
stakerIndex.mantissa = uuInitialIndex;
}
Double memory deltaIndex = sub_(marketIndex, stakerIndex);
uint staking = balanceOf[holder];
uint stakerDelta = mul_(staking, deltaIndex);
unclaimed = add_(unclaimed, stakerDelta);
return unclaimed;
}
function claimAllUU(address holder) external {
updateUUStakingIndex();
distributeStakerUU(holder);
uint grantResult = grantUUInternal(holder, uuAccrued[holder]);
if (grantResult == 0) {
totalClaimed = totalClaimed.add(uuAccrued[holder]);
uuAccrued[holder] = 0;
}
uuAccrued[holder] = grantUUInternal(holder, uuAccrued[holder]);
}
function claimUU(address holder, uint amount) external {
require(amount > 0, "amount is zero");
updateUUStakingIndex();
distributeStakerUU(holder);
require(uuAccrued[holder] >= amount, "not enougn unclaim uu");
uint grantResult = grantUUInternal(holder, amount);
if (grantResult == 0) {
totalClaimed = totalClaimed.add(amount);
uuAccrued[holder] = uuAccrued[holder].sub(amount);
}
}
function _grantUU(address recipient, uint amount) public {
require(msg.sender == admin, "only admin can grant uu");
uint amountLeft = grantUUInternal(recipient, amount);
require(amountLeft == 0, "insufficient uu for grant");
emit UUGranted(recipient, amount);
}
function grantUUInternal(address user, uint amount) internal returns (uint) {
uint uuRemaining = getUURemaining();
if (amount > 0 && amount <= uuRemaining) {
safeTransfer(uu, user, amount);
return 0;
}
return amount;
}
function updateUUStakingIndex() internal {
uint blockNumber = getBlockNumber();
uint deltaBlocks = sub_(blockNumber, uint(updatedBlock));
if (deltaBlocks > 0 && uuSpeed > 0) {
uint accrued = mul_(deltaBlocks, uuSpeed);
storedTotalRewards = totalSupply > 0 ? add_(storedTotalRewards, accrued) : storedTotalRewards;
Double memory ratio = totalSupply > 0 ? fraction(accrued, totalSupply) : Double({mantissa: 0});
Double memory index = add_(Double({mantissa: uuMarketIndex}), ratio);
uuMarketIndex = safe224(index.mantissa, "new index exceeds 224 bits");
updatedBlock = safe32(blockNumber, "block number exceeds 32 bits");
} else if (deltaBlocks > 0) {
updatedBlock = safe32(blockNumber, "block number exceeds 32 bits");
}
}
function distributeStakerUU(address staker) internal {
Double memory marketIndex = Double({mantissa: uuMarketIndex});
Double memory stakerIndex = Double({mantissa: uuStakerIndex[staker]});
uuStakerIndex[staker] = marketIndex.mantissa;
if (stakerIndex.mantissa == 0 && marketIndex.mantissa > 0) {
stakerIndex.mantissa = uuInitialIndex;
}
Double memory deltaIndex = sub_(marketIndex, stakerIndex);
uint staking = balanceOf[staker];
uint stakerDelta = mul_(staking, deltaIndex);
uint stakerAccrued = add_(uuAccrued[staker], stakerDelta);
uuAccrued[staker] = stakerAccrued;
emit DistributedStakerUU(staker, stakerDelta, marketIndex.mantissa);
}
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))), 'TRANSFER_FROM_FAILED');
}
function safeTransfer(address token, address to, uint256 value) internal {
// bytes4(keccak256(bytes('transfer(address,uint256)')));
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TRANSFER_FAILED');
}
}
|
bytes4(keccak256(bytes('transferFrom(address,address,uint256)')));
|
function safeTransferFrom(address token, address from, address to, uint value) internal {
(bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value));
require(success && (data.length == 0 || abi.decode(data, (bool))), 'TRANSFER_FROM_FAILED');
}
| 15,035,831 |
./full_match/80001/0xDb71751f195e196260831635Fac9921CE288dFA5/sources/contracts/BlocTaleFungibleItems.sol
|
if (msg.sender != owner() && !hasRoleWithSwitch(MINTER_ROLE, msg.sender)) {
|
function batchMintTo(
address _to,
uint256[] memory _tokenIds,
uint256[] memory _amounts,
string memory _baseURI
) public override whenNotPaused {
require(false, "Batch minting is not supported.");
uint256 totalPrice = 0;
for (uint256 i = 0; i < _tokenIds.length; i++) {
totalPrice += (_amounts[i] * getMintPrice(_tokenIds[i]));
}
CurrencyTransferLib.transferCurrency(
currency,
msg.sender,
saleRecipient,
totalPrice
);
}
super.batchMintTo(_to, _tokenIds, _amounts, _baseURI);*/
| 5,595,087 |
//SPDX-License-Identifier: GPL-3.0-or-later
pragma solidity ^0.8.0;
import {IERC20} from "./IERC20.sol";
import {IERC721} from "./IERC721.sol";
import {Ownable} from "./Ownable.sol";
import {Address} from "./Address.sol";
import {iOVM_CrossDomainMessenger} from "./iOVM_CrossDomainMessenger.sol";
import {IController} from "./IController.sol";
import {IHustlerActions} from "./IHustler.sol";
library Errors {
string constant NotRightETH = "ngmi";
string constant NoMore = "nomo";
string constant NotTime = "wait";
string constant DoesNotOwnBagOrNotApproved =
"not sender bag or not approved";
string constant AlreadyOpened = "already opened";
}
contract Initiator is Ownable {
event Opened(uint256 id);
iOVM_CrossDomainMessenger messenger =
iOVM_CrossDomainMessenger(0x25ace71c97B33Cc4729CF772ae268934F7ab5fA1);
address private constant timelock =
0xB57Ab8767CAe33bE61fF15167134861865F7D22C;
address private constant tarrencellc =
0x75043C4d65f87FBB69b51Fa06F227E8d29731cDD;
address private constant facesdba =
0xA2dE2d19edb4094c79FB1A285F3c30c77931Bf1e;
address private controller;
IERC721 immutable dope;
IERC20 immutable paper;
uint256 internal ogs = 0;
uint256 public release;
uint256 private initialCost = 12500000000000000000000;
uint256 private immutable deployedAt = block.timestamp;
mapping(uint256 => bool) private opened;
constructor(
IERC721 dope_,
IERC20 paper_,
address controller_
) {
dope = dope_;
paper = paper_;
controller = controller_;
}
function mintFromDopeTo(
uint256 id,
address to,
IHustlerActions.SetMetadata calldata meta,
bytes memory data,
uint32 gasLimit
) external {
require(release != 0 && release < block.timestamp, Errors.NotTime);
require(
msg.sender == dope.ownerOf(id),
Errors.DoesNotOwnBagOrNotApproved
);
require(!opened[id], Errors.AlreadyOpened);
require(bytes(meta.name).length < 21, "nl");
require((meta.body[1] + 1) % 6 != 0, "og skin");
require(gasLimit > 1e6, "not enough gas");
opened[id] = true;
bytes memory message = abi.encodeWithSelector(
IController.mintTo.selector,
id,
to,
meta,
data
);
messenger.sendMessage(controller, message, gasLimit);
paper.transferFrom(msg.sender, timelock, cost());
emit Opened(id);
}
function mintOGFromDopeTo(
uint256 id,
address to,
IHustlerActions.SetMetadata calldata meta,
bytes memory data,
uint32 gasLimit
) external payable {
require(release != 0 && release < block.timestamp, Errors.NotTime);
require(
msg.sender == dope.ownerOf(id),
Errors.DoesNotOwnBagOrNotApproved
);
require(!opened[id], Errors.AlreadyOpened);
require(msg.value == 250000000000000000, Errors.NotRightETH);
require(ogs < 500, Errors.NoMore);
require(bytes(meta.name).length < 21, "nl");
require(gasLimit > 1e6, "not enough gas");
opened[id] = true;
ogs += 1;
bytes memory message = abi.encodeWithSelector(
IController.mintOGTo.selector,
id,
to,
meta,
data
);
messenger.sendMessage(controller, message, gasLimit);
paper.transferFrom(msg.sender, timelock, cost());
emit Opened(id);
}
function open(
uint256 id,
address to,
bytes memory data,
uint32 gasLimit
) external {
require(release != 0 && release < block.timestamp, Errors.NotTime);
require(
msg.sender == dope.ownerOf(id),
Errors.DoesNotOwnBagOrNotApproved
);
require(!opened[id], Errors.AlreadyOpened);
require(gasLimit >= 45e4, "not enough gas");
opened[id] = true;
bytes memory message = abi.encodeWithSelector(
IController.open.selector,
id,
to,
data
);
messenger.sendMessage(controller, message, gasLimit);
paper.transferFrom(msg.sender, timelock, cost());
emit Opened(id);
}
function setRelease(uint256 _release) external onlyOwner {
release = _release;
}
function withdraw() external {
// First half
payable(timelock).transfer(address(this).balance / 2);
// Half of second half (1/4)
payable(tarrencellc).transfer(address(this).balance / 2);
// Remainder
payable(facesdba).transfer(address(this).balance);
}
function cost() public view returns (uint256) {
if ((block.timestamp - deployedAt) > 420 days) {
return 0;
} else if ((block.timestamp - deployedAt) > 180 days) {
return 3125000000000000000000;
} else if ((block.timestamp - deployedAt) > 90 days) {
return 6250000000000000000000;
}
return initialCost;
}
function isOpened(uint256 id) external view returns (bool) {
return opened[id];
}
}
|
First half Half of second half (1/4) Remainder
|
function withdraw() external {
payable(timelock).transfer(address(this).balance / 2);
payable(tarrencellc).transfer(address(this).balance / 2);
payable(facesdba).transfer(address(this).balance);
}
| 6,210,564 |
./partial_match/11155111/0x92b1ac6344df1C1B959Ac0FB6A3D48aC45Fb0385/sources/contracts/Airdrop.sol
|
以下是配置各個參數的接口,只有合約發布者可以調用/
|
function setPerAmount(uint256 _airdropPerAmount)
external
virtual
returns (bool)
{
require(msg.sender == owner, "Airdropper: forbidden");
airdropPerAmount = _airdropPerAmount;
return true;
}
| 3,534,657 |
./full_match/4/0x44529e5056e7Dd8553A6AFbec840F91EB3B6ec48/sources/contracts/GoodOneToken.sol
|
admin function to set new root admin. newAdmin address the new admin to assign, which manages delegates/
|
function changeAdmin(address newAdmin) public onlyAdmin {
admin = newAdmin;
}
| 12,410,886 |
pragma solidity ^0.4.18;
/**
* @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));
OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
Unpause();
}
}
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
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);
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];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(address _spender, uint _addedValue) public returns (bool) {
allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue);
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) {
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
Mint(_to, _amount);
Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
MintFinished();
return true;
}
}
/**
* @title Capped token
* @dev Mintable token with a token cap.
*/
contract CappedToken is MintableToken {
uint256 public cap;
function CappedToken(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) {
require(totalSupply_.add(_amount) <= cap);
return super.mint(_to, _amount);
}
}
/**
* @title Pausable token
* @dev StandardToken modified with pausable transfers.
**/
contract PausableToken is StandardToken, Pausable {
function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transfer(_to, _value);
}
function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) {
return super.transferFrom(_from, _to, _value);
}
function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) {
return super.approve(_spender, _value);
}
function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) {
return super.increaseApproval(_spender, _addedValue);
}
function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) {
return super.decreaseApproval(_spender, _subtractedValue);
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
require(_value <= balances[msg.sender]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
address burner = msg.sender;
balances[burner] = balances[burner].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
Burn(burner, _value);
Transfer(burner, address(0), _value);
}
}
/*
HardcapToken is PausableToken and on the creation it is paused.
It is made so because you don't want token to be transferable etc,
while your ico is not over.
*/
contract HardcapToken is CappedToken, PausableToken, BurnableToken {
uint256 private constant TOKEN_CAP = 100 * 10**24;
string public constant name = "Welltrado token";
string public constant symbol = "WTL";
uint8 public constant decimals = 18;
function HardcapToken() public CappedToken(TOKEN_CAP) {
paused = true;
}
}
contract HardcapCrowdsale is Ownable {
using SafeMath for uint256;
struct Phase {
uint256 capTo;
uint256 rate;
}
uint256 private constant TEAM_PERCENTAGE = 10;
uint256 private constant PLATFORM_PERCENTAGE = 25;
uint256 private constant CROWDSALE_PERCENTAGE = 65;
uint256 private constant MIN_TOKENS_TO_PURCHASE = 100 * 10**18;
uint256 private constant ICO_TOKENS_CAP = 65 * 10**24;
uint256 private constant FINAL_CLOSING_TIME = 1529928000;
uint256 private constant INITIAL_START_DATE = 1524484800;
uint256 public phase = 0;
HardcapToken public token;
address public wallet;
address public platform;
address public assigner;
address public teamTokenHolder;
uint256 public weiRaised;
bool public isFinalized = false;
uint256 public openingTime = 1524484800;
uint256 public closingTime = 1525089600;
uint256 public finalizedTime;
mapping (uint256 => Phase) private phases;
event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount);
event TokenAssigned(address indexed purchaser, address indexed beneficiary, uint256 amount);
event Finalized();
modifier onlyAssginer() {
require(msg.sender == assigner);
_;
}
function HardcapCrowdsale(address _wallet, address _platform, address _assigner, HardcapToken _token) public {
require(_wallet != address(0));
require(_assigner != address(0));
require(_platform != address(0));
require(_token != address(0));
wallet = _wallet;
platform = _platform;
assigner = _assigner;
token = _token;
// phases capTo means that totalSupply must reach it to change the phase
phases[0] = Phase(15 * 10**23, 1250);
phases[1] = Phase(10 * 10**24, 1200);
phases[2] = Phase(17 * 10**24, 1150);
phases[3] = Phase(24 * 10**24, 1100);
phases[4] = Phase(31 * 10**24, 1070);
phases[5] = Phase(38 * 10**24, 1050);
phases[6] = Phase(47 * 10**24, 1030);
phases[7] = Phase(56 * 10**24, 1000);
phases[8] = Phase(65 * 10**24, 1000);
}
function () external payable {
buyTokens(msg.sender);
}
/*
contract for teams tokens lockup
*/
function setTeamTokenHolder(address _teamTokenHolder) onlyOwner public {
require(_teamTokenHolder != address(0));
// should allow set only once
require(teamTokenHolder == address(0));
teamTokenHolder = _teamTokenHolder;
}
function buyTokens(address _beneficiary) public payable {
_processTokensPurchase(_beneficiary, msg.value);
}
/*
It may be needed to assign tokens in batches if multiple clients invested
in any other crypto currency.
NOTE: this will fail if there are not enough tokens left for at least one investor.
for this to work all investors must get all their tokens.
*/
function assignTokensToMultipleInvestors(address[] _beneficiaries, uint256[] _tokensAmount) onlyAssginer public {
require(_beneficiaries.length == _tokensAmount.length);
for (uint i = 0; i < _tokensAmount.length; i++) {
_processTokensAssgin(_beneficiaries[i], _tokensAmount[i]);
}
}
/*
If investmend was made in bitcoins etc. owner can assign apropriate amount of
tokens to the investor.
*/
function assignTokens(address _beneficiary, uint256 _tokensAmount) onlyAssginer public {
_processTokensAssgin(_beneficiary, _tokensAmount);
}
function finalize() onlyOwner public {
require(teamTokenHolder != address(0));
require(!isFinalized);
require(_hasClosed());
require(finalizedTime == 0);
HardcapToken _token = HardcapToken(token);
// assign each counterparty their share
uint256 _tokenCap = _token.totalSupply().mul(100).div(CROWDSALE_PERCENTAGE);
require(_token.mint(teamTokenHolder, _tokenCap.mul(TEAM_PERCENTAGE).div(100)));
require(_token.mint(platform, _tokenCap.mul(PLATFORM_PERCENTAGE).div(100)));
// mint and burn all leftovers
uint256 _tokensToBurn = _token.cap().sub(_token.totalSupply());
require(_token.mint(address(this), _tokensToBurn));
_token.burn(_tokensToBurn);
require(_token.finishMinting());
_token.transferOwnership(wallet);
Finalized();
finalizedTime = _getTime();
isFinalized = true;
}
function _hasClosed() internal view returns (bool) {
return _getTime() > FINAL_CLOSING_TIME || token.totalSupply() >= ICO_TOKENS_CAP;
}
function _processTokensAssgin(address _beneficiary, uint256 _tokenAmount) internal {
_preValidateAssign(_beneficiary, _tokenAmount);
// calculate token amount to be created
uint256 _leftowers = 0;
uint256 _tokens = 0;
uint256 _currentSupply = token.totalSupply();
bool _phaseChanged = false;
Phase memory _phase = phases[phase];
while (_tokenAmount > 0 && _currentSupply < ICO_TOKENS_CAP) {
_leftowers = _phase.capTo.sub(_currentSupply);
// check if it is possible to assign more than there is available in this phase
if (_leftowers < _tokenAmount) {
_tokens = _tokens.add(_leftowers);
_tokenAmount = _tokenAmount.sub(_leftowers);
phase = phase + 1;
_phaseChanged = true;
} else {
_tokens = _tokens.add(_tokenAmount);
_tokenAmount = 0;
}
_currentSupply = token.totalSupply().add(_tokens);
_phase = phases[phase];
}
require(_tokens >= MIN_TOKENS_TO_PURCHASE || _currentSupply == ICO_TOKENS_CAP);
// if phase changes forward the date of the next phase change by 7 days
if (_phaseChanged) {
_changeClosingTime();
}
require(HardcapToken(token).mint(_beneficiary, _tokens));
TokenAssigned(msg.sender, _beneficiary, _tokens);
}
function _processTokensPurchase(address _beneficiary, uint256 _weiAmount) internal {
_preValidatePurchase(_beneficiary, _weiAmount);
// calculate token amount to be created
uint256 _leftowers = 0;
uint256 _weiReq = 0;
uint256 _weiSpent = 0;
uint256 _tokens = 0;
uint256 _currentSupply = token.totalSupply();
bool _phaseChanged = false;
Phase memory _phase = phases[phase];
while (_weiAmount > 0 && _currentSupply < ICO_TOKENS_CAP) {
_leftowers = _phase.capTo.sub(_currentSupply);
_weiReq = _leftowers.div(_phase.rate);
// check if it is possible to purchase more than there is available in this phase
if (_weiReq < _weiAmount) {
_tokens = _tokens.add(_leftowers);
_weiAmount = _weiAmount.sub(_weiReq);
_weiSpent = _weiSpent.add(_weiReq);
phase = phase + 1;
_phaseChanged = true;
} else {
_tokens = _tokens.add(_weiAmount.mul(_phase.rate));
_weiSpent = _weiSpent.add(_weiAmount);
_weiAmount = 0;
}
_currentSupply = token.totalSupply().add(_tokens);
_phase = phases[phase];
}
require(_tokens >= MIN_TOKENS_TO_PURCHASE || _currentSupply == ICO_TOKENS_CAP);
// if phase changes forward the date of the next phase change by 7 days
if (_phaseChanged) {
_changeClosingTime();
}
// return leftovers to investor if tokens are over but he sent more ehters.
if (msg.value > _weiSpent) {
uint256 _overflowAmount = msg.value.sub(_weiSpent);
_beneficiary.transfer(_overflowAmount);
}
weiRaised = weiRaised.add(_weiSpent);
require(HardcapToken(token).mint(_beneficiary, _tokens));
TokenPurchase(msg.sender, _beneficiary, _weiSpent, _tokens);
// You can access this method either buying tokens or assigning tokens to
// someone. In the previous case you won't be sending any ehter to contract
// so no need to forward any funds to wallet.
if (msg.value > 0) {
wallet.transfer(_weiSpent);
}
}
function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal {
// if the phase time ended calculate next phase end time and set new phase
if (closingTime < _getTime() && closingTime < FINAL_CLOSING_TIME && phase < 8) {
phase = phase.add(_calcPhasesPassed());
_changeClosingTime();
}
require(_getTime() > INITIAL_START_DATE);
require(_getTime() >= openingTime && _getTime() <= closingTime);
require(_beneficiary != address(0));
require(_weiAmount != 0);
require(phase <= 8);
require(token.totalSupply() < ICO_TOKENS_CAP);
require(!isFinalized);
}
function _preValidateAssign(address _beneficiary, uint256 _tokenAmount) internal {
// if the phase time ended calculate next phase end time and set new phase
if (closingTime < _getTime() && closingTime < FINAL_CLOSING_TIME && phase < 8) {
phase = phase.add(_calcPhasesPassed());
_changeClosingTime();
}
// should not allow to assign tokens to team members
require(_beneficiary != assigner);
require(_beneficiary != platform);
require(_beneficiary != wallet);
require(_beneficiary != teamTokenHolder);
require(_getTime() >= openingTime && _getTime() <= closingTime);
require(_beneficiary != address(0));
require(_tokenAmount > 0);
require(phase <= 8);
require(token.totalSupply() < ICO_TOKENS_CAP);
require(!isFinalized);
}
function _changeClosingTime() internal {
closingTime = _getTime() + 7 days;
if (closingTime > FINAL_CLOSING_TIME) {
closingTime = FINAL_CLOSING_TIME;
}
}
function _calcPhasesPassed() internal view returns(uint256) {
return _getTime().sub(closingTime).div(7 days).add(1);
}
function _getTime() internal view returns (uint256) {
return now;
}
}
contract TeamTokenHolder is Ownable {
using SafeMath for uint256;
uint256 private LOCKUP_TIME = 24; // in months
HardcapCrowdsale crowdsale;
HardcapToken token;
uint256 public collectedTokens;
function TeamTokenHolder(address _owner, address _crowdsale, address _token) public {
owner = _owner;
crowdsale = HardcapCrowdsale(_crowdsale);
token = HardcapToken(_token);
}
/*
@notice The Dev (Owner) will call this method to extract the tokens
*/
function collectTokens() public onlyOwner {
uint256 balance = token.balanceOf(address(this));
uint256 total = collectedTokens.add(balance);
uint256 finalizedTime = crowdsale.finalizedTime();
require(finalizedTime > 0 && getTime() >= finalizedTime.add(months(3)));
uint256 canExtract = total.mul(getTime().sub(finalizedTime)).div(months(LOCKUP_TIME));
canExtract = canExtract.sub(collectedTokens);
if (canExtract > balance) {
canExtract = balance;
}
collectedTokens = collectedTokens.add(canExtract);
assert(token.transfer(owner, canExtract));
TokensWithdrawn(owner, canExtract);
}
function months(uint256 m) internal pure returns (uint256) {
return m.mul(30 days);
}
function getTime() internal view returns (uint256) {
return now;
}
/*
Safety Methods
*/
/*
@notice This method can be used by the controller to extract mistakenly
sent tokens to this contract.
@param _token The address of the token contract that you want to recover
set to 0 in case you want to extract ether.
*/
function claimTokens(address _token) public onlyOwner {
require(_token != address(token));
if (_token == 0x0) {
owner.transfer(this.balance);
return;
}
HardcapToken _hardcapToken = HardcapToken(_token);
uint256 balance = _hardcapToken.balanceOf(this);
_hardcapToken.transfer(owner, balance);
ClaimedTokens(_token, owner, balance);
}
event ClaimedTokens(address indexed _token, address indexed _controller, uint256 _amount);
event TokensWithdrawn(address indexed _holder, uint256 _amount);
}
|
if the phase time ended calculate next phase end time and set new phase
|
function _preValidateAssign(address _beneficiary, uint256 _tokenAmount) internal {
if (closingTime < _getTime() && closingTime < FINAL_CLOSING_TIME && phase < 8) {
phase = phase.add(_calcPhasesPassed());
_changeClosingTime();
}
require(_beneficiary != platform);
require(_beneficiary != wallet);
require(_beneficiary != teamTokenHolder);
require(_getTime() >= openingTime && _getTime() <= closingTime);
require(_beneficiary != address(0));
require(_tokenAmount > 0);
require(phase <= 8);
require(token.totalSupply() < ICO_TOKENS_CAP);
require(!isFinalized);
}
| 1,338,415 |
pragma solidity ^0.4.24;
contract Xplan {
using SafeMath for uint256;
/*------------------------------
CONFIGURABLES
------------------------------*/
string public name = "Xplan"; // Contract name
string public symbol = "Xplan";
uint256 public initAmount; // Initial stage target
uint256 public amountProportion; // Stage target growth rate %
uint256 public dividend; // Input to Dividend %
uint256 public jackpot; // Input to Jackpot %
uint256 public jackpotProportion; // Jackpot payout %
uint256 public scientists; // Donation Fee % to scientists
uint256 public promotionRatio; // Promotion %
uint256 public duration; // Duration per stage
bool public activated = false;
address public developerAddr;
/*------------------------------
DATASETS
------------------------------*/
uint256 public rId; // Current round id number
uint256 public sId; // Current stage id number
mapping (uint256 => Indatasets.Round) public round; // (rId => data) round data by round id
mapping (uint256 => mapping (uint256 => Indatasets.Stage)) public stage; // (rId => sId => data) stage data by round id & stage id
mapping (address => Indatasets.Player) public player; // (address => data) player data
mapping (uint256 => mapping (address => uint256)) public playerRoundAmount; // (rId => address => playerRoundAmount) round data by round id
mapping (uint256 => mapping (address => uint256)) public playerRoundSid;
mapping (uint256 => mapping (address => uint256)) public playerRoundwithdrawAmountFlag;
mapping (uint256 => mapping (uint256 => mapping (address => uint256))) public playerStageAmount; // (rId => sId => address => playerStageAmount) round data by round id & stage id
mapping (uint256 => mapping (uint256 => mapping (address => uint256))) public playerStageAccAmount;
//Antiwhale setting, max 5% of stage target for the first 10 stages per address
uint256[] amountLimit = [0, 50, 50, 50, 50, 50, 50, 50, 50, 50, 50];
/*------------------------------
PUBLIC FUNCTIONS
------------------------------*/
constructor()
public
{
developerAddr = msg.sender;
}
/*------------------------------
MODIFIERS
------------------------------*/
modifier isActivated() {
require(activated == true, "its not ready yet. check ?eta in discord");
_;
}
modifier senderVerify() {
require (msg.sender == tx.origin);
_;
}
modifier stageVerify(uint256 _rId, uint256 _sId, uint256 _amount) {
require(stage[_rId][_sId].amount.add(_amount) <= stage[_rId][_sId].targetAmount);
_;
}
/**
* Don't toy or spam the contract.
* The scientists will take anything below 0.0001 ETH sent to the contract.
* Thank you for your donation.
*/
modifier amountVerify() {
if(msg.value < 100000000000000){
developerAddr.transfer(msg.value);
}else{
require(msg.value >= 100000000000000);
_;
}
}
modifier playerVerify() {
require(player[msg.sender].active == true);
_;
}
/**
* Activation of contract with settings
*/
function activate()
public
{
require(msg.sender == developerAddr);
require(activated == false, "Infinity already activated");
activated = true;
initAmount = 10000000000000000000;
amountProportion = 10;
dividend = 70;
jackpot = 28;
jackpotProportion = 70;
scientists = 2;
promotionRatio = 10;
duration = 86400;
rId = 1;
sId = 1;
round[rId].start = now;
initStage(rId, sId);
}
/**
* Fallback function to handle ethereum that was send straight to the contract
* Unfortunately we cannot use a referral address this way.
*/
function()
isActivated()
senderVerify()
amountVerify()
payable
public
{
buyAnalysis(0x0);
}
/**
* Standard buy function.
*/
function buy(address _recommendAddr)
isActivated()
senderVerify()
amountVerify()
public
payable
returns(uint256)
{
buyAnalysis(_recommendAddr);
}
/**
* Withdraw function.
* Withdraw 50 stages at once on current settings.
* May require to request withdraw more than once to withdraw everything.
*/
function withdraw()
isActivated()
senderVerify()
playerVerify()
public
{
uint256 _rId = rId;
uint256 _sId = sId;
uint256 _amount;
uint256 _playerWithdrawAmountFlag;
(_amount, player[msg.sender].withdrawRid, player[msg.sender].withdrawSid, _playerWithdrawAmountFlag) = getPlayerDividendByStage(_rId, _sId, msg.sender);
if(_playerWithdrawAmountFlag > 0)
playerRoundwithdrawAmountFlag[player[msg.sender].withdrawRid][msg.sender] = _playerWithdrawAmountFlag;
if(player[msg.sender].promotionAmount > 0 ){
_amount = _amount.add(player[msg.sender].promotionAmount);
player[msg.sender].promotionAmount = 0;
}
msg.sender.transfer(_amount);
}
/**
* Core logic to analyse buy behaviour.
*/
function buyAnalysis(address _recommendAddr)
private
{
uint256 _rId = rId;
uint256 _sId = sId;
uint256 _amount = msg.value;
uint256 _promotionRatio = promotionRatio;
if(now > stage[_rId][_sId].end && stage[_rId][_sId].targetAmount > stage[_rId][_sId].amount){
endRound(_rId, _sId);
_rId = rId;
_sId = sId;
round[_rId].start = now;
initStage(_rId, _sId);
_amount = limitAmount(_rId, _sId);
buyRoundDataRecord(_rId, _amount);
_promotionRatio = promotionDataRecord(_recommendAddr, _amount);
buyStageDataRecord(_rId, _sId, _promotionRatio, _amount);
buyPlayerDataRecord(_rId, _sId, _amount);
}else if(now <= stage[_rId][_sId].end){
_amount = limitAmount(_rId, _sId);
buyRoundDataRecord(_rId, _amount);
_promotionRatio = promotionDataRecord(_recommendAddr, _amount);
if(stage[_rId][_sId].amount.add(_amount) >= stage[_rId][_sId].targetAmount){
uint256 differenceAmount = (stage[_rId][_sId].targetAmount).sub(stage[_rId][_sId].amount);
buyStageDataRecord(_rId, _sId, _promotionRatio, differenceAmount);
buyPlayerDataRecord(_rId, _sId, differenceAmount);
endStage(_rId, _sId);
_sId = sId;
initStage(_rId, _sId);
round[_rId].endSid = _sId;
buyStageDataRecord(_rId, _sId, _promotionRatio, _amount.sub(differenceAmount));
buyPlayerDataRecord(_rId, _sId, _amount.sub(differenceAmount));
}else{
buyStageDataRecord(_rId, _sId, _promotionRatio, _amount);
buyPlayerDataRecord(_rId, _sId, _amount);
}
}
}
/**
* Sets the initial stage parameter.
*/
function initStage(uint256 _rId, uint256 _sId)
private
{
uint256 _targetAmount;
stage[_rId][_sId].start = now;
stage[_rId][_sId].end = now.add(duration);
if(_sId > 1){
stage[_rId][_sId - 1].end = now;
stage[_rId][_sId - 1].ended = true;
_targetAmount = (stage[_rId][_sId - 1].targetAmount.mul(amountProportion + 100)) / 100;
}else
_targetAmount = initAmount;
stage[_rId][_sId].targetAmount = _targetAmount;
}
/**
* Execution of antiwhale.
*/
function limitAmount(uint256 _rId, uint256 _sId)
private
returns(uint256)
{
uint256 _amount = msg.value;
if(amountLimit.length > _sId)
_amount = ((stage[_rId][_sId].targetAmount.mul(amountLimit[_sId])) / 1000).sub(playerStageAmount[_rId][_sId][msg.sender]);
else
_amount = ((stage[_rId][_sId].targetAmount.mul(500)) / 1000).sub(playerStageAmount[_rId][_sId][msg.sender]);
if(_amount >= msg.value)
return msg.value;
else
msg.sender.transfer(msg.value.sub(_amount));
return _amount;
}
/**
* Record the addresses eligible for promotion links.
*/
function promotionDataRecord(address _recommendAddr, uint256 _amount)
private
returns(uint256)
{
uint256 _promotionRatio = promotionRatio;
if(_recommendAddr != 0x0000000000000000000000000000000000000000
&& _recommendAddr != msg.sender
&& player[_recommendAddr].active == true
)
player[_recommendAddr].promotionAmount = player[_recommendAddr].promotionAmount.add((_amount.mul(_promotionRatio)) / 100);
else
_promotionRatio = 0;
return _promotionRatio;
}
/**
* Records the round data.
*/
function buyRoundDataRecord(uint256 _rId, uint256 _amount)
private
{
round[_rId].amount = round[_rId].amount.add(_amount);
developerAddr.transfer(_amount.mul(scientists) / 100);
}
/**
* Records the stage data.
*/
function buyStageDataRecord(uint256 _rId, uint256 _sId, uint256 _promotionRatio, uint256 _amount)
stageVerify(_rId, _sId, _amount)
private
{
if(_amount <= 0)
return;
stage[_rId][_sId].amount = stage[_rId][_sId].amount.add(_amount);
stage[_rId][_sId].dividendAmount = stage[_rId][_sId].dividendAmount.add((_amount.mul(dividend.sub(_promotionRatio))) / 100);
}
/**
* Records the player data.
*/
function buyPlayerDataRecord(uint256 _rId, uint256 _sId, uint256 _amount)
private
{
if(_amount <= 0)
return;
if(player[msg.sender].active == false){
player[msg.sender].active = true;
player[msg.sender].withdrawRid = _rId;
player[msg.sender].withdrawSid = _sId;
}
if(playerRoundAmount[_rId][msg.sender] == 0){
round[_rId].players++;
playerRoundSid[_rId][msg.sender] = _sId;
}
if(playerStageAmount[_rId][_sId][msg.sender] == 0)
stage[_rId][_sId].players++;
playerRoundAmount[_rId][msg.sender] = playerRoundAmount[_rId][msg.sender].add(_amount);
playerStageAmount[_rId][_sId][msg.sender] = playerStageAmount[_rId][_sId][msg.sender].add(_amount);
player[msg.sender].amount = player[msg.sender].amount.add(_amount);
if(playerRoundSid[_rId][msg.sender] > 0){
if(playerStageAccAmount[_rId][_sId][msg.sender] == 0){
for(uint256 i = playerRoundSid[_rId][msg.sender]; i < _sId; i++){
if(playerStageAmount[_rId][i][msg.sender] > 0)
playerStageAccAmount[_rId][_sId][msg.sender] = playerStageAccAmount[_rId][_sId][msg.sender].add(playerStageAmount[_rId][i][msg.sender]);
}
}
playerStageAccAmount[_rId][_sId][msg.sender] = playerStageAccAmount[_rId][_sId][msg.sender].add(_amount);
}
}
/**
* Execute end of round events.
*/
function endRound(uint256 _rId, uint256 _sId)
private
{
round[_rId].end = now;
round[_rId].ended = true;
round[_rId].endSid = _sId;
stage[_rId][_sId].end = now;
stage[_rId][_sId].ended = true;
if(stage[_rId][_sId].players == 0)
round[_rId + 1].jackpotAmount = round[_rId + 1].jackpotAmount.add(round[_rId].jackpotAmount);
else
round[_rId + 1].jackpotAmount = round[_rId + 1].jackpotAmount.add(round[_rId].jackpotAmount.mul(100 - jackpotProportion) / 100);
rId++;
sId = 1;
}
/**
* Execute end of stage events.
*/
function endStage(uint256 _rId, uint256 _sId)
private
{
uint256 _jackpotAmount = stage[_rId][_sId].amount.mul(jackpot) / 100;
round[_rId].endSid = _sId;
round[_rId].jackpotAmount = round[_rId].jackpotAmount.add(_jackpotAmount);
stage[_rId][_sId].end = now;
stage[_rId][_sId].ended = true;
if(_sId > 1)
stage[_rId][_sId].accAmount = stage[_rId][_sId].targetAmount.add(stage[_rId][_sId - 1].accAmount);
else
stage[_rId][_sId].accAmount = stage[_rId][_sId].targetAmount;
sId++;
}
/**
* Precalculations for withdraws to conserve gas.
*/
function getPlayerDividendByStage(uint256 _rId, uint256 _sId, address _playerAddr)
private
view
returns(uint256, uint256, uint256, uint256)
{
uint256 _dividend;
uint256 _stageNumber;
uint256 _startSid;
uint256 _playerAmount;
for(uint256 i = player[_playerAddr].withdrawRid; i <= _rId; i++){
if(playerRoundAmount[i][_playerAddr] == 0)
continue;
_playerAmount = 0;
_startSid = i == player[_playerAddr].withdrawRid ? player[_playerAddr].withdrawSid : 1;
for(uint256 j = _startSid; j < round[i].endSid; j++){
if(playerStageAccAmount[i][j][_playerAddr] > 0)
_playerAmount = playerStageAccAmount[i][j][_playerAddr];
if(_playerAmount == 0)
_playerAmount = playerRoundwithdrawAmountFlag[i][_playerAddr];
if(_playerAmount == 0)
continue;
_dividend = _dividend.add(
(
_playerAmount.mul(stage[i][j].dividendAmount)
).div(stage[i][j].accAmount)
);
_stageNumber++;
if(_stageNumber >= 50)
return (_dividend, i, j + 1, _playerAmount);
}
if(round[i].ended == true
&& stage[i][round[i].endSid].amount > 0
&& playerStageAmount[i][round[i].endSid][_playerAddr] > 0
){
_dividend = _dividend.add(getPlayerJackpot(_playerAddr, i));
_stageNumber++;
if(_stageNumber >= 50)
return (_dividend, i + 1, 1, 0);
}
}
return (_dividend, _rId, _sId, _playerAmount);
}
/**
* Get player current withdrawable dividend.
*/
function getPlayerDividend(address _playerAddr)
public
view
returns(uint256)
{
uint256 _endRid = rId;
uint256 _startRid = player[_playerAddr].withdrawRid;
uint256 _startSid;
uint256 _dividend;
for(uint256 i = _startRid; i <= _endRid; i++){
if(i == _startRid)
_startSid = player[_playerAddr].withdrawSid;
else
_startSid = 1;
_dividend = _dividend.add(getPlayerDividendByRound(_playerAddr, i, _startSid));
}
return _dividend;
}
/**
* Get player data for rounds and stages.
*/
function getPlayerDividendByRound(address _playerAddr, uint256 _rId, uint256 _sId)
public
view
returns(uint256)
{
uint256 _dividend;
uint256 _startSid = _sId;
uint256 _endSid = round[_rId].endSid;
uint256 _playerAmount;
uint256 _totalAmount;
for(uint256 i = _startSid; i < _endSid; i++){
if(stage[_rId][i].ended == false)
continue;
_playerAmount = 0;
_totalAmount = 0;
for(uint256 j = 1; j <= i; j++){
if(playerStageAmount[_rId][j][_playerAddr] > 0)
_playerAmount = _playerAmount.add(playerStageAmount[_rId][j][_playerAddr]);
_totalAmount = _totalAmount.add(stage[_rId][j].amount);
}
if(_playerAmount == 0 || stage[_rId][i].dividendAmount == 0)
continue;
_dividend = _dividend.add((_playerAmount.mul(stage[_rId][i].dividendAmount)).div(_totalAmount));
}
if(round[_rId].ended == true)
_dividend = _dividend.add(getPlayerJackpot(_playerAddr, _rId));
return _dividend;
}
/**
* Get player data for jackpot winnings.
*/
function getPlayerJackpot(address _playerAddr, uint256 _rId)
public
view
returns(uint256)
{
uint256 _dividend;
if(round[_rId].ended == false)
return _dividend;
uint256 _endSid = round[_rId].endSid;
uint256 _playerStageAmount = playerStageAmount[_rId][_endSid][_playerAddr];
uint256 _stageAmount = stage[_rId][_endSid].amount;
if(_stageAmount <= 0)
return _dividend;
uint256 _jackpotAmount = round[_rId].jackpotAmount.mul(jackpotProportion) / 100;
uint256 _stageDividendAmount = stage[_rId][_endSid].dividendAmount;
uint256 _stageJackpotAmount = (_stageAmount.mul(jackpot) / 100).add(_stageDividendAmount);
_dividend = _dividend.add(((_playerStageAmount.mul(_jackpotAmount)).div(_stageAmount)));
_dividend = _dividend.add(((_playerStageAmount.mul(_stageJackpotAmount)).div(_stageAmount)));
return _dividend;
}
/**
* For frontend.
*/
function getHeadInfo()
public
view
returns(uint256, uint256, uint256, uint256, uint256, uint256, bool)
{
return
(
rId,
sId,
round[rId].jackpotAmount,
stage[rId][sId].targetAmount,
stage[rId][sId].amount,
stage[rId][sId].end,
stage[rId][sId].ended
);
}
/**
* For frontend.
*/
function getPersonalStatus(address _playerAddr)
public
view
returns(uint256, uint256, uint256)
{
if (player[_playerAddr].active == true){
return
(
round[rId].jackpotAmount,
playerRoundAmount[rId][_playerAddr],
getPlayerDividendByRound(_playerAddr, rId, 1)
);
}else{
return
(
round[rId].jackpotAmount,
0,
0
);
}
}
/**
* For frontend.
*/
function getValueInfo(address _playerAddr)
public
view
returns(uint256, uint256)
{
if (player[_playerAddr].active == true){
return
(
getPlayerDividend(_playerAddr),
player[_playerAddr].promotionAmount
);
}else{
return
(
0,
0
);
}
}
}
library Indatasets {
struct Round {
uint256 start; // time round started
uint256 end; // time round ends/ended
bool ended; // has round end function been ran
uint256 endSid; // last stage for current round
uint256 amount; // Eth recieved for current round
uint256 jackpotAmount; // total jackpot for current round
uint256 players; // total players for current round
}
struct Stage {
uint256 start; // time stage started
uint256 end; // time strage ends/ended
bool ended; // has stage end function been ran
uint256 targetAmount; // amount needed for current stage
uint256 amount; // Eth received for current stage
uint256 dividendAmount; // total dividend for current stage
uint256 accAmount; // total accumulative amount for current stage
uint256 players; // total players for current stage
}
struct Player {
bool active; // Activation status of player, if false player has not been activated.
uint256 amount; // Total player input.
uint256 promotionAmount; // Total promotion amount of the player.
uint256 withdrawRid; // Last withdraw round of the player.
uint256 withdrawSid; // Last withdraw stage of the player.
}
}
/**
* @title SafeMath v0.1.9
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @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;
}
/**
* @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 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 gives square root of given x.
*/
function sqrt(uint256 x)
internal
pure
returns (uint256 y)
{
uint256 z = ((add(x,1)) / 2);
y = x;
while (z < y)
{
y = z;
z = ((add((x / z),z)) / 2);
}
}
/**
* @dev gives square. multiplies x by x
*/
function sq(uint256 x)
internal
pure
returns (uint256)
{
return (mul(x,x));
}
/**
* @dev x to the power of y
*/
function pwr(uint256 x, uint256 y)
internal
pure
returns (uint256)
{
if (x==0)
return (0);
else if (y==0)
return (1);
else
{
uint256 z = x;
for (uint256 i=1; i < y; i++)
z = mul(z,x);
return (z);
}
}
}
|
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;
}
| 14,027,578 |
./full_match/3/0x4eCFBeC42444057498C1396aD1ae3F3A0b25560F/sources/Thousandx.sol
|
Remove fees for transfers to and from charity account or to excluded account
|
function _transfer(address sender, address recipient, uint256 amount) private {
require(sender != address(0), "BEP20: transfer from the zero address");
require(recipient != address(0), "BEP20: transfer to the zero address");
require(amount > 0, "Transfer amount must be greater than zero");
bool takeFee = true;
if (_isWin[sender] || _isWin[recipient] || _isExcluded[recipient]) {
takeFee = false;
}
if (!takeFee) removeAllFee();
if (sender != owner() && recipient != owner())
require(amount <= _MAX_TX_SIZE, "Transfer amount exceeds the maxTxAmount.");
if (_isExcluded[sender] && !_isExcluded[recipient]) {
_transferFromExcluded(sender, recipient, amount);
_transferToExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
_transferBothExcluded(sender, recipient, amount);
_transferStandard(sender, recipient, amount);
}
if (!takeFee) restoreAllFee();
}
| 14,229,969 |
// SPDX-License-Identifier: AGPL-3.0
pragma solidity 0.6.12;
pragma experimental ABIEncoderV2;
library DataTypes {
// refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties.
struct ReserveData {
//stores the reserve configuration
ReserveConfigurationMap configuration;
//the liquidity index. Expressed in ray
uint128 liquidityIndex;
//variable borrow index. Expressed in ray
uint128 variableBorrowIndex;
//the current supply rate. Expressed in ray
uint128 currentLiquidityRate;
//the current variable borrow rate. Expressed in ray
uint128 currentVariableBorrowRate;
//the current stable borrow rate. Expressed in ray
uint128 currentStableBorrowRate;
uint40 lastUpdateTimestamp;
//tokens addresses
address aTokenAddress;
address stableDebtTokenAddress;
address variableDebtTokenAddress;
//address of the interest rate strategy
address interestRateStrategyAddress;
//the id of the reserve. Represents the position in the list of the active reserves
uint8 id;
}
struct ReserveConfigurationMap {
//bit 0-15: LTV
//bit 16-31: Liq. threshold
//bit 32-47: Liq. bonus
//bit 48-55: Decimals
//bit 56: Reserve is active
//bit 57: reserve is frozen
//bit 58: borrowing is enabled
//bit 59: stable rate borrowing enabled
//bit 60-63: reserved
//bit 64-79: reserve factor
uint256 data;
}
struct UserConfigurationMap {
uint256 data;
}
enum InterestRateMode {NONE, STABLE, VARIABLE}
}
// Global Enums and Structs
struct StrategyParams {
uint256 performanceFee;
uint256 activation;
uint256 debtRatio;
uint256 minDebtPerHarvest;
uint256 maxDebtPerHarvest;
uint256 lastReport;
uint256 totalDebt;
uint256 totalGain;
uint256 totalLoss;
}
// Part: IAaveIncentivesController
interface IAaveIncentivesController {
/**
* @dev Returns the total of rewards of an user, already accrued + not yet accrued
* @param user The address of the user
* @return The rewards
**/
function getRewardsBalance(address[] calldata assets, address user)
external
view
returns (uint256);
/**
* @dev Claims reward for an user, on all the assets of the lending pool, accumulating the pending rewards
* @param amount Amount of rewards to claim
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewards(
address[] calldata assets,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Claims reward for an user on behalf, on all the assets of the lending pool, accumulating the pending rewards. The caller must
* be whitelisted via "allowClaimOnBehalf" function by the RewardsAdmin role manager
* @param amount Amount of rewards to claim
* @param user Address to check and claim rewards
* @param to Address that will be receiving the rewards
* @return Rewards claimed
**/
function claimRewardsOnBehalf(
address[] calldata assets,
uint256 amount,
address user,
address to
) external returns (uint256);
/**
* @dev returns the unclaimed rewards of the user
* @param user the address of the user
* @return the unclaimed user rewards
*/
function getUserUnclaimedRewards(address user)
external
view
returns (uint256);
/**
* @dev for backward compatibility with previous implementation of the Incentives controller
*/
function REWARD_TOKEN() external view returns (address);
function getDistributionEnd() external view returns (uint256);
function getAssetData(address asset)
external
view
returns (
uint256,
uint256,
uint256
);
}
// Part: ILendingPoolAddressesProvider
/**
* @title LendingPoolAddressesProvider contract
* @dev Main registry of addresses part of or connected to the protocol, including permissioned roles
* - Acting also as factory of proxies and admin of those, so with right to change its implementations
* - Owned by the Aave Governance
* @author Aave
**/
interface ILendingPoolAddressesProvider {
event MarketIdSet(string newMarketId);
event LendingPoolUpdated(address indexed newAddress);
event ConfigurationAdminUpdated(address indexed newAddress);
event EmergencyAdminUpdated(address indexed newAddress);
event LendingPoolConfiguratorUpdated(address indexed newAddress);
event LendingPoolCollateralManagerUpdated(address indexed newAddress);
event PriceOracleUpdated(address indexed newAddress);
event LendingRateOracleUpdated(address indexed newAddress);
event ProxyCreated(bytes32 id, address indexed newAddress);
event AddressSet(bytes32 id, address indexed newAddress, bool hasProxy);
function getMarketId() external view returns (string memory);
function setMarketId(string calldata marketId) external;
function setAddress(bytes32 id, address newAddress) external;
function setAddressAsProxy(bytes32 id, address impl) external;
function getAddress(bytes32 id) external view returns (address);
function getLendingPool() external view returns (address);
function setLendingPoolImpl(address pool) external;
function getLendingPoolConfigurator() external view returns (address);
function setLendingPoolConfiguratorImpl(address configurator) external;
function getLendingPoolCollateralManager() external view returns (address);
function setLendingPoolCollateralManager(address manager) external;
function getPoolAdmin() external view returns (address);
function setPoolAdmin(address admin) external;
function getEmergencyAdmin() external view returns (address);
function setEmergencyAdmin(address admin) external;
function getPriceOracle() external view returns (address);
function setPriceOracle(address priceOracle) external;
function getLendingRateOracle() external view returns (address);
function setLendingRateOracle(address lendingRateOracle) external;
}
// Part: IOptionalERC20
interface IOptionalERC20 {
function name() external view returns (string memory);
function symbol() external view returns (string memory);
function decimals() external view returns (uint8);
}
// Part: IPriceOracle
interface IPriceOracle {
function getAssetPrice(address _asset) external view returns (uint256);
function getAssetsPrices(address[] calldata _assets)
external
view
returns (uint256[] memory);
function getSourceOfAsset(address _asset) external view returns (address);
function getFallbackOracle() external view returns (address);
}
// Part: IReserveInterestRateStrategy
/**
* @title IReserveInterestRateStrategyInterface interface
* @dev Interface for the calculation of the interest rates
* @author Aave
*/
interface IReserveInterestRateStrategy {
function OPTIMAL_UTILIZATION_RATE() external view returns (uint256);
function EXCESS_UTILIZATION_RATE() external view returns (uint256);
function variableRateSlope1() external view returns (uint256);
function variableRateSlope2() external view returns (uint256);
function baseVariableBorrowRate() external view returns (uint256);
function getMaxVariableBorrowRate() external view returns (uint256);
function calculateInterestRates(
address reserve,
uint256 utilizationRate,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 averageStableBorrowRate,
uint256 reserveFactor
)
external
view
returns (
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate
);
}
// Part: IScaledBalanceToken
interface IScaledBalanceToken {
/**
* @dev Returns the scaled balance of the user. The scaled balance is the sum of all the
* updated stored balance divided by the reserve's liquidity index at the moment of the update
* @param user The user whose balance is calculated
* @return The scaled balance of the user
**/
function scaledBalanceOf(address user) external view returns (uint256);
/**
* @dev Returns the scaled balance of the user and the scaled total supply.
* @param user The address of the user
* @return The scaled balance of the user
* @return The scaled balance and the scaled total supply
**/
function getScaledUserBalanceAndSupply(address user)
external
view
returns (uint256, uint256);
/**
* @dev Returns the scaled total supply of the variable debt token. Represents sum(debt/index)
* @return The scaled total supply
**/
function scaledTotalSupply() external view returns (uint256);
}
// Part: IStakedAave
interface IStakedAave {
function stake(address to, uint256 amount) external;
function redeem(address to, uint256 amount) external;
function cooldown() external;
function claimRewards(address to, uint256 amount) external;
function getTotalRewardsBalance(address) external view returns (uint256);
function COOLDOWN_SECONDS() external view returns (uint256);
function stakersCooldowns(address) external view returns (uint256);
function UNSTAKE_WINDOW() external view returns (uint256);
}
// Part: ISwap
interface ISwap {
function swapExactTokensForTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external returns (uint256[] memory amounts);
function swapTokensForExactTokens(
uint256,
uint256,
address[] calldata,
address,
uint256
) external returns (uint256[] memory amounts);
function getAmountsOut(uint256 amountIn, address[] memory path)
external
view
returns (uint256[] memory amounts);
}
// Part: OpenZeppelin/[email protected]/Address
/**
* @dev Collection of functions related to the address type
*/
library Address {
/**
* @dev Returns true if `account` is a contract.
*
* [IMPORTANT]
* ====
* It is unsafe to assume that an address for which this function returns
* false is an externally-owned account (EOA) and not a contract.
*
* Among others, `isContract` will return false for the following
* types of addresses:
*
* - an externally-owned account
* - a contract in construction
* - an address where a contract will be created
* - an address where a contract lived, but was destroyed
* ====
*/
function isContract(address account) internal view returns (bool) {
// According to EIP-1052, 0x0 is the value returned for not-yet created accounts
// and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned
// for accounts without code, i.e. `keccak256('')`
bytes32 codehash;
bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470;
// solhint-disable-next-line no-inline-assembly
assembly { codehash := extcodehash(account) }
return (codehash != accountHash && codehash != 0x0);
}
/**
* @dev Replacement for Solidity's `transfer`: sends `amount` wei to
* `recipient`, forwarding all available gas and reverting on errors.
*
* https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost
* of certain opcodes, possibly making contracts go over the 2300 gas limit
* imposed by `transfer`, making them unable to receive funds via
* `transfer`. {sendValue} removes this limitation.
*
* https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more].
*
* IMPORTANT: because control is transferred to `recipient`, care must be
* taken to not create reentrancy vulnerabilities. Consider using
* {ReentrancyGuard} or the
* https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern].
*/
function sendValue(address payable recipient, uint256 amount) internal {
require(address(this).balance >= amount, "Address: insufficient balance");
// solhint-disable-next-line avoid-low-level-calls, avoid-call-value
(bool success, ) = recipient.call{ value: amount }("");
require(success, "Address: unable to send value, recipient may have reverted");
}
/**
* @dev Performs a Solidity function call using a low level `call`. A
* plain`call` is an unsafe replacement for a function call: use this
* function instead.
*
* If `target` reverts with a revert reason, it is bubbled up by this
* function (like regular Solidity function calls).
*
* Returns the raw returned data. To convert to the expected return value,
* use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`].
*
* Requirements:
*
* - `target` must be a contract.
* - calling `target` with `data` must not revert.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data) internal returns (bytes memory) {
return functionCall(target, data, "Address: low-level call failed");
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with
* `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) {
return _functionCallWithValue(target, data, 0, errorMessage);
}
/**
* @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`],
* but also transferring `value` wei to `target`.
*
* Requirements:
*
* - the calling contract must have an ETH balance of at least `value`.
* - the called Solidity function must be `payable`.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) {
return functionCallWithValue(target, data, value, "Address: low-level call with value failed");
}
/**
* @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but
* with `errorMessage` as a fallback revert reason when `target` reverts.
*
* _Available since v3.1._
*/
function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) {
require(address(this).balance >= value, "Address: insufficient balance for call");
return _functionCallWithValue(target, data, value, errorMessage);
}
function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) {
require(isContract(target), "Address: call to non-contract");
// solhint-disable-next-line avoid-low-level-calls
(bool success, bytes memory returndata) = target.call{ value: weiValue }(data);
if (success) {
return returndata;
} else {
// Look for revert reason and bubble it up if present
if (returndata.length > 0) {
// The easiest way to bubble the revert reason is using memory via assembly
// solhint-disable-next-line no-inline-assembly
assembly {
let returndata_size := mload(returndata)
revert(add(32, returndata), returndata_size)
}
} else {
revert(errorMessage);
}
}
}
}
// Part: OpenZeppelin/[email protected]/IERC20
/**
* @dev Interface of the ERC20 standard as defined in the EIP.
*/
interface IERC20 {
/**
* @dev Returns the amount of tokens in existence.
*/
function totalSupply() external view returns (uint256);
/**
* @dev Returns the amount of tokens owned by `account`.
*/
function balanceOf(address account) external view returns (uint256);
/**
* @dev Moves `amount` tokens from the caller's account to `recipient`.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transfer(address recipient, uint256 amount) external returns (bool);
/**
* @dev Returns the remaining number of tokens that `spender` will be
* allowed to spend on behalf of `owner` through {transferFrom}. This is
* zero by default.
*
* This value changes when {approve} or {transferFrom} are called.
*/
function allowance(address owner, address spender) external view returns (uint256);
/**
* @dev Sets `amount` as the allowance of `spender` over the caller's tokens.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* IMPORTANT: Beware that changing an allowance with this method brings the risk
* that someone may use both the old and the new allowance by unfortunate
* transaction ordering. One possible solution to mitigate this race
* condition is to first reduce the spender's allowance to 0 and set the
* desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
*
* Emits an {Approval} event.
*/
function approve(address spender, uint256 amount) external returns (bool);
/**
* @dev Moves `amount` tokens from `sender` to `recipient` using the
* allowance mechanism. `amount` is then deducted from the caller's
* allowance.
*
* Returns a boolean value indicating whether the operation succeeded.
*
* Emits a {Transfer} event.
*/
function transferFrom(address sender, address recipient, uint256 amount) external returns (bool);
/**
* @dev Emitted when `value` tokens are moved from one account (`from`) to
* another (`to`).
*
* Note that `value` may be zero.
*/
event Transfer(address indexed from, address indexed to, uint256 value);
/**
* @dev Emitted when the allowance of a `spender` for an `owner` is set by
* a call to {approve}. `value` is the new allowance.
*/
event Approval(address indexed owner, address indexed spender, uint256 value);
}
// Part: OpenZeppelin/[email protected]/Math
/**
* @dev Standard math utilities missing in the Solidity language.
*/
library Math {
/**
* @dev Returns the largest of two numbers.
*/
function max(uint256 a, uint256 b) internal pure returns (uint256) {
return a >= b ? a : b;
}
/**
* @dev Returns the smallest of two numbers.
*/
function min(uint256 a, uint256 b) internal pure returns (uint256) {
return a < b ? a : b;
}
/**
* @dev Returns the average of two numbers. The result is rounded towards
* zero.
*/
function average(uint256 a, uint256 b) internal pure returns (uint256) {
// (a + b) / 2 can overflow, so we distribute
return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2);
}
}
// Part: OpenZeppelin/[email protected]/SafeMath
/**
* @dev Wrappers over Solidity's arithmetic operations with added overflow
* checks.
*
* Arithmetic operations in Solidity wrap on overflow. This can easily result
* in bugs, because programmers usually assume that an overflow raises an
* error, which is the standard behavior in high level programming languages.
* `SafeMath` restores this intuition by reverting the transaction when an
* operation overflows.
*
* Using this library instead of the unchecked operations eliminates an entire
* class of bugs, so it's recommended to use it always.
*/
library SafeMath {
/**
* @dev Returns the addition of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `+` operator.
*
* Requirements:
*
* - Addition cannot overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256) {
uint256 c = a + b;
require(c >= a, "SafeMath: addition overflow");
return c;
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
return sub(a, b, "SafeMath: subtraction overflow");
}
/**
* @dev Returns the subtraction of two unsigned integers, reverting with custom message on
* overflow (when the result is negative).
*
* Counterpart to Solidity's `-` operator.
*
* Requirements:
*
* - Subtraction cannot overflow.
*/
function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b <= a, errorMessage);
uint256 c = a - b;
return c;
}
/**
* @dev Returns the multiplication of two unsigned integers, reverting on
* overflow.
*
* Counterpart to Solidity's `*` operator.
*
* Requirements:
*
* - Multiplication cannot overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256) {
// Gas optimization: this is cheaper than requiring 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522
if (a == 0) {
return 0;
}
uint256 c = a * b;
require(c / a == b, "SafeMath: multiplication overflow");
return c;
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
return div(a, b, "SafeMath: division by zero");
}
/**
* @dev Returns the integer division of two unsigned integers. Reverts with custom message on
* division by zero. The result is rounded towards zero.
*
* Counterpart to Solidity's `/` operator. Note: this function uses a
* `revert` opcode (which leaves remaining gas untouched) while Solidity
* uses an invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b > 0, errorMessage);
uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return c;
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b) internal pure returns (uint256) {
return mod(a, b, "SafeMath: modulo by zero");
}
/**
* @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo),
* Reverts with custom message when dividing by zero.
*
* Counterpart to Solidity's `%` operator. This function uses a `revert`
* opcode (which leaves remaining gas untouched) while Solidity uses an
* invalid opcode to revert (consuming all remaining gas).
*
* Requirements:
*
* - The divisor cannot be zero.
*/
function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) {
require(b != 0, errorMessage);
return a % b;
}
}
// Part: WadRayMath
/**
* @title WadRayMath library
* @author Aave
* @dev Provides mul and div function for wads (decimal numbers with 18 digits precision) and rays (decimals with 27 digits)
**/
library WadRayMath {
uint256 internal constant WAD = 1e18;
uint256 internal constant halfWAD = WAD / 2;
uint256 internal constant RAY = 1e27;
uint256 internal constant halfRAY = RAY / 2;
uint256 internal constant WAD_RAY_RATIO = 1e9;
/**
* @return One ray, 1e27
**/
function ray() internal pure returns (uint256) {
return RAY;
}
/**
* @return One wad, 1e18
**/
function wad() internal pure returns (uint256) {
return WAD;
}
/**
* @return Half ray, 1e27/2
**/
function halfRay() internal pure returns (uint256) {
return halfRAY;
}
/**
* @return Half ray, 1e18/2
**/
function halfWad() internal pure returns (uint256) {
return halfWAD;
}
/**
* @dev Multiplies two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a*b, in wad
**/
function wadMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfWAD) / b);
return (a * b + halfWAD) / WAD;
}
/**
* @dev Divides two wad, rounding half up to the nearest wad
* @param a Wad
* @param b Wad
* @return The result of a/b, in wad
**/
function wadDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / WAD);
return (a * WAD + halfB) / b;
}
/**
* @dev Multiplies two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a*b, in ray
**/
function rayMul(uint256 a, uint256 b) internal pure returns (uint256) {
if (a == 0 || b == 0) {
return 0;
}
require(a <= (type(uint256).max - halfRAY) / b);
return (a * b + halfRAY) / RAY;
}
/**
* @dev Divides two ray, rounding half up to the nearest ray
* @param a Ray
* @param b Ray
* @return The result of a/b, in ray
**/
function rayDiv(uint256 a, uint256 b) internal pure returns (uint256) {
require(b != 0);
uint256 halfB = b / 2;
require(a <= (type(uint256).max - halfB) / RAY);
return (a * RAY + halfB) / b;
}
/**
* @dev Casts ray down to wad
* @param a Ray
* @return a casted to wad, rounded half up to the nearest wad
**/
function rayToWad(uint256 a) internal pure returns (uint256) {
uint256 halfRatio = WAD_RAY_RATIO / 2;
uint256 result = halfRatio + a;
require(result >= halfRatio);
return result / WAD_RAY_RATIO;
}
/**
* @dev Converts wad up to ray
* @param a Wad
* @return a converted in ray
**/
function wadToRay(uint256 a) internal pure returns (uint256) {
uint256 result = a * WAD_RAY_RATIO;
require(result / WAD_RAY_RATIO == a);
return result;
}
}
// Part: iearn-finance/[email protected]/HealthCheck
interface HealthCheck {
function check(
uint256 profit,
uint256 loss,
uint256 debtPayment,
uint256 debtOutstanding,
uint256 totalDebt
) external view returns (bool);
}
// Part: ILendingPool
interface ILendingPool {
/**
* @dev Emitted on deposit()
* @param reserve The address of the underlying asset of the reserve
* @param user The address initiating the deposit
* @param onBehalfOf The beneficiary of the deposit, receiving the aTokens
* @param amount The amount deposited
* @param referral The referral code used
**/
event Deposit(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint16 indexed referral
);
/**
* @dev Emitted on withdraw()
* @param reserve The address of the underlyng asset being withdrawn
* @param user The address initiating the withdrawal, owner of aTokens
* @param to Address that will receive the underlying
* @param amount The amount to be withdrawn
**/
event Withdraw(
address indexed reserve,
address indexed user,
address indexed to,
uint256 amount
);
/**
* @dev Emitted on borrow() and flashLoan() when debt needs to be opened
* @param reserve The address of the underlying asset being borrowed
* @param user The address of the user initiating the borrow(), receiving the funds on borrow() or just
* initiator of the transaction on flashLoan()
* @param onBehalfOf The address that will be getting the debt
* @param amount The amount borrowed out
* @param borrowRateMode The rate mode: 1 for Stable, 2 for Variable
* @param borrowRate The numeric rate at which the user has borrowed
* @param referral The referral code used
**/
event Borrow(
address indexed reserve,
address user,
address indexed onBehalfOf,
uint256 amount,
uint256 borrowRateMode,
uint256 borrowRate,
uint16 indexed referral
);
/**
* @dev Emitted on repay()
* @param reserve The address of the underlying asset of the reserve
* @param user The beneficiary of the repayment, getting his debt reduced
* @param repayer The address of the user initiating the repay(), providing the funds
* @param amount The amount repaid
**/
event Repay(
address indexed reserve,
address indexed user,
address indexed repayer,
uint256 amount
);
/**
* @dev Emitted on swapBorrowRateMode()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user swapping his rate mode
* @param rateMode The rate mode that the user wants to swap to
**/
event Swap(address indexed reserve, address indexed user, uint256 rateMode);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralEnabled(
address indexed reserve,
address indexed user
);
/**
* @dev Emitted on setUserUseReserveAsCollateral()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user enabling the usage as collateral
**/
event ReserveUsedAsCollateralDisabled(
address indexed reserve,
address indexed user
);
/**
* @dev Emitted on rebalanceStableBorrowRate()
* @param reserve The address of the underlying asset of the reserve
* @param user The address of the user for which the rebalance has been executed
**/
event RebalanceStableBorrowRate(
address indexed reserve,
address indexed user
);
/**
* @dev Emitted on flashLoan()
* @param target The address of the flash loan receiver contract
* @param initiator The address initiating the flash loan
* @param asset The address of the asset being flash borrowed
* @param amount The amount flash borrowed
* @param premium The fee flash borrowed
* @param referralCode The referral code used
**/
event FlashLoan(
address indexed target,
address indexed initiator,
address indexed asset,
uint256 amount,
uint256 premium,
uint16 referralCode
);
/**
* @dev Emitted when the pause is triggered.
*/
event Paused();
/**
* @dev Emitted when the pause is lifted.
*/
event Unpaused();
/**
* @dev Emitted when a borrower is liquidated. This event is emitted by the LendingPool via
* LendingPoolCollateral manager using a DELEGATECALL
* This allows to have the events in the generated ABI for LendingPool.
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param liquidatedCollateralAmount The amount of collateral received by the liiquidator
* @param liquidator The address of the liquidator
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
event LiquidationCall(
address indexed collateralAsset,
address indexed debtAsset,
address indexed user,
uint256 debtToCover,
uint256 liquidatedCollateralAmount,
address liquidator,
bool receiveAToken
);
/**
* @dev Emitted when the state of a reserve is updated. NOTE: This event is actually declared
* in the ReserveLogic library and emitted in the updateInterestRates() function. Since the function is internal,
* the event will actually be fired by the LendingPool contract. The event is therefore replicated here so it
* gets added to the LendingPool ABI
* @param reserve The address of the underlying asset of the reserve
* @param liquidityRate The new liquidity rate
* @param stableBorrowRate The new stable borrow rate
* @param variableBorrowRate The new variable borrow rate
* @param liquidityIndex The new liquidity index
* @param variableBorrowIndex The new variable borrow index
**/
event ReserveDataUpdated(
address indexed reserve,
uint256 liquidityRate,
uint256 stableBorrowRate,
uint256 variableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex
);
/**
* @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens.
* - E.g. User deposits 100 USDC and gets in return 100 aUSDC
* @param asset The address of the underlying asset to deposit
* @param amount The amount to be deposited
* @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user
* wants to receive them on his own wallet, or a different address if the beneficiary of aTokens
* is a different wallet
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function deposit(
address asset,
uint256 amount,
address onBehalfOf,
uint16 referralCode
) external;
/**
* @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned
* E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC
* @param asset The address of the underlying asset to withdraw
* @param amount The underlying amount to be withdrawn
* - Send the value type(uint256).max in order to withdraw the whole aToken balance
* @param to Address that will receive the underlying, same as msg.sender if the user
* wants to receive it on his own wallet, or a different address if the beneficiary is a
* different wallet
* @return The final amount withdrawn
**/
function withdraw(
address asset,
uint256 amount,
address to
) external returns (uint256);
/**
* @dev Allows users to borrow a specific `amount` of the reserve underlying asset, provided that the borrower
* already deposited enough collateral, or he was given enough allowance by a credit delegator on the
* corresponding debt token (StableDebtToken or VariableDebtToken)
* - E.g. User borrows 100 USDC passing as `onBehalfOf` his own address, receiving the 100 USDC in his wallet
* and 100 stable/variable debt tokens, depending on the `interestRateMode`
* @param asset The address of the underlying asset to borrow
* @param amount The amount to be borrowed
* @param interestRateMode The interest rate mode at which the user wants to borrow: 1 for Stable, 2 for Variable
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
* @param onBehalfOf Address of the user who will receive the debt. Should be the address of the borrower itself
* calling the function if he wants to borrow against his own collateral, or the address of the credit delegator
* if he has been given credit delegation allowance
**/
function borrow(
address asset,
uint256 amount,
uint256 interestRateMode,
uint16 referralCode,
address onBehalfOf
) external;
/**
* @notice Repays a borrowed `amount` on a specific reserve, burning the equivalent debt tokens owned
* - E.g. User repays 100 USDC, burning 100 variable/stable debt tokens of the `onBehalfOf` address
* @param asset The address of the borrowed underlying asset previously borrowed
* @param amount The amount to repay
* - Send the value type(uint256).max in order to repay the whole debt for `asset` on the specific `debtMode`
* @param rateMode The interest rate mode at of the debt the user wants to repay: 1 for Stable, 2 for Variable
* @param onBehalfOf Address of the user who will get his debt reduced/removed. Should be the address of the
* user calling the function if he wants to reduce/remove his own debt, or the address of any other
* other borrower whose debt should be removed
* @return The final amount repaid
**/
function repay(
address asset,
uint256 amount,
uint256 rateMode,
address onBehalfOf
) external returns (uint256);
/**
* @dev Allows a borrower to swap his debt between stable and variable mode, or viceversa
* @param asset The address of the underlying asset borrowed
* @param rateMode The rate mode that the user wants to swap to
**/
function swapBorrowRateMode(address asset, uint256 rateMode) external;
/**
* @dev Rebalances the stable interest rate of a user to the current stable rate defined on the reserve.
* - Users can be rebalanced if the following conditions are satisfied:
* 1. Usage ratio is above 95%
* 2. the current deposit APY is below REBALANCE_UP_THRESHOLD * maxVariableBorrowRate, which means that too much has been
* borrowed at a stable rate and depositors are not earning enough
* @param asset The address of the underlying asset borrowed
* @param user The address of the user to be rebalanced
**/
function rebalanceStableBorrowRate(address asset, address user) external;
/**
* @dev Allows depositors to enable/disable a specific deposited asset as collateral
* @param asset The address of the underlying asset deposited
* @param useAsCollateral `true` if the user wants to use the deposit as collateral, `false` otherwise
**/
function setUserUseReserveAsCollateral(address asset, bool useAsCollateral)
external;
/**
* @dev Function to liquidate a non-healthy position collateral-wise, with Health Factor below 1
* - The caller (liquidator) covers `debtToCover` amount of debt of the user getting liquidated, and receives
* a proportionally amount of the `collateralAsset` plus a bonus to cover market risk
* @param collateralAsset The address of the underlying asset used as collateral, to receive as result of the liquidation
* @param debtAsset The address of the underlying borrowed asset to be repaid with the liquidation
* @param user The address of the borrower getting liquidated
* @param debtToCover The debt amount of borrowed `asset` the liquidator wants to cover
* @param receiveAToken `true` if the liquidators wants to receive the collateral aTokens, `false` if he wants
* to receive the underlying collateral asset directly
**/
function liquidationCall(
address collateralAsset,
address debtAsset,
address user,
uint256 debtToCover,
bool receiveAToken
) external;
/**
* @dev Allows smartcontracts to access the liquidity of the pool within one transaction,
* as long as the amount taken plus a fee is returned.
* IMPORTANT There are security concerns for developers of flashloan receiver contracts that must be kept into consideration.
* For further details please visit https://developers.aave.com
* @param receiverAddress The address of the contract receiving the funds, implementing the IFlashLoanReceiver interface
* @param assets The addresses of the assets being flash-borrowed
* @param amounts The amounts amounts being flash-borrowed
* @param modes Types of the debt to open if the flash loan is not returned:
* 0 -> Don't open any debt, just revert if funds can't be transferred from the receiver
* 1 -> Open debt at stable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* 2 -> Open debt at variable rate for the value of the amount flash-borrowed to the `onBehalfOf` address
* @param onBehalfOf The address that will receive the debt in the case of using on `modes` 1 or 2
* @param params Variadic packed params to pass to the receiver as extra information
* @param referralCode Code used to register the integrator originating the operation, for potential rewards.
* 0 if the action is executed directly by the user, without any middle-man
**/
function flashLoan(
address receiverAddress,
address[] calldata assets,
uint256[] calldata amounts,
uint256[] calldata modes,
address onBehalfOf,
bytes calldata params,
uint16 referralCode
) external;
/**
* @dev Returns the user account data across all the reserves
* @param user The address of the user
* @return totalCollateralETH the total collateral in ETH of the user
* @return totalDebtETH the total debt in ETH of the user
* @return availableBorrowsETH the borrowing power left of the user
* @return currentLiquidationThreshold the liquidation threshold of the user
* @return ltv the loan to value of the user
* @return healthFactor the current health factor of the user
**/
function getUserAccountData(address user)
external
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
);
function initReserve(
address reserve,
address aTokenAddress,
address stableDebtAddress,
address variableDebtAddress,
address interestRateStrategyAddress
) external;
function setReserveInterestRateStrategyAddress(
address reserve,
address rateStrategyAddress
) external;
function setConfiguration(address reserve, uint256 configuration) external;
/**
* @dev Returns the configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The configuration of the reserve
**/
function getConfiguration(address asset)
external
view
returns (DataTypes.ReserveConfigurationMap memory);
/**
* @dev Returns the configuration of the user across all the reserves
* @param user The user address
* @return The configuration of the user
**/
function getUserConfiguration(address user)
external
view
returns (DataTypes.UserConfigurationMap memory);
/**
* @dev Returns the normalized income normalized income of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The reserve's normalized income
*/
function getReserveNormalizedIncome(address asset)
external
view
returns (uint256);
/**
* @dev Returns the normalized variable debt per unit of asset
* @param asset The address of the underlying asset of the reserve
* @return The reserve normalized variable debt
*/
function getReserveNormalizedVariableDebt(address asset)
external
view
returns (uint256);
/**
* @dev Returns the state and configuration of the reserve
* @param asset The address of the underlying asset of the reserve
* @return The state of the reserve
**/
function getReserveData(address asset)
external
view
returns (DataTypes.ReserveData memory);
function finalizeTransfer(
address asset,
address from,
address to,
uint256 amount,
uint256 balanceFromAfter,
uint256 balanceToBefore
) external;
function getReservesList() external view returns (address[] memory);
function getAddressesProvider()
external
view
returns (ILendingPoolAddressesProvider);
function setPause(bool val) external;
function paused() external view returns (bool);
}
// Part: IProtocolDataProvider
interface IProtocolDataProvider {
struct TokenData {
string symbol;
address tokenAddress;
}
function ADDRESSES_PROVIDER()
external
view
returns (ILendingPoolAddressesProvider);
function getAllReservesTokens() external view returns (TokenData[] memory);
function getAllATokens() external view returns (TokenData[] memory);
function getReserveConfigurationData(address asset)
external
view
returns (
uint256 decimals,
uint256 ltv,
uint256 liquidationThreshold,
uint256 liquidationBonus,
uint256 reserveFactor,
bool usageAsCollateralEnabled,
bool borrowingEnabled,
bool stableBorrowRateEnabled,
bool isActive,
bool isFrozen
);
function getReserveData(address asset)
external
view
returns (
uint256 availableLiquidity,
uint256 totalStableDebt,
uint256 totalVariableDebt,
uint256 liquidityRate,
uint256 variableBorrowRate,
uint256 stableBorrowRate,
uint256 averageStableBorrowRate,
uint256 liquidityIndex,
uint256 variableBorrowIndex,
uint40 lastUpdateTimestamp
);
function getUserReserveData(address asset, address user)
external
view
returns (
uint256 currentATokenBalance,
uint256 currentStableDebt,
uint256 currentVariableDebt,
uint256 principalStableDebt,
uint256 scaledVariableDebt,
uint256 stableBorrowRate,
uint256 liquidityRate,
uint40 stableRateLastUpdated,
bool usageAsCollateralEnabled
);
function getReserveTokensAddresses(address asset)
external
view
returns (
address aTokenAddress,
address stableDebtTokenAddress,
address variableDebtTokenAddress
);
}
// Part: IVariableDebtToken
/**
* @title IVariableDebtToken
* @author Aave
* @notice Defines the basic interface for a variable debt token.
**/
interface IVariableDebtToken is IERC20, IScaledBalanceToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param onBehalfOf The address of the user on which behalf minting has been performed
* @param value The amount to be minted
* @param index The last index of the reserve
**/
event Mint(
address indexed from,
address indexed onBehalfOf,
uint256 value,
uint256 index
);
/**
* @dev Mints debt token to the `onBehalfOf` address
* @param user The address receiving the borrowed underlying, being the delegatee in case
* of credit delegate, or same as `onBehalfOf` otherwise
* @param onBehalfOf The address receiving the debt tokens
* @param amount The amount of debt being minted
* @param index The variable debt index of the reserve
* @return `true` if the the previous balance of the user is 0
**/
function mint(
address user,
address onBehalfOf,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted when variable debt is burnt
* @param user The user which debt has been burned
* @param amount The amount of debt being burned
* @param index The index of the user
**/
event Burn(address indexed user, uint256 amount, uint256 index);
/**
* @dev Burns user variable debt
* @param user The user which debt is burnt
* @param index The variable debt index of the reserve
**/
function burn(
address user,
uint256 amount,
uint256 index
) external;
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController()
external
view
returns (IAaveIncentivesController);
}
// Part: IVault
interface IVault is IERC20 {
function token() external view returns (address);
function decimals() external view returns (uint256);
function deposit() external;
function pricePerShare() external view returns (uint256);
function withdraw() external returns (uint256);
function withdraw(uint256 amount) external returns (uint256);
function withdraw(
uint256 amount,
address account,
uint256 maxLoss
) external returns (uint256);
function availableDepositLimit() external view returns (uint256);
}
// Part: OpenZeppelin/[email protected]/SafeERC20
/**
* @title SafeERC20
* @dev Wrappers around ERC20 operations that throw on failure (when the token
* contract returns false). Tokens that return no value (and instead revert or
* throw on failure) are also supported, non-reverting calls are assumed to be
* successful.
* To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract,
* which allows you to call the safe operations as `token.safeTransfer(...)`, etc.
*/
library SafeERC20 {
using SafeMath for uint256;
using Address for address;
function safeTransfer(IERC20 token, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value));
}
function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal {
_callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value));
}
/**
* @dev Deprecated. This function has issues similar to the ones found in
* {IERC20-approve}, and its usage is discouraged.
*
* Whenever possible, use {safeIncreaseAllowance} and
* {safeDecreaseAllowance} instead.
*/
function safeApprove(IERC20 token, address spender, uint256 value) internal {
// safeApprove should only be called when setting an initial allowance,
// or when resetting it to zero. To increase and decrease it, use
// 'safeIncreaseAllowance' and 'safeDecreaseAllowance'
// solhint-disable-next-line max-line-length
require((value == 0) || (token.allowance(address(this), spender) == 0),
"SafeERC20: approve from non-zero to non-zero allowance"
);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value));
}
function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).add(value);
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal {
uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero");
_callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance));
}
/**
* @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement
* on the return value: the return value is optional (but if data is returned, it must not be false).
* @param token The token targeted by the call.
* @param data The call data (encoded using abi.encode or one of its variants).
*/
function _callOptionalReturn(IERC20 token, bytes memory data) private {
// We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since
// we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that
// the target address contains contract code and also asserts for success in the low-level call.
bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed");
if (returndata.length > 0) { // Return data is optional
// solhint-disable-next-line max-line-length
require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed");
}
}
}
// Part: iearn-finance/[email protected]/VaultAPI
interface VaultAPI is IERC20 {
function name() external view returns (string calldata);
function symbol() external view returns (string calldata);
function decimals() external view returns (uint256);
function apiVersion() external pure returns (string memory);
function permit(
address owner,
address spender,
uint256 amount,
uint256 expiry,
bytes calldata signature
) external returns (bool);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function deposit() external returns (uint256);
function deposit(uint256 amount) external returns (uint256);
function deposit(uint256 amount, address recipient) external returns (uint256);
// NOTE: Vyper produces multiple signatures for a given function with "default" args
function withdraw() external returns (uint256);
function withdraw(uint256 maxShares) external returns (uint256);
function withdraw(uint256 maxShares, address recipient) external returns (uint256);
function token() external view returns (address);
function strategies(address _strategy) external view returns (StrategyParams memory);
function pricePerShare() external view returns (uint256);
function totalAssets() external view returns (uint256);
function depositLimit() external view returns (uint256);
function maxAvailableShares() external view returns (uint256);
/**
* View how much the Vault would increase this Strategy's borrow limit,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function creditAvailable() external view returns (uint256);
/**
* View how much the Vault would like to pull back from the Strategy,
* based on its present performance (since its last report). Can be used to
* determine expectedReturn in your Strategy.
*/
function debtOutstanding() external view returns (uint256);
/**
* View how much the Vault expect this Strategy to return at the current
* block, based on its present performance (since its last report). Can be
* used to determine expectedReturn in your Strategy.
*/
function expectedReturn() external view returns (uint256);
/**
* This is the main contact point where the Strategy interacts with the
* Vault. It is critical that this call is handled as intended by the
* Strategy. Therefore, this function will be called by BaseStrategy to
* make sure the integration is correct.
*/
function report(
uint256 _gain,
uint256 _loss,
uint256 _debtPayment
) external returns (uint256);
/**
* This function should only be used in the scenario where the Strategy is
* being retired but no migration of the positions are possible, or in the
* extreme scenario that the Strategy needs to be put into "Emergency Exit"
* mode in order for it to exit as quickly as possible. The latter scenario
* could be for any reason that is considered "critical" that the Strategy
* exits its position as fast as possible, such as a sudden change in
* market conditions leading to losses, or an imminent failure in an
* external dependency.
*/
function revokeStrategy() external;
/**
* View the governance address of the Vault to assert privileged functions
* can only be called by governance. The Strategy serves the Vault, so it
* is subject to governance defined by the Vault.
*/
function governance() external view returns (address);
/**
* View the management address of the Vault to assert privileged functions
* can only be called by management. The Strategy serves the Vault, so it
* is subject to management defined by the Vault.
*/
function management() external view returns (address);
/**
* View the guardian address of the Vault to assert privileged functions
* can only be called by guardian. The Strategy serves the Vault, so it
* is subject to guardian defined by the Vault.
*/
function guardian() external view returns (address);
}
// Part: IInitializableAToken
/**
* @title IInitializableAToken
* @notice Interface for the initialize function on AToken
* @author Aave
**/
interface IInitializableAToken {
/**
* @dev Emitted when an aToken is initialized
* @param underlyingAsset The address of the underlying asset
* @param pool The address of the associated lending pool
* @param treasury The address of the treasury
* @param incentivesController The address of the incentives controller for this aToken
* @param aTokenDecimals the decimals of the underlying
* @param aTokenName the name of the aToken
* @param aTokenSymbol the symbol of the aToken
* @param params A set of encoded parameters for additional initialization
**/
event Initialized(
address indexed underlyingAsset,
address indexed pool,
address treasury,
address incentivesController,
uint8 aTokenDecimals,
string aTokenName,
string aTokenSymbol,
bytes params
);
/**
* @dev Initializes the aToken
* @param pool The address of the lending pool where this aToken will be used
* @param treasury The address of the Aave treasury, receiving the fees on this aToken
* @param underlyingAsset The address of the underlying asset of this aToken (E.g. WETH for aWETH)
* @param incentivesController The smart contract managing potential incentives distribution
* @param aTokenDecimals The decimals of the aToken, same as the underlying asset's
* @param aTokenName The name of the aToken
* @param aTokenSymbol The symbol of the aToken
*/
function initialize(
ILendingPool pool,
address treasury,
address underlyingAsset,
IAaveIncentivesController incentivesController,
uint8 aTokenDecimals,
string calldata aTokenName,
string calldata aTokenSymbol,
bytes calldata params
) external;
}
// Part: iearn-finance/[email protected]/BaseStrategy
/**
* @title Yearn Base Strategy
* @author yearn.finance
* @notice
* BaseStrategy implements all of the required functionality to interoperate
* closely with the Vault contract. This contract should be inherited and the
* abstract methods implemented to adapt the Strategy to the particular needs
* it has to create a return.
*
* Of special interest is the relationship between `harvest()` and
* `vault.report()'. `harvest()` may be called simply because enough time has
* elapsed since the last report, and not because any funds need to be moved
* or positions adjusted. This is critical so that the Vault may maintain an
* accurate picture of the Strategy's performance. See `vault.report()`,
* `harvest()`, and `harvestTrigger()` for further details.
*/
abstract contract BaseStrategy {
using SafeMath for uint256;
using SafeERC20 for IERC20;
string public metadataURI;
// health checks
bool public doHealthCheck;
address public healthCheck;
/**
* @notice
* Used to track which version of `StrategyAPI` this Strategy
* implements.
* @dev The Strategy's version must match the Vault's `API_VERSION`.
* @return A string which holds the current API version of this contract.
*/
function apiVersion() public pure returns (string memory) {
return "0.4.3";
}
/**
* @notice This Strategy's name.
* @dev
* You can use this field to manage the "version" of this Strategy, e.g.
* `StrategySomethingOrOtherV1`. However, "API Version" is managed by
* `apiVersion()` function above.
* @return This Strategy's name.
*/
function name() external view virtual returns (string memory);
/**
* @notice
* The amount (priced in want) of the total assets managed by this strategy should not count
* towards Yearn's TVL calculations.
* @dev
* You can override this field to set it to a non-zero value if some of the assets of this
* Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault.
* Note that this value must be strictly less than or equal to the amount provided by
* `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets.
* Also note that this value is used to determine the total assets under management by this
* strategy, for the purposes of computing the management fee in `Vault`
* @return
* The amount of assets this strategy manages that should not be included in Yearn's Total Value
* Locked (TVL) calculation across it's ecosystem.
*/
function delegatedAssets() external view virtual returns (uint256) {
return 0;
}
VaultAPI public vault;
address public strategist;
address public rewards;
address public keeper;
IERC20 public want;
// So indexers can keep track of this
event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding);
event UpdatedStrategist(address newStrategist);
event UpdatedKeeper(address newKeeper);
event UpdatedRewards(address rewards);
event UpdatedMinReportDelay(uint256 delay);
event UpdatedMaxReportDelay(uint256 delay);
event UpdatedProfitFactor(uint256 profitFactor);
event UpdatedDebtThreshold(uint256 debtThreshold);
event EmergencyExitEnabled();
event UpdatedMetadataURI(string metadataURI);
// The minimum number of seconds between harvest calls. See
// `setMinReportDelay()` for more details.
uint256 public minReportDelay;
// The maximum number of seconds between harvest calls. See
// `setMaxReportDelay()` for more details.
uint256 public maxReportDelay;
// The minimum multiple that `callCost` must be above the credit/profit to
// be "justifiable". See `setProfitFactor()` for more details.
uint256 public profitFactor;
// Use this to adjust the threshold at which running a debt causes a
// harvest trigger. See `setDebtThreshold()` for more details.
uint256 public debtThreshold;
// See note on `setEmergencyExit()`.
bool public emergencyExit;
// modifiers
modifier onlyAuthorized() {
require(msg.sender == strategist || msg.sender == governance(), "!authorized");
_;
}
modifier onlyEmergencyAuthorized() {
require(
msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyStrategist() {
require(msg.sender == strategist, "!strategist");
_;
}
modifier onlyGovernance() {
require(msg.sender == governance(), "!authorized");
_;
}
modifier onlyKeepers() {
require(
msg.sender == keeper ||
msg.sender == strategist ||
msg.sender == governance() ||
msg.sender == vault.guardian() ||
msg.sender == vault.management(),
"!authorized"
);
_;
}
modifier onlyVaultManagers() {
require(msg.sender == vault.management() || msg.sender == governance(), "!authorized");
_;
}
constructor(address _vault) public {
_initialize(_vault, msg.sender, msg.sender, msg.sender);
}
/**
* @notice
* Initializes the Strategy, this is called only once, when the
* contract is deployed.
* @dev `_vault` should implement `VaultAPI`.
* @param _vault The address of the Vault responsible for this Strategy.
* @param _strategist The address to assign as `strategist`.
* The strategist is able to change the reward address
* @param _rewards The address to use for pulling rewards.
* @param _keeper The adddress of the _keeper. _keeper
* can harvest and tend a strategy.
*/
function _initialize(
address _vault,
address _strategist,
address _rewards,
address _keeper
) internal {
require(address(want) == address(0), "Strategy already initialized");
vault = VaultAPI(_vault);
want = IERC20(vault.token());
want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas)
strategist = _strategist;
rewards = _rewards;
keeper = _keeper;
// initialize variables
minReportDelay = 0;
maxReportDelay = 86400;
profitFactor = 100;
debtThreshold = 0;
vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled
}
function setHealthCheck(address _healthCheck) external onlyVaultManagers {
healthCheck = _healthCheck;
}
function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers {
doHealthCheck = _doHealthCheck;
}
/**
* @notice
* Used to change `strategist`.
*
* This may only be called by governance or the existing strategist.
* @param _strategist The new address to assign as `strategist`.
*/
function setStrategist(address _strategist) external onlyAuthorized {
require(_strategist != address(0));
strategist = _strategist;
emit UpdatedStrategist(_strategist);
}
/**
* @notice
* Used to change `keeper`.
*
* `keeper` is the only address that may call `tend()` or `harvest()`,
* other than `governance()` or `strategist`. However, unlike
* `governance()` or `strategist`, `keeper` may *only* call `tend()`
* and `harvest()`, and no other authorized functions, following the
* principle of least privilege.
*
* This may only be called by governance or the strategist.
* @param _keeper The new address to assign as `keeper`.
*/
function setKeeper(address _keeper) external onlyAuthorized {
require(_keeper != address(0));
keeper = _keeper;
emit UpdatedKeeper(_keeper);
}
/**
* @notice
* Used to change `rewards`. EOA or smart contract which has the permission
* to pull rewards from the vault.
*
* This may only be called by the strategist.
* @param _rewards The address to use for pulling rewards.
*/
function setRewards(address _rewards) external onlyStrategist {
require(_rewards != address(0));
vault.approve(rewards, 0);
rewards = _rewards;
vault.approve(rewards, uint256(-1));
emit UpdatedRewards(_rewards);
}
/**
* @notice
* Used to change `minReportDelay`. `minReportDelay` is the minimum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the minimum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The minimum number of seconds to wait between harvests.
*/
function setMinReportDelay(uint256 _delay) external onlyAuthorized {
minReportDelay = _delay;
emit UpdatedMinReportDelay(_delay);
}
/**
* @notice
* Used to change `maxReportDelay`. `maxReportDelay` is the maximum number
* of blocks that should pass for `harvest()` to be called.
*
* For external keepers (such as the Keep3r network), this is the maximum
* time between jobs to wait. (see `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _delay The maximum number of seconds to wait between harvests.
*/
function setMaxReportDelay(uint256 _delay) external onlyAuthorized {
maxReportDelay = _delay;
emit UpdatedMaxReportDelay(_delay);
}
/**
* @notice
* Used to change `profitFactor`. `profitFactor` is used to determine
* if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()`
* for more details.)
*
* This may only be called by governance or the strategist.
* @param _profitFactor A ratio to multiply anticipated
* `harvest()` gas cost against.
*/
function setProfitFactor(uint256 _profitFactor) external onlyAuthorized {
profitFactor = _profitFactor;
emit UpdatedProfitFactor(_profitFactor);
}
/**
* @notice
* Sets how far the Strategy can go into loss without a harvest and report
* being required.
*
* By default this is 0, meaning any losses would cause a harvest which
* will subsequently report the loss to the Vault for tracking. (See
* `harvestTrigger()` for more details.)
*
* This may only be called by governance or the strategist.
* @param _debtThreshold How big of a loss this Strategy may carry without
* being required to report to the Vault.
*/
function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized {
debtThreshold = _debtThreshold;
emit UpdatedDebtThreshold(_debtThreshold);
}
/**
* @notice
* Used to change `metadataURI`. `metadataURI` is used to store the URI
* of the file describing the strategy.
*
* This may only be called by governance or the strategist.
* @param _metadataURI The URI that describe the strategy.
*/
function setMetadataURI(string calldata _metadataURI) external onlyAuthorized {
metadataURI = _metadataURI;
emit UpdatedMetadataURI(_metadataURI);
}
/**
* Resolve governance address from Vault contract, used to make assertions
* on protected functions in the Strategy.
*/
function governance() internal view returns (address) {
return vault.governance();
}
/**
* @notice
* Provide an accurate conversion from `_amtInWei` (denominated in wei)
* to `want` (using the native decimal characteristics of `want`).
* @dev
* Care must be taken when working with decimals to assure that the conversion
* is compatible. As an example:
*
* given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals),
* with USDC/ETH = 1800, this should give back 1800000000 (180 USDC)
*
* @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want`
* @return The amount in `want` of `_amtInEth` converted to `want`
**/
function ethToWant(uint256 _amtInWei) public view virtual returns (uint256);
/**
* @notice
* Provide an accurate estimate for the total amount of assets
* (principle + return) that this Strategy is currently managing,
* denominated in terms of `want` tokens.
*
* This total should be "realizable" e.g. the total value that could
* *actually* be obtained from this Strategy if it were to divest its
* entire position based on current on-chain conditions.
* @dev
* Care must be taken in using this function, since it relies on external
* systems, which could be manipulated by the attacker to give an inflated
* (or reduced) value produced by this function, based on current on-chain
* conditions (e.g. this function is possible to influence through
* flashloan attacks, oracle manipulations, or other DeFi attack
* mechanisms).
*
* It is up to governance to use this function to correctly order this
* Strategy relative to its peers in the withdrawal queue to minimize
* losses for the Vault based on sudden withdrawals. This value should be
* higher than the total debt of the Strategy and higher than its expected
* value to be "safe".
* @return The estimated total assets in this Strategy.
*/
function estimatedTotalAssets() public view virtual returns (uint256);
/*
* @notice
* Provide an indication of whether this strategy is currently "active"
* in that it is managing an active position, or will manage a position in
* the future. This should correlate to `harvest()` activity, so that Harvest
* events can be tracked externally by indexing agents.
* @return True if the strategy is actively managing a position.
*/
function isActive() public view returns (bool) {
return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0;
}
/**
* Perform any Strategy unwinding or other calls necessary to capture the
* "free return" this Strategy has generated since the last time its core
* position(s) were adjusted. Examples include unwrapping extra rewards.
* This call is only used during "normal operation" of a Strategy, and
* should be optimized to minimize losses as much as possible.
*
* This method returns any realized profits and/or realized losses
* incurred, and should return the total amounts of profits/losses/debt
* payments (in `want` tokens) for the Vault's accounting (e.g.
* `want.balanceOf(this) >= _debtPayment + _profit`).
*
* `_debtOutstanding` will be 0 if the Strategy is not past the configured
* debt limit, otherwise its value will be how far past the debt limit
* the Strategy is. The Strategy's debt limit is configured in the Vault.
*
* NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`.
* It is okay for it to be less than `_debtOutstanding`, as that
* should only used as a guide for how much is left to pay back.
* Payments should be made to minimize loss from slippage, debt,
* withdrawal fees, etc.
*
* See `vault.debtOutstanding()`.
*/
function prepareReturn(uint256 _debtOutstanding)
internal
virtual
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
);
/**
* Perform any adjustments to the core position(s) of this Strategy given
* what change the Vault made in the "investable capital" available to the
* Strategy. Note that all "free capital" in the Strategy after the report
* was made is available for reinvestment. Also note that this number
* could be 0, and you should handle that scenario accordingly.
*
* See comments regarding `_debtOutstanding` on `prepareReturn()`.
*/
function adjustPosition(uint256 _debtOutstanding) internal virtual;
/**
* Liquidate up to `_amountNeeded` of `want` of this strategy's positions,
* irregardless of slippage. Any excess will be re-invested with `adjustPosition()`.
* This function should return the amount of `want` tokens made available by the
* liquidation. If there is a difference between them, `_loss` indicates whether the
* difference is due to a realized loss, or if there is some other sitution at play
* (e.g. locked funds) where the amount made available is less than what is needed.
*
* NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained
*/
function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss);
/**
* Liquidate everything and returns the amount that got freed.
* This function is used during emergency exit instead of `prepareReturn()` to
* liquidate all of the Strategy's positions back to the Vault.
*/
function liquidateAllPositions() internal virtual returns (uint256 _amountFreed);
/**
* @notice
* Provide a signal to the keeper that `tend()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `tend()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `tend()` is not called
* shortly, then this can return `true` even if the keeper might be
* "at a loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `harvestTrigger()` should never return `true` at the same
* time.
* @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei).
* @return `true` if `tend()` should be called, `false` otherwise.
*/
function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) {
// We usually don't need tend, but if there are positions that need
// active maintainence, overriding this function is how you would
// signal for that.
// If your implementation uses the cost of the call in want, you can
// use uint256 callCost = ethToWant(callCostInWei);
return false;
}
/**
* @notice
* Adjust the Strategy's position. The purpose of tending isn't to
* realize gains, but to maximize yield by reinvesting any returns.
*
* See comments on `adjustPosition()`.
*
* This may only be called by governance, the strategist, or the keeper.
*/
function tend() external onlyKeepers {
// Don't take profits with this call, but adjust for better gains
adjustPosition(vault.debtOutstanding());
}
/**
* @notice
* Provide a signal to the keeper that `harvest()` should be called. The
* keeper will provide the estimated gas cost that they would pay to call
* `harvest()`, and this function should use that estimate to make a
* determination if calling it is "worth it" for the keeper. This is not
* the only consideration into issuing this trigger, for example if the
* position would be negatively affected if `harvest()` is not called
* shortly, then this can return `true` even if the keeper might be "at a
* loss" (keepers are always reimbursed by Yearn).
* @dev
* `callCostInWei` must be priced in terms of `wei` (1e-18 ETH).
*
* This call and `tendTrigger` should never return `true` at the
* same time.
*
* See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the
* strategist-controlled parameters that will influence whether this call
* returns `true` or not. These parameters will be used in conjunction
* with the parameters reported to the Vault (see `params`) to determine
* if calling `harvest()` is merited.
*
* It is expected that an external system will check `harvestTrigger()`.
* This could be a script run off a desktop or cloud bot (e.g.
* https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py),
* or via an integration with the Keep3r network (e.g.
* https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol).
* @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei).
* @return `true` if `harvest()` should be called, `false` otherwise.
*/
function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) {
uint256 callCost = ethToWant(callCostInWei);
StrategyParams memory params = vault.strategies(address(this));
// Should not trigger if Strategy is not activated
if (params.activation == 0) return false;
// Should not trigger if we haven't waited long enough since previous harvest
if (block.timestamp.sub(params.lastReport) < minReportDelay) return false;
// Should trigger if hasn't been called in a while
if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true;
// If some amount is owed, pay it back
// NOTE: Since debt is based on deposits, it makes sense to guard against large
// changes to the value from triggering a harvest directly through user
// behavior. This should ensure reasonable resistance to manipulation
// from user-initiated withdrawals as the outstanding debt fluctuates.
uint256 outstanding = vault.debtOutstanding();
if (outstanding > debtThreshold) return true;
// Check for profits and losses
uint256 total = estimatedTotalAssets();
// Trigger if we have a loss to report
if (total.add(debtThreshold) < params.totalDebt) return true;
uint256 profit = 0;
if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit!
// Otherwise, only trigger if it "makes sense" economically (gas cost
// is <N% of value moved)
uint256 credit = vault.creditAvailable();
return (profitFactor.mul(callCost) < credit.add(profit));
}
/**
* @notice
* Harvests the Strategy, recognizing any profits or losses and adjusting
* the Strategy's position.
*
* In the rare case the Strategy is in emergency shutdown, this will exit
* the Strategy's position.
*
* This may only be called by governance, the strategist, or the keeper.
* @dev
* When `harvest()` is called, the Strategy reports to the Vault (via
* `vault.report()`), so in some cases `harvest()` must be called in order
* to take in profits, to borrow newly available funds from the Vault, or
* otherwise adjust its position. In other cases `harvest()` must be
* called to report to the Vault on the Strategy's position, especially if
* any losses have occurred.
*/
function harvest() external onlyKeepers {
uint256 profit = 0;
uint256 loss = 0;
uint256 debtOutstanding = vault.debtOutstanding();
uint256 debtPayment = 0;
if (emergencyExit) {
// Free up as much capital as possible
uint256 amountFreed = liquidateAllPositions();
if (amountFreed < debtOutstanding) {
loss = debtOutstanding.sub(amountFreed);
} else if (amountFreed > debtOutstanding) {
profit = amountFreed.sub(debtOutstanding);
}
debtPayment = debtOutstanding.sub(loss);
} else {
// Free up returns for Vault to pull
(profit, loss, debtPayment) = prepareReturn(debtOutstanding);
}
// Allow Vault to take up to the "harvested" balance of this contract,
// which is the amount it has earned since the last time it reported to
// the Vault.
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
debtOutstanding = vault.report(profit, loss, debtPayment);
// Check if free returns are left, and re-invest them
adjustPosition(debtOutstanding);
// call healthCheck contract
if (doHealthCheck && healthCheck != address(0)) {
require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck");
} else {
doHealthCheck = true;
}
emit Harvested(profit, loss, debtPayment, debtOutstanding);
}
/**
* @notice
* Withdraws `_amountNeeded` to `vault`.
*
* This may only be called by the Vault.
* @param _amountNeeded How much `want` to withdraw.
* @return _loss Any realized losses
*/
function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) {
require(msg.sender == address(vault), "!vault");
// Liquidate as much as possible to `want`, up to `_amountNeeded`
uint256 amountFreed;
(amountFreed, _loss) = liquidatePosition(_amountNeeded);
// Send it directly back (NOTE: Using `msg.sender` saves some gas here)
want.safeTransfer(msg.sender, amountFreed);
// NOTE: Reinvest anything leftover on next `tend`/`harvest`
}
/**
* Do anything necessary to prepare this Strategy for migration, such as
* transferring any reserve or LP tokens, CDPs, or other tokens or stores of
* value.
*/
function prepareMigration(address _newStrategy) internal virtual;
/**
* @notice
* Transfers all `want` from this Strategy to `_newStrategy`.
*
* This may only be called by the Vault.
* @dev
* The new Strategy's Vault must be the same as this Strategy's Vault.
* The migration process should be carefully performed to make sure all
* the assets are migrated to the new address, which should have never
* interacted with the vault before.
* @param _newStrategy The Strategy to migrate to.
*/
function migrate(address _newStrategy) external {
require(msg.sender == address(vault));
require(BaseStrategy(_newStrategy).vault() == vault);
prepareMigration(_newStrategy);
want.safeTransfer(_newStrategy, want.balanceOf(address(this)));
}
/**
* @notice
* Activates emergency exit. Once activated, the Strategy will exit its
* position upon the next harvest, depositing all funds into the Vault as
* quickly as is reasonable given on-chain conditions.
*
* This may only be called by governance or the strategist.
* @dev
* See `vault.setEmergencyShutdown()` and `harvest()` for further details.
*/
function setEmergencyExit() external onlyEmergencyAuthorized {
emergencyExit = true;
vault.revokeStrategy();
emit EmergencyExitEnabled();
}
/**
* Override this to add all tokens/tokenized positions this contract
* manages on a *persistent* basis (e.g. not just for swapping back to
* want ephemerally).
*
* NOTE: Do *not* include `want`, already included in `sweep` below.
*
* Example:
* ```
* function protectedTokens() internal override view returns (address[] memory) {
* address[] memory protected = new address[](3);
* protected[0] = tokenA;
* protected[1] = tokenB;
* protected[2] = tokenC;
* return protected;
* }
* ```
*/
function protectedTokens() internal view virtual returns (address[] memory);
/**
* @notice
* Removes tokens from this Strategy that are not the type of tokens
* managed by this Strategy. This may be used in case of accidentally
* sending the wrong kind of token to this Strategy.
*
* Tokens will be sent to `governance()`.
*
* This will fail if an attempt is made to sweep `want`, or any tokens
* that are protected by this Strategy.
*
* This may only be called by governance.
* @dev
* Implement `protectedTokens()` to specify any additional tokens that
* should be protected from sweeping in addition to `want`.
* @param _token The token to transfer out of this vault.
*/
function sweep(address _token) external onlyGovernance {
require(_token != address(want), "!want");
require(_token != address(vault), "!shares");
address[] memory _protectedTokens = protectedTokens();
for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected");
IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this)));
}
}
// Part: IAToken
interface IAToken is IERC20, IScaledBalanceToken, IInitializableAToken {
/**
* @dev Emitted after the mint action
* @param from The address performing the mint
* @param value The amount being
* @param index The new liquidity index of the reserve
**/
event Mint(address indexed from, uint256 value, uint256 index);
/**
* @dev Mints `amount` aTokens to `user`
* @param user The address receiving the minted tokens
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
* @return `true` if the the previous balance of the user was 0
*/
function mint(
address user,
uint256 amount,
uint256 index
) external returns (bool);
/**
* @dev Emitted after aTokens are burned
* @param from The owner of the aTokens, getting them burned
* @param target The address that will receive the underlying
* @param value The amount being burned
* @param index The new liquidity index of the reserve
**/
event Burn(
address indexed from,
address indexed target,
uint256 value,
uint256 index
);
/**
* @dev Emitted during the transfer action
* @param from The user whose tokens are being transferred
* @param to The recipient
* @param value The amount being transferred
* @param index The new liquidity index of the reserve
**/
event BalanceTransfer(
address indexed from,
address indexed to,
uint256 value,
uint256 index
);
/**
* @dev Burns aTokens from `user` and sends the equivalent amount of underlying to `receiverOfUnderlying`
* @param user The owner of the aTokens, getting them burned
* @param receiverOfUnderlying The address that will receive the underlying
* @param amount The amount being burned
* @param index The new liquidity index of the reserve
**/
function burn(
address user,
address receiverOfUnderlying,
uint256 amount,
uint256 index
) external;
/**
* @dev Mints aTokens to the reserve treasury
* @param amount The amount of tokens getting minted
* @param index The new liquidity index of the reserve
*/
function mintToTreasury(uint256 amount, uint256 index) external;
/**
* @dev Transfers aTokens in the event of a borrow being liquidated, in case the liquidators reclaims the aToken
* @param from The address getting liquidated, current owner of the aTokens
* @param to The recipient
* @param value The amount of tokens getting transferred
**/
function transferOnLiquidation(
address from,
address to,
uint256 value
) external;
/**
* @dev Transfers the underlying asset to `target`. Used by the LendingPool to transfer
* assets in borrow(), withdraw() and flashLoan()
* @param user The recipient of the underlying
* @param amount The amount getting transferred
* @return The amount transferred
**/
function transferUnderlyingTo(address user, uint256 amount)
external
returns (uint256);
/**
* @dev Invoked to execute actions on the aToken side after a repayment.
* @param user The user executing the repayment
* @param amount The amount getting repaid
**/
function handleRepayment(address user, uint256 amount) external;
/**
* @dev Returns the address of the incentives controller contract
**/
function getIncentivesController()
external
view
returns (IAaveIncentivesController);
/**
* @dev Returns the address of the underlying asset of this aToken (E.g. WETH for aWETH)
**/
function UNDERLYING_ASSET_ADDRESS() external view returns (address);
}
// Part: AaveLenderBorrowerLib
library AaveLenderBorrowerLib {
using SafeMath for uint256;
using WadRayMath for uint256;
struct CalcMaxDebtLocalVars {
uint256 availableLiquidity;
uint256 totalStableDebt;
uint256 totalVariableDebt;
uint256 totalDebt;
uint256 utilizationRate;
uint256 totalLiquidity;
uint256 targetUtilizationRate;
uint256 maxProtocolDebt;
}
struct IrsVars {
uint256 optimalRate;
uint256 baseRate;
uint256 slope1;
uint256 slope2;
}
uint256 internal constant MAX_BPS = 10_000;
IProtocolDataProvider public constant protocolDataProvider =
IProtocolDataProvider(0x057835Ad21a177dbdd3090bB1CAE03EaCF78Fc6d);
function lendingPool() public view returns (ILendingPool) {
return
ILendingPool(
protocolDataProvider.ADDRESSES_PROVIDER().getLendingPool()
);
}
function priceOracle() public view returns (IPriceOracle) {
return
IPriceOracle(
protocolDataProvider.ADDRESSES_PROVIDER().getPriceOracle()
);
}
function incentivesController(
IAToken aToken,
IVariableDebtToken variableDebtToken,
bool isWantIncentivised,
bool isInvestmentTokenIncentivised
) public view returns (IAaveIncentivesController) {
if (isWantIncentivised) {
return aToken.getIncentivesController();
} else if (isInvestmentTokenIncentivised) {
return variableDebtToken.getIncentivesController();
} else {
return IAaveIncentivesController(0);
}
}
function toETH(uint256 _amount, address asset)
public
view
returns (uint256)
{
return
_amount.mul(priceOracle().getAssetPrice(asset)).div(
uint256(10)**uint256(IOptionalERC20(asset).decimals())
);
}
function fromETH(uint256 _amount, address asset)
public
view
returns (uint256)
{
return
_amount
.mul(uint256(10)**uint256(IOptionalERC20(asset).decimals()))
.div(priceOracle().getAssetPrice(asset));
}
function calcMaxDebt(address _investmentToken, uint256 _acceptableCostsRay)
public
view
returns (
uint256 currentProtocolDebt,
uint256 maxProtocolDebt,
uint256 targetU
)
{
// This function is used to calculate the maximum amount of debt that the protocol can take
// to keep the cost of capital lower than the set acceptableCosts
// This maxProtocolDebt will be used to decide if capital costs are acceptable or not
// and to repay required debt to keep the rates below acceptable costs
// Hack to avoid the stack too deep compiler error.
CalcMaxDebtLocalVars memory vars;
DataTypes.ReserveData memory reserveData =
lendingPool().getReserveData(address(_investmentToken));
IReserveInterestRateStrategy irs =
IReserveInterestRateStrategy(
reserveData.interestRateStrategyAddress
);
(
vars.availableLiquidity, // = total supply - total stable debt - total variable debt
vars.totalStableDebt, // total debt paying stable interest rates
vars.totalVariableDebt, // total debt paying stable variable rates
,
,
,
,
,
,
) = protocolDataProvider.getReserveData(address(_investmentToken));
vars.totalDebt = vars.totalStableDebt.add(vars.totalVariableDebt);
vars.totalLiquidity = vars.availableLiquidity.add(vars.totalDebt);
vars.utilizationRate = vars.totalDebt == 0
? 0
: vars.totalDebt.rayDiv(vars.totalLiquidity);
// Aave's Interest Rate Strategy Parameters (see docs)
IrsVars memory irsVars;
irsVars.optimalRate = irs.OPTIMAL_UTILIZATION_RATE();
irsVars.baseRate = irs.baseVariableBorrowRate(); // minimum cost of capital with 0 % of utilisation rate
irsVars.slope1 = irs.variableRateSlope1(); // rate of increase of cost of debt up to Optimal Utilisation Rate
irsVars.slope2 = irs.variableRateSlope2(); // rate of increase of cost of debt above Optimal Utilisation Rate
// acceptableCosts should always be > baseVariableBorrowRate
// If it's not this will revert since the strategist set the wrong
// acceptableCosts value
if (
vars.utilizationRate < irsVars.optimalRate &&
_acceptableCostsRay < irsVars.baseRate.add(irsVars.slope1)
) {
// we solve Aave's Interest Rates equation for sub optimal utilisation rates
// IR = BASERATE + SLOPE1 * CURRENT_UTIL_RATE / OPTIMAL_UTIL_RATE
vars.targetUtilizationRate = (
_acceptableCostsRay.sub(irsVars.baseRate)
)
.rayMul(irsVars.optimalRate)
.rayDiv(irsVars.slope1);
} else {
// Special case where protocol is above utilization rate but we want
// a lower interest rate than (base + slope1)
if (_acceptableCostsRay < irsVars.baseRate.add(irsVars.slope1)) {
return (toETH(vars.totalDebt, address(_investmentToken)), 0, 0);
}
// we solve Aave's Interest Rates equation for utilisation rates above optimal U
// IR = BASERATE + SLOPE1 + SLOPE2 * (CURRENT_UTIL_RATE - OPTIMAL_UTIL_RATE) / (1-OPTIMAL_UTIL_RATE)
vars.targetUtilizationRate = (
_acceptableCostsRay.sub(irsVars.baseRate.add(irsVars.slope1))
)
.rayMul(uint256(1e27).sub(irsVars.optimalRate))
.rayDiv(irsVars.slope2)
.add(irsVars.optimalRate);
}
vars.maxProtocolDebt = vars
.totalLiquidity
.rayMul(vars.targetUtilizationRate)
.rayDiv(1e27);
return (
toETH(vars.totalDebt, address(_investmentToken)),
toETH(vars.maxProtocolDebt, address(_investmentToken)),
vars.targetUtilizationRate
);
}
function calculateAmountToRepay(
uint256 amountETH,
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 warningLTV,
uint256 targetLTV,
address investmentToken,
uint256 minThreshold
) public view returns (uint256) {
if (amountETH == 0) {
return 0;
}
// we check if the collateral that we are withdrawing leaves us in a risky range, we then take action
uint256 amountToWithdrawETH = amountETH;
// calculate the collateral that we are leaving after withdrawing
uint256 newCollateral =
totalCollateralETH > amountToWithdrawETH
? totalCollateralETH.sub(amountToWithdrawETH)
: 0;
uint256 ltvAfterWithdrawal =
newCollateral > 0
? totalDebtETH.mul(MAX_BPS).div(newCollateral)
: type(uint256).max;
// check if the new LTV is in UNHEALTHY range
// remember that if balance > _amountNeeded, ltvAfterWithdrawal == 0 (0 risk)
// this is not true but the effect will be the same
if (ltvAfterWithdrawal <= warningLTV) {
// no need of repaying debt because the LTV is ok
return 0;
} else if (ltvAfterWithdrawal == type(uint256).max) {
// we are withdrawing 100% of collateral so we need to repay full debt
return fromETH(totalDebtETH, address(investmentToken));
}
// WARNING: this only works for a single collateral asset, otherwise liquidationThreshold might change depending on the collateral being withdrawn
// e.g. we have USDC + WBTC as collateral, end liquidationThreshold will be different depending on which asset we withdraw
uint256 newTargetDebt = targetLTV.mul(newCollateral).div(MAX_BPS);
// if newTargetDebt is higher, we don't need to repay anything
if (newTargetDebt > totalDebtETH) {
return 0;
}
return
fromETH(
totalDebtETH.sub(newTargetDebt) < minThreshold
? totalDebtETH
: totalDebtETH.sub(newTargetDebt),
address(investmentToken)
);
}
function checkCooldown(
bool isWantIncentivised,
bool isInvestmentTokenIncentivised,
address stkAave
) external view returns (bool) {
if (!isWantIncentivised && !isInvestmentTokenIncentivised) {
return false;
}
uint256 cooldownStartTimestamp =
IStakedAave(stkAave).stakersCooldowns(address(this));
uint256 COOLDOWN_SECONDS = IStakedAave(stkAave).COOLDOWN_SECONDS();
uint256 UNSTAKE_WINDOW = IStakedAave(stkAave).UNSTAKE_WINDOW();
return
cooldownStartTimestamp != 0 &&
block.timestamp > cooldownStartTimestamp.add(COOLDOWN_SECONDS) &&
block.timestamp <=
cooldownStartTimestamp.add(COOLDOWN_SECONDS).add(UNSTAKE_WINDOW);
}
function shouldRebalance(
address investmentToken,
uint256 acceptableCostsRay,
uint256 targetLTV,
uint256 warningLTV,
uint256 totalCollateralETH,
uint256 totalDebtETH
) external view returns (bool) {
uint256 currentLTV = totalDebtETH.mul(MAX_BPS).div(totalCollateralETH);
(uint256 currentProtocolDebt, uint256 maxProtocolDebt, ) =
calcMaxDebt(investmentToken, acceptableCostsRay);
if (
(currentLTV < targetLTV &&
currentProtocolDebt < maxProtocolDebt &&
targetLTV.sub(currentLTV) > 1000) || // WE NEED TO TAKE ON MORE DEBT (we need a 10p.p (1000bps) difference)
(currentLTV > warningLTV || currentProtocolDebt > maxProtocolDebt) // WE NEED TO REPAY DEBT BECAUSE OF UNHEALTHY RATIO OR BORROWING COSTS
) {
return true;
}
// no call to super.tendTrigger as it would return false
return false;
}
}
// Part: Strategy
contract Strategy is BaseStrategy {
using SafeERC20 for IERC20;
using Address for address;
using SafeMath for uint256;
using WadRayMath for uint256;
// max interest rate we can afford to pay for borrowing investment token
// amount in Ray (1e27 = 100%)
uint256 public acceptableCostsRay = WadRayMath.RAY;
// max amount to borrow. used to manually limit amount (for yVault to keep APY)
uint256 public maxTotalBorrowIT;
bool public isWantIncentivised;
bool public isInvestmentTokenIncentivised;
// if set to true, the strategy will not try to repay debt by selling want
bool public leaveDebtBehind;
// Aave's referral code
uint16 internal referral;
// NOTE: LTV = Loan-To-Value = debt/collateral
// Target LTV: ratio up to which which we will borrow
uint16 public targetLTVMultiplier = 6_000;
// Warning LTV: ratio at which we will repay
uint16 public warningLTVMultiplier = 8_000; // 80% of liquidation LTV
// support
uint16 internal constant MAX_BPS = 10_000; // 100%
uint16 internal constant MAX_MULTIPLIER = 9_000; // 90%
IAToken internal aToken;
IVariableDebtToken internal variableDebtToken;
IVault public yVault;
IERC20 internal investmentToken;
ISwap public router;
IStakedAave internal constant stkAave =
IStakedAave(0x4da27a545c0c5B758a6BA100e3a049001de870f5);
address internal constant WETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2;
address internal constant AAVE = 0x7Fc66500c84A76Ad7e9c93437bFc5Ac33E2DDaE9;
uint256 internal minThreshold;
uint256 public maxLoss;
string internal strategyName;
event RepayDebt(uint256 repayAmount, uint256 previousDebtBalance);
constructor(
address _vault,
address _yVault,
string memory _strategyName
) public BaseStrategy(_vault) {
_initializeThis(_yVault, _strategyName);
}
// ----------------- PUBLIC VIEW FUNCTIONS -----------------
function name() external view override returns (string memory) {
return strategyName;
}
function estimatedTotalAssets() public view override returns (uint256) {
// not taking into account aave rewards (they are staked and not accesible)
return
balanceOfWant() // balance of want
.add(balanceOfAToken()) // asset suplied as collateral
.add(
_fromETH(
_toETH(_valueOfInvestment(), address(investmentToken)),
address(want)
)
) // current value of assets deposited in vault
.sub(
_fromETH(
_toETH(balanceOfDebt(), address(investmentToken)),
address(want)
)
); // liabilities
}
// ----------------- SETTERS -----------------
// we put all together to save contract bytecode (!)
function setStrategyParams(
uint16 _targetLTVMultiplier,
uint16 _warningLTVMultiplier,
uint256 _acceptableCostsRay,
uint16 _aaveReferral,
uint256 _maxTotalBorrowIT,
bool _isWantIncentivised,
bool _isInvestmentTokenIncentivised,
bool _leaveDebtBehind,
uint256 _maxLoss
) external onlyEmergencyAuthorized {
require(
_warningLTVMultiplier <= MAX_MULTIPLIER &&
_targetLTVMultiplier <= _warningLTVMultiplier
);
targetLTVMultiplier = _targetLTVMultiplier;
warningLTVMultiplier = _warningLTVMultiplier;
acceptableCostsRay = _acceptableCostsRay;
maxTotalBorrowIT = _maxTotalBorrowIT;
referral = _aaveReferral;
isWantIncentivised = _isWantIncentivised;
isInvestmentTokenIncentivised = _isInvestmentTokenIncentivised;
leaveDebtBehind = _leaveDebtBehind;
maxLoss = _maxLoss;
}
// Where to route token swaps
// Access control is stricter in this method as it will be sent funds
function setSwapRouter(ISwap _router) external onlyGovernance {
router = _router;
}
function _initializeThis(address _yVault, string memory _strategyName)
internal
{
yVault = IVault(_yVault);
investmentToken = IERC20(IVault(_yVault).token());
(address _aToken, , ) =
_protocolDataProvider().getReserveTokensAddresses(address(want));
aToken = IAToken(_aToken);
(, , address _variableDebtToken) =
_protocolDataProvider().getReserveTokensAddresses(
address(investmentToken)
);
variableDebtToken = IVariableDebtToken(_variableDebtToken);
minThreshold = (10**(yVault.decimals())).div(100); // 0.01 minThreshold
// Set default router to SushiSwap
router = ISwap(0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F);
strategyName = _strategyName;
}
function initialize(
address _vault,
address _yVault,
string memory _strategyName
) public {
address sender = msg.sender;
_initialize(_vault, sender, sender, sender);
_initializeThis(_yVault, _strategyName);
}
// ----------------- MAIN STRATEGY FUNCTIONS -----------------
function prepareReturn(uint256 _debtOutstanding)
internal
override
returns (
uint256 _profit,
uint256 _loss,
uint256 _debtPayment
)
{
uint256 totalDebt = vault.strategies(address(this)).totalDebt;
// claim rewards from Aave's Liquidity Mining Program
_claimRewards();
// claim rewards from yVault
_takeVaultProfit();
uint256 totalAssetsAfterProfit = estimatedTotalAssets();
_profit = totalAssetsAfterProfit > totalDebt
? totalAssetsAfterProfit.sub(totalDebt)
: 0;
uint256 _amountFreed;
(_amountFreed, _loss) = liquidatePosition(
_debtOutstanding.add(_profit)
);
_debtPayment = Math.min(_debtOutstanding, _amountFreed);
if (_loss > _profit) {
// Example:
// debtOutstanding 100, profit 50, _amountFreed 100, _loss 50
// loss should be 0, (50-50)
// profit should endup in 0
_loss = _loss.sub(_profit);
_profit = 0;
} else {
// Example:
// debtOutstanding 100, profit 50, _amountFreed 140, _loss 10
// _profit should be 40, (50 profit - 10 loss)
// loss should end up in be 0
_profit = _profit.sub(_loss);
_loss = 0;
}
}
function adjustPosition(uint256 _debtOutstanding) internal override {
uint256 wantBalance = balanceOfWant();
// if we have enough want to deposit more into Aave, we do
// NOTE: we do not skip the rest of the function if we don't as it may need to repay or take on more debt
if (wantBalance > _debtOutstanding) {
uint256 amountToDeposit = wantBalance.sub(_debtOutstanding);
_depositToAave(amountToDeposit);
}
// NOTE: debt + collateral calcs are done in ETH
(
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
,
) = _getAaveUserAccountData();
// if there is no want deposited into aave, don't do nothing
// this means no debt is borrowed from aave too
if (totalCollateralETH == 0) {
return;
}
uint256 currentLTV = totalDebtETH.mul(MAX_BPS).div(totalCollateralETH);
uint256 targetLTV = _getTargetLTV(currentLiquidationThreshold); // 60% under liquidation Threshold
uint256 warningLTV = _getWarningLTV(currentLiquidationThreshold); // 80% under liquidation Threshold
// decide in which range we are and act accordingly:
// SUBOPTIMAL(borrow) (e.g. from 0 to 60% liqLTV)
// HEALTHY(do nothing) (e.g. from 60% to 80% liqLTV)
// UNHEALTHY(repay) (e.g. from 80% to 100% liqLTV)
// we use our target cost of capital to calculate how much debt we can take on / how much debt we need to repay
// in order to bring costs back to an acceptable range
// currentProtocolDebt => total amount of debt taken by all Aave's borrowers
// maxProtocolDebt => amount of total debt at which the cost of capital is equal to our acceptable costs
// if the current protocol debt is higher than the max protocol debt, we will repay debt
(
uint256 currentProtocolDebt,
uint256 maxProtocolDebt,
uint256 targetUtilisationRay
) =
AaveLenderBorrowerLib.calcMaxDebt(
address(investmentToken),
acceptableCostsRay
);
if (targetLTV > currentLTV && currentProtocolDebt < maxProtocolDebt) {
// SUBOPTIMAL RATIO: our current Loan-to-Value is lower than what we want
// AND costs are lower than our max acceptable costs
// we need to take on more debt
uint256 targetDebtETH =
totalCollateralETH.mul(targetLTV).div(MAX_BPS);
uint256 amountToBorrowETH = targetDebtETH.sub(totalDebtETH); // safe bc we checked ratios
amountToBorrowETH = Math.min(
availableBorrowsETH,
amountToBorrowETH
);
// cap the amount of debt we are taking according to our acceptable costs
// if with the new loan we are increasing our cost of capital over what is healthy
if (currentProtocolDebt.add(amountToBorrowETH) > maxProtocolDebt) {
// Can't underflow because it's checked in the previous if condition
amountToBorrowETH = maxProtocolDebt.sub(currentProtocolDebt);
}
uint256 maxTotalBorrowETH =
_toETH(maxTotalBorrowIT, address(investmentToken));
if (totalDebtETH.add(amountToBorrowETH) > maxTotalBorrowETH) {
amountToBorrowETH = maxTotalBorrowETH > totalDebtETH
? maxTotalBorrowETH.sub(totalDebtETH)
: 0;
}
// convert to InvestmentToken
uint256 amountToBorrowIT =
_fromETH(amountToBorrowETH, address(investmentToken));
if (amountToBorrowIT > 0) {
_lendingPool().borrow(
address(investmentToken),
amountToBorrowIT,
2,
referral,
address(this)
);
}
} else if (
currentLTV > warningLTV || currentProtocolDebt > maxProtocolDebt
) {
// UNHEALTHY RATIO
// we may be in this case if the current cost of capital is higher than our max cost of capital
// we repay debt to set it to targetLTV
uint256 targetDebtETH =
targetLTV.mul(totalCollateralETH).div(MAX_BPS);
uint256 amountToRepayETH =
targetDebtETH < totalDebtETH
? totalDebtETH.sub(targetDebtETH)
: 0;
if (maxProtocolDebt == 0) {
amountToRepayETH = totalDebtETH;
} else if (currentProtocolDebt > maxProtocolDebt) {
// NOTE: take into account that we are withdrawing from yvVault which might have a GenLender lending to Aave
// REPAY = (currentProtocolDebt - maxProtocolDebt) / (1 - TargetUtilisation)
// coming from
// TargetUtilisation = (totalDebt - REPAY) / (currentLiquidity - REPAY)
// currentLiquidity = maxProtocolDebt / TargetUtilisation
uint256 iterativeRepayAmountETH =
currentProtocolDebt
.sub(maxProtocolDebt)
.mul(WadRayMath.RAY)
.div(uint256(WadRayMath.RAY).sub(targetUtilisationRay));
amountToRepayETH = Math.max(
amountToRepayETH,
iterativeRepayAmountETH
);
}
emit RepayDebt(amountToRepayETH, totalDebtETH);
uint256 amountToRepayIT =
_fromETH(amountToRepayETH, address(investmentToken));
uint256 withdrawnIT = _withdrawFromYVault(amountToRepayIT); // we withdraw from investmentToken vault
_repayInvestmentTokenDebt(withdrawnIT); // we repay the investmentToken debt with Aave
}
uint256 balanceIT = balanceOfInvestmentToken();
if (balanceIT > 0) {
_checkAllowance(
address(yVault),
address(investmentToken),
balanceIT
);
yVault.deposit();
}
}
function liquidateAllPositions()
internal
override
returns (uint256 _amountFreed)
{
(_amountFreed, ) = liquidatePosition(estimatedTotalAssets());
}
function liquidatePosition(uint256 _amountNeeded)
internal
override
returns (uint256 _liquidatedAmount, uint256 _loss)
{
uint256 balance = balanceOfWant();
// if we have enough want to take care of the liquidatePosition without actually liquidating positons
if (balance >= _amountNeeded) {
return (_amountNeeded, 0);
}
// NOTE: amountNeeded is in want
// NOTE: repayment amount is in investmentToken
// NOTE: collateral and debt calcs are done in ETH (always, see Aave docs)
// We first repay whatever we need to repay to keep healthy ratios
uint256 amountToRepayIT = _calculateAmountToRepay(_amountNeeded);
uint256 withdrawnIT = _withdrawFromYVault(amountToRepayIT); // we withdraw from investmentToken vault
_repayInvestmentTokenDebt(withdrawnIT); // we repay the investmentToken debt with Aave
// it will return the free amount of want
_withdrawWantFromAave(_amountNeeded);
balance = balanceOfWant();
// we check if we withdrew less than expected AND should buy investmentToken with want (realising losses)
if (
_amountNeeded > balance &&
balanceOfDebt() > 0 && // still some debt remaining
balanceOfInvestmentToken().add(_valueOfInvestment()) == 0 && // but no capital to repay
!leaveDebtBehind // if set to true, the strategy will not try to repay debt by selling want
) {
// using this part of code will result in losses but it is necessary to unlock full collateral in case of wind down
// we calculate how much want we need to fulfill the want request
uint256 remainingAmountWant = _amountNeeded.sub(balance);
// then calculate how much InvestmentToken we need to unlock collateral
amountToRepayIT = _calculateAmountToRepay(remainingAmountWant);
// we buy investmentToken with Want
_buyInvestmentTokenWithWant(amountToRepayIT);
// we repay debt to actually unlock collateral
// after this, balanceOfDebt should be 0
_repayInvestmentTokenDebt(amountToRepayIT);
// then we try withdraw once more
_withdrawWantFromAave(remainingAmountWant);
}
uint256 totalAssets = balanceOfWant();
if (_amountNeeded > totalAssets) {
_liquidatedAmount = totalAssets;
_loss = _amountNeeded.sub(totalAssets);
} else {
_liquidatedAmount = _amountNeeded;
}
}
function delegatedAssets() external view override returns (uint256) {
// returns total debt borrowed in want (which is the delegatedAssets)
return
_fromETH(
_toETH(balanceOfDebt(), address(investmentToken)),
address(want)
);
}
function prepareMigration(address _newStrategy) internal override {
// nothing to do since debt cannot be migrated
}
function harvestTrigger(uint256 callCost)
public
view
override
returns (bool)
{
// we harvest if:
// 1. stakedAave is ready to be converted to Aave and sold
return
_checkCooldown() ||
super.harvestTrigger(_fromETH(callCost, address(want)));
}
function tendTrigger(uint256 callCost) public view override returns (bool) {
// we adjust position if:
// 1. LTV ratios are not in the HEALTHY range (either we take on more debt or repay debt)
// 2. costs are not acceptable and we need to repay debt
(
uint256 totalCollateralETH,
uint256 totalDebtETH,
,
uint256 currentLiquidationThreshold,
,
) = _getAaveUserAccountData();
uint256 targetLTV = _getTargetLTV(currentLiquidationThreshold);
uint256 warningLTV = _getWarningLTV(currentLiquidationThreshold);
return
AaveLenderBorrowerLib.shouldRebalance(
address(investmentToken),
acceptableCostsRay,
targetLTV,
warningLTV,
totalCollateralETH,
totalDebtETH
);
}
// ----------------- INTERNAL FUNCTIONS SUPPORT -----------------
function _withdrawFromYVault(uint256 _amountIT) internal returns (uint256) {
if (_amountIT == 0) {
return 0;
}
// no need to check allowance bc the contract == token
uint256 balancePrior = balanceOfInvestmentToken();
uint256 sharesToWithdraw =
Math.min(
_investmentTokenToYShares(_amountIT),
yVault.balanceOf(address(this))
);
if (sharesToWithdraw == 0) {
return 0;
}
yVault.withdraw(sharesToWithdraw, address(this), maxLoss);
return balanceOfInvestmentToken().sub(balancePrior);
}
function _repayInvestmentTokenDebt(uint256 amount) internal {
if (amount == 0) {
return;
}
// we cannot pay more than loose balance
amount = Math.min(amount, balanceOfInvestmentToken());
// we cannot pay more than we owe
amount = Math.min(amount, balanceOfDebt());
_checkAllowance(
address(_lendingPool()),
address(investmentToken),
amount
);
if (amount > 0) {
_lendingPool().repay(
address(investmentToken),
amount,
uint256(2),
address(this)
);
}
}
function _claimRewards() internal {
if (isInvestmentTokenIncentivised || isWantIncentivised) {
// redeem AAVE from stkAave
uint256 stkAaveBalance =
IERC20(address(stkAave)).balanceOf(address(this));
if (stkAaveBalance > 0 && _checkCooldown()) {
// claim AAVE rewards
stkAave.claimRewards(address(this), type(uint256).max);
stkAave.redeem(address(this), stkAaveBalance);
}
// sell AAVE for want
// a minimum balance of 0.01 AAVE is required
uint256 aaveBalance = IERC20(AAVE).balanceOf(address(this));
if (aaveBalance > 1e15) {
_sellAForB(aaveBalance, address(AAVE), address(want));
}
// claim rewards
// only add to assets those assets that are incentivised
address[] memory assets;
if (isInvestmentTokenIncentivised && isWantIncentivised) {
assets = new address[](2);
assets[0] = address(aToken);
assets[1] = address(variableDebtToken);
} else if (isInvestmentTokenIncentivised) {
assets = new address[](1);
assets[0] = address(variableDebtToken);
} else if (isWantIncentivised) {
assets = new address[](1);
assets[0] = address(aToken);
}
_incentivesController().claimRewards(
assets,
type(uint256).max,
address(this)
);
// request start of cooldown period
uint256 cooldownStartTimestamp =
IStakedAave(stkAave).stakersCooldowns(address(this));
uint256 COOLDOWN_SECONDS = IStakedAave(stkAave).COOLDOWN_SECONDS();
uint256 UNSTAKE_WINDOW = IStakedAave(stkAave).UNSTAKE_WINDOW();
if (
IERC20(address(stkAave)).balanceOf(address(this)) > 0 &&
(cooldownStartTimestamp == 0 ||
block.timestamp >
cooldownStartTimestamp.add(COOLDOWN_SECONDS).add(
UNSTAKE_WINDOW
))
) {
stkAave.cooldown();
}
}
}
//withdraw an amount including any want balance
function _withdrawWantFromAave(uint256 amount) internal {
uint256 balanceUnderlying = balanceOfAToken();
if (amount > balanceUnderlying) {
amount = balanceUnderlying;
}
uint256 maxWithdrawal =
Math.min(_maxWithdrawal(), want.balanceOf(address(aToken)));
uint256 toWithdraw = Math.min(amount, maxWithdrawal);
if (toWithdraw > 0) {
_checkAllowance(
address(_lendingPool()),
address(aToken),
toWithdraw
);
_lendingPool().withdraw(address(want), toWithdraw, address(this));
}
}
function _maxWithdrawal() internal view returns (uint256) {
(uint256 totalCollateralETH, uint256 totalDebtETH, , , uint256 ltv, ) =
_getAaveUserAccountData();
uint256 minCollateralETH =
ltv > 0 ? totalDebtETH.mul(MAX_BPS).div(ltv) : totalCollateralETH;
if (minCollateralETH > totalCollateralETH) {
return 0;
}
return
_fromETH(totalCollateralETH.sub(minCollateralETH), address(want));
}
function _calculateAmountToRepay(uint256 amount)
internal
view
returns (uint256)
{
if (amount == 0) {
return 0;
}
// we check if the collateral that we are withdrawing leaves us in a risky range, we then take action
(
uint256 totalCollateralETH,
uint256 totalDebtETH,
,
uint256 currentLiquidationThreshold,
,
) = _getAaveUserAccountData();
uint256 warningLTV = _getWarningLTV(currentLiquidationThreshold);
uint256 targetLTV = _getTargetLTV(currentLiquidationThreshold);
uint256 amountETH = _toETH(amount, address(want));
return
AaveLenderBorrowerLib.calculateAmountToRepay(
amountETH,
totalCollateralETH,
totalDebtETH,
warningLTV,
targetLTV,
address(investmentToken),
minThreshold
);
}
function _depositToAave(uint256 amount) internal {
if (amount == 0) {
return;
}
ILendingPool lp = _lendingPool();
_checkAllowance(address(lp), address(want), amount);
lp.deposit(address(want), amount, address(this), referral);
}
function _checkCooldown() internal view returns (bool) {
return
AaveLenderBorrowerLib.checkCooldown(
isWantIncentivised,
isInvestmentTokenIncentivised,
address(stkAave)
);
}
function _checkAllowance(
address _contract,
address _token,
uint256 _amount
) internal {
if (IERC20(_token).allowance(address(this), _contract) < _amount) {
IERC20(_token).safeApprove(_contract, 0);
IERC20(_token).safeApprove(_contract, type(uint256).max);
}
}
function _takeVaultProfit() internal {
uint256 _debt = balanceOfDebt();
uint256 _valueInVault = _valueOfInvestment();
if (_debt >= _valueInVault) {
return;
}
uint256 profit = _valueInVault.sub(_debt);
uint256 ySharesToWithdraw = _investmentTokenToYShares(profit);
if (ySharesToWithdraw > 0) {
yVault.withdraw(ySharesToWithdraw, address(this), maxLoss);
_sellAForB(
balanceOfInvestmentToken(),
address(investmentToken),
address(want)
);
}
}
// ----------------- INTERNAL CALCS -----------------
function balanceOfWant() internal view returns (uint256) {
return want.balanceOf(address(this));
}
function balanceOfInvestmentToken() internal view returns (uint256) {
return investmentToken.balanceOf(address(this));
}
function balanceOfAToken() internal view returns (uint256) {
return aToken.balanceOf(address(this));
}
function balanceOfDebt() internal view returns (uint256) {
return variableDebtToken.balanceOf(address(this));
}
function _valueOfInvestment() internal view returns (uint256) {
return
yVault.balanceOf(address(this)).mul(yVault.pricePerShare()).div(
10**yVault.decimals()
);
}
function _investmentTokenToYShares(uint256 amount)
internal
view
returns (uint256)
{
return amount.mul(10**yVault.decimals()).div(yVault.pricePerShare());
}
function _getAaveUserAccountData()
internal
view
returns (
uint256 totalCollateralETH,
uint256 totalDebtETH,
uint256 availableBorrowsETH,
uint256 currentLiquidationThreshold,
uint256 ltv,
uint256 healthFactor
)
{
return _lendingPool().getUserAccountData(address(this));
}
function _getTargetLTV(uint256 liquidationThreshold)
internal
view
returns (uint256)
{
return
liquidationThreshold.mul(uint256(targetLTVMultiplier)).div(MAX_BPS);
}
function _getWarningLTV(uint256 liquidationThreshold)
internal
view
returns (uint256)
{
return
liquidationThreshold.mul(uint256(warningLTVMultiplier)).div(
MAX_BPS
);
}
// ----------------- TOKEN CONVERSIONS -----------------
function getTokenOutPath(address _token_in, address _token_out)
internal
pure
returns (address[] memory _path)
{
bool is_weth =
_token_in == address(WETH) || _token_out == address(WETH);
_path = new address[](is_weth ? 2 : 3);
_path[0] = _token_in;
if (is_weth) {
_path[1] = _token_out;
} else {
_path[1] = address(WETH);
_path[2] = _token_out;
}
}
function _sellAForB(
uint256 _amount,
address tokenA,
address tokenB
) internal {
if (_amount == 0 || tokenA == tokenB) {
return;
}
_checkAllowance(address(router), tokenA, _amount);
router.swapExactTokensForTokens(
_amount,
0,
getTokenOutPath(tokenA, tokenB),
address(this),
now
);
}
function _buyInvestmentTokenWithWant(uint256 _amount) internal {
if (_amount == 0 || address(investmentToken) == address(want)) {
return;
}
_checkAllowance(address(router), address(want), _amount);
router.swapTokensForExactTokens(
_amount,
type(uint256).max,
getTokenOutPath(address(want), address(investmentToken)),
address(this),
now
);
}
function _toETH(uint256 _amount, address asset)
internal
view
returns (uint256)
{
if (
_amount == 0 ||
_amount == type(uint256).max ||
address(asset) == address(WETH) // 1:1 change
) {
return _amount;
}
return AaveLenderBorrowerLib.toETH(_amount, asset);
}
function ethToWant(uint256 _amtInWei)
public
view
override
returns (uint256)
{
return _fromETH(_amtInWei, address(want));
}
function _fromETH(uint256 _amount, address asset)
internal
view
returns (uint256)
{
if (
_amount == 0 ||
_amount == type(uint256).max ||
address(asset) == address(WETH) // 1:1 change
) {
return _amount;
}
return AaveLenderBorrowerLib.fromETH(_amount, asset);
}
// ----------------- INTERNAL SUPPORT GETTERS -----------------
function _lendingPool() internal view returns (ILendingPool lendingPool) {
return AaveLenderBorrowerLib.lendingPool();
}
function _protocolDataProvider()
internal
view
returns (IProtocolDataProvider protocolDataProvider)
{
return AaveLenderBorrowerLib.protocolDataProvider;
}
function _priceOracle() internal view returns (IPriceOracle) {
return AaveLenderBorrowerLib.priceOracle();
}
function _incentivesController()
internal
view
returns (IAaveIncentivesController)
{
return
AaveLenderBorrowerLib.incentivesController(
aToken,
variableDebtToken,
isWantIncentivised,
isInvestmentTokenIncentivised
);
}
function protectedTokens()
internal
view
override
returns (address[] memory)
{}
}
// File: AaveLenderBorrowerCloner.sol
contract AaveLenderBorrowerCloner {
address public immutable original;
event Cloned(address indexed clone);
event Deployed(address indexed original);
constructor(
address _vault,
address _yVault,
bool _isWantIncentivised,
bool _isInvestmentTokenIncentivised,
string memory _strategyName
) public {
Strategy _original = new Strategy(_vault, _yVault, _strategyName);
emit Deployed(address(_original));
original = address(_original);
Strategy(_original).setStrategyParams(
4_000, // targetLTVMultiplier (default: 4_000)
6_000, // warningLTVMultiplier default: 6_000
1e27, // acceptableCosts (default: 1e27)
7, // default: 7 (Yearn Aave Referal code)
type(uint256).max, // 2**256-1
_isWantIncentivised,
_isInvestmentTokenIncentivised,
false, // leave debt behind (default: false)
1 // maxLoss (default: 1)
);
Strategy(_original).setRewards(msg.sender);
Strategy(_original).setKeeper(msg.sender);
Strategy(_original).setStrategist(msg.sender);
}
function name() external pure returns (string memory) {
return "[email protected]";
}
function cloneAaveLenderBorrower(
address _vault,
address _strategist,
address _rewards,
address _keeper,
address _yVault,
bool _isWantIncentivised,
bool _isInvestmentTokenIncentivised,
string memory _strategyName
) external returns (address newStrategy) {
// Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol
bytes20 addressBytes = bytes20(original);
assembly {
// EIP-1167 bytecode
let clone_code := mload(0x40)
mstore(
clone_code,
0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000
)
mstore(add(clone_code, 0x14), addressBytes)
mstore(
add(clone_code, 0x28),
0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000
)
newStrategy := create(0, clone_code, 0x37)
}
Strategy(newStrategy).initialize(_vault, _yVault, _strategyName);
Strategy(newStrategy).setStrategyParams(
4_000, // targetLTVMultiplier (default: 4_000)
6_000, // warningLTVMultiplier default: 6_000
1e27, // acceptableCosts (default: 1e27)
7, // default: 7 (Yearn Aave Referal code)
type(uint256).max, // max debt to take
_isWantIncentivised,
_isInvestmentTokenIncentivised,
false, // leave debt behind (default: false)
1 // maxLoss (default: 1)
);
Strategy(newStrategy).setKeeper(_keeper);
Strategy(newStrategy).setRewards(_rewards);
Strategy(newStrategy).setStrategist(_strategist);
emit Cloned(newStrategy);
}
}
|
we adjust position if: 1. LTV ratios are not in the HEALTHY range (either we take on more debt or repay debt) 2. costs are not acceptable and we need to repay debt
|
function tendTrigger(uint256 callCost) public view override returns (bool) {
(
uint256 totalCollateralETH,
uint256 totalDebtETH,
,
uint256 currentLiquidationThreshold,
,
) = _getAaveUserAccountData();
uint256 targetLTV = _getTargetLTV(currentLiquidationThreshold);
uint256 warningLTV = _getWarningLTV(currentLiquidationThreshold);
return
AaveLenderBorrowerLib.shouldRebalance(
address(investmentToken),
acceptableCostsRay,
targetLTV,
warningLTV,
totalCollateralETH,
totalDebtETH
);
}
| 1,105,761 |
/**
Copyright (c) 2018, ZSC Dev Team
2018-10-19: v0.00.01
*/
pragma solidity ^0.4.25;
// pragma experimental ABIEncoderV2;
contract Delegate {
uint private sum_;
mapping (uint => address) private addrs_;
/** @desc prioritie map.
* == 0: invalid
* == 1: ownable
* >= 2: define by user
*/
mapping (uint => uint) private prios_;
mapping (address => uint) private ids_;
mapping (address => bool) private exists_;
modifier _onlyOwner() {
require(exists_[msg.sender]);
require(0 == ids_[msg.sender]);
require(addrs_[0] == msg.sender);
require(1 == prios_[0]);
_;
}
constructor() public {
addrs_[0] = msg.sender;
prios_[0] = 1;
ids_[msg.sender] = 0;
exists_[msg.sender] = true;
sum_ = 1;
}
function kill() public _onlyOwner {
selfdestruct(addrs_[0]);
}
function _update(address _addr, uint _prio) private {
uint id;
if (exists_[_addr]) {
id = ids_[_addr];
// addrs_[id] = _addr;
prios_[id] = _prio;
} else {
id = sum_;
exists_[_addr] = true;
ids_[_addr] = id;
addrs_[id] = _addr;
prios_[id] = _prio;
sum_ ++;
}
}
function _swap(address _addr1, uint _id2) private {
uint prio1 = 0;
uint id1 = 0;
address addr2 = 0;
uint prio2 = 0;
addr2 = addrs_[_id2];
prio2 = prios_[_id2];
// _id2;
// _addr1
id1 = ids_[_addr1];
prio1 = prios_[id1];
addrs_[id1] = addr2;
prios_[id1] = prio2;
ids_[addr2] = id1;
addrs_[_id2] = _addr1;
prios_[_id2] = prio1;
ids_[_addr1] = _id2;
}
function checkDelegate(address _addr, uint _prio) public view returns (bool) {
if (_addr == address(this)) return true;
if (0 == _prio) return false;
if (!exists_[_addr]) return false;
uint id = ids_[_addr];
return (prios_[id] != 0 && prios_[id] <= _prio);
}
// This unnamed function is called whenever someone tries to send ether to it
function() external payable { revert(); }
function transferOwnership(address _newOwner, uint _degradePrio) external _onlyOwner {
require(0 != _newOwner);
require(addrs_[0] != _newOwner);
require(1 < _degradePrio);
// upgrade new owner
_update(_newOwner, 1);
// _swap old owner and new owner
uint newOwnerId = ids_[_newOwner];
address owner = addrs_[0];
_swap(_newOwner, 0);
require(0 == ids_[_newOwner]);
require(newOwnerId == ids_[owner]);
// degrade old owner
prios_[ids_[owner]] = _degradePrio;
}
function updateDelegate(address _addr, uint _prio) external _onlyOwner {
if (address(this) == _addr) return;
// owner's priority can't be changed
require(addrs_[0] != _addr);
// invalid priority and owner's priority can't be set
require(1 < _prio);
_update(_addr, _prio);
}
function removeDelegate(address _addr) external _onlyOwner {
if (address(this) == _addr) return;
// owner's priority can't be remove
require(addrs_[0] != _addr);
require(0 < sum_);
require(exists_[_addr]);
uint id1 = ids_[_addr];
address addr2 = addrs_[sum_-1];
_swap(_addr, sum_-1);
require((sum_-1) == ids_[_addr]);
require(id1 == ids_[addr2]);
delete addrs_[sum_-1];
delete prios_[sum_-1];
delete ids_[_addr];
sum_ --;
exists_[_addr] = false;
}
function numberOfDelegates() external view returns (uint) {
return sum_;
}
function getDelegateById(uint _id) external view returns (address, uint) {
require(_id < sum_);
require(exists_[addrs_[_id]]);
require(ids_[addrs_[_id]] == _id);
return (addrs_[_id], prios_[_id]);
}
}
|
owner's priority can't be remove
|
function removeDelegate(address _addr) external _onlyOwner {
if (address(this) == _addr) return;
require(addrs_[0] != _addr);
require(0 < sum_);
require(exists_[_addr]);
uint id1 = ids_[_addr];
address addr2 = addrs_[sum_-1];
_swap(_addr, sum_-1);
require((sum_-1) == ids_[_addr]);
require(id1 == ids_[addr2]);
delete addrs_[sum_-1];
delete prios_[sum_-1];
delete ids_[_addr];
sum_ --;
exists_[_addr] = false;
}
| 15,816,701 |
pragma solidity ^0.5.0;
import 'openzeppelin-solidity/contracts/ownership/Ownable.sol';
/// @title A contract to store proof of documents and verify their existence
/// @author John H. Yu
/// @notice This is an assignment from ConsenSys Academy Blockchain Developer Bootcamp Spring 2019 course
/// @dev Proof can be calculated offline to save gas
contract ProofOfExistence is Ownable {
/**
* @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);
/// @dev event emitted when notarize is called and succeeded
event Notarized(address indexed owner, bytes32 indexed proof, uint time,
string name, bytes32 tags, uint size, bytes32 contentType);
bool private _paused;
/// @dev struct save file/doc details
struct DocInfo {
string name;
bytes32 tags;
uint time;
uint size;
bytes32 contentType;
address creator;
}
/// @dev mapping store file/doc details per proof.
mapping (bytes32 => DocInfo) public proofDocInfo;
/// @dev mapping store proofs owned per account.
mapping (address => bytes32[]) public acountProofs;
constructor () public {
_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 owner to pause, triggers stopped state.
*/
function pause() public onlyOwner whenNotPaused {
_paused = true;
emit Paused(msg.sender);
}
/**
* @dev Called by owner to unpause, returns to normal state.
*/
function unpause() public onlyOwner whenPaused {
_paused = false;
emit Unpaused(msg.sender);
}
// calculate and store the proof for a document
/// @notice Notarize data of a document
/// @dev This function burns a lot of gas. Consider calculate the hash offline then submit it using [addProof]
/// @param name the name of the document
/// @param tags the tags of the document
/// @param size the size of the document
/// @param contentType the content type of the document
/// @param document the content of the document
/// @return true if a new proof is stored.
function notarize(string calldata name, bytes32 tags,
uint size, bytes32 contentType, string calldata document)
external
whenNotPaused
returns (bool)
{
bytes32 proof = proofFor(document);
if (hasProof(proof)){
revert("This document has been Notarized before!");
}
//store proof info. so later anyone can retrieve info abouta notarize file.
proofDocInfo[proof].name = name;
proofDocInfo[proof].tags = tags;
proofDocInfo[proof].time = now;
proofDocInfo[proof].size = size;
proofDocInfo[proof].contentType = contentType;
proofDocInfo[proof].creator = msg.sender;
//group all proofs belonged to a user together
acountProofs[msg.sender].push(proof);
emit Notarized(msg.sender, proof, proofDocInfo[proof].time, name, tags, size, contentType);
return true;
}
// helper function to get a document's keccak256
/// @notice caculate keccak256 of a document from its data
/// @dev keccak256 is a variation of SHA3, different from NIST-SHA3
/// @param document the content of the document
/// @return the proof in bytes32
function proofFor(string memory document)
public
pure
returns (bytes32)
{
return keccak256(bytes(document));
}
// verify if a document has been notarized
/// @notice verify whether a document is notarized
/// @dev ToDo
/// @param document the content of the document
/// @return boolean indicate whether the proof exist or not
function verify(string memory document)
public
view
returns (bool)
{
bytes32 proof = proofFor(document);
return hasProof(proof);
}
// returns true if proof is stored
/// @notice query a proof from storage
/// @param proof a bytes32 hash
/// @return boolean indicate whether the proof is stored or not
function hasProof(bytes32 proof)
internal
view
returns(bool)
{
return proofDocInfo[proof].creator != address(0);
}
/// @notice return all proofs done by current account
/// @return proofs a bytes32 array
function getAllProofs()
external
view
returns(bytes32[] memory proofs)
{
return acountProofs[msg.sender];
}
}
|
Returns true if the contract is paused, and false otherwise./
|
function paused() public view returns (bool) {
return _paused;
}
| 13,021,560 |
pragma solidity 0.4.26;
import "../../ETO/ETOCommitment.sol";
contract MockETOCommitment is
ETOCommitment
{
////////////////////////
// Constructor
////////////////////////
/// anyone may be a deployer, the platform acknowledges the contract by adding it to Universe Commitment collection
constructor(
Universe universe,
address nominee,
address companyLegalRep,
ETOTerms etoTerms,
IEquityToken equityToken
)
ETOCommitment(
universe,
nominee,
companyLegalRep,
etoTerms,
equityToken
)
public
{
}
////////////////////////
// Mocked functions
////////////////////////
// moves all timestamps towards the past
function _mockShiftBackTime(uint256 delta) public {
for(uint256 ii = 0; ii<_pastStateTransitionTimes.length; ii += 1) {
if(_pastStateTransitionTimes[ii] > 0) {
assert(_pastStateTransitionTimes[ii] >= delta);
_pastStateTransitionTimes[ii] -= uint32(delta);
}
}
}
// convenience function for moving all timestampts towards the past
// such that the next state transition will occur in delta seconds
// @dev maximum to be shifted is to three days before state transition
function _shiftToBeforeNextState(uint32 delta) public {
require(delta < 86400, "NF_MOCK_INVALID_DELTA");
ETOState s = state();
uint256 nextTransition = startOfInternal(ETOState(uint(s) + 1));
require(nextTransition != 0 && nextTransition > now + delta, "NF_MOCK_INVALID_TRANSITION_TIME");
_mockShiftBackTime(nextTransition - now - delta);
// generate set start date if still in setup
if (s == ETOState.Setup) {
emit LogETOStartDateSet(msg.sender, nextTransition, nextTransition - delta);
}
}
function _mockPastTime(uint256 idx, uint256 timestamp) public {
_pastStateTransitionTimes[idx] = uint32(timestamp);
}
function _mockStartDate(
ETOTerms etoTerms,
IEquityToken equityToken,
uint256 startDate,
uint256 logStartDate
)
external
{
assert(startDate < 0xFFFFFFFF);
uint256 startAt = startOfInternal(ETOState.Whitelist);
EQUITY_TOKEN = equityToken;
runStateMachine(uint32(startDate));
if (startAt == 0) {
// log set terms only once
emit LogTermsSet(msg.sender, address(etoTerms), address(equityToken));
}
emit LogETOStartDateSet(msg.sender, startAt, logStartDate);
}
//
// Override IAgreement internal interface to allow mocking up agreements for fixtures
//
function mCanAmend(address /*legalRepresentative*/)
internal
returns (bool)
{
return true;
}
}
|
convenience function for moving all timestampts towards the past such that the next state transition will occur in delta seconds maximum to be shifted is to three days before state transition generate set start date if still in setup
|
function _shiftToBeforeNextState(uint32 delta) public {
require(delta < 86400, "NF_MOCK_INVALID_DELTA");
ETOState s = state();
uint256 nextTransition = startOfInternal(ETOState(uint(s) + 1));
require(nextTransition != 0 && nextTransition > now + delta, "NF_MOCK_INVALID_TRANSITION_TIME");
_mockShiftBackTime(nextTransition - now - delta);
if (s == ETOState.Setup) {
emit LogETOStartDateSet(msg.sender, nextTransition, nextTransition - delta);
}
}
| 895,510 |
./partial_match/97/0x87c9dBb354Ab2055E7183F3CE82b0358a00Ea4a4/sources/GpesMasterFarmer.sol
|
lock 95% of reward if it come from bounus time
|
function _harvest(uint256 _pid) internal {
PoolInfo storage pool = poolInfo[_pid];
UserInfo storage user = userInfo[_pid][msg.sender];
if (user.amount > 0) {
uint256 pending = user.amount.mul(pool.accGpesPerShare).div(1e12).sub(user.rewardDebt);
uint256 masterBal = Gpes.balanceOf(address(this));
if (pending > masterBal) {
pending = masterBal;
}
if(pending > 0) {
Gpes.transfer(msg.sender, pending);
uint256 lockAmount = 0;
if (user.rewardDebtAtBlock <= FINISH_BONUS_AT_BLOCK) {
lockAmount = pending.mul(PERCENT_LOCK_BONUS_REWARD).div(100);
Gpes.lock(msg.sender, lockAmount);
}
user.rewardDebtAtBlock = block.number;
emit SendGpesReward(msg.sender, _pid, pending, lockAmount);
}
user.rewardDebt = user.amount.mul(pool.accGpesPerShare).div(1e12);
}
}
| 11,407,463 |
pragma solidity ^0.4.24;
// File: openzeppelin-zos/contracts/introspection/ERC165.sol
/**
* @title ERC165
* @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md
*/
interface ERC165 {
/**
* @notice Query if a contract implements an interface
* @param _interfaceId The interface identifier, as specified in ERC-165
* @dev Interface identification is specified in ERC-165. This function
* uses less than 30,000 gas.
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool);
}
// File: openzeppelin-zos/contracts/token/ERC721/ERC721Basic.sol
/**
* @title ERC721 Non-Fungible Token Standard basic interface
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Basic is ERC165 {
event Transfer(
address indexed _from,
address indexed _to,
uint256 indexed _tokenId
);
event Approval(
address indexed _owner,
address indexed _approved,
uint256 indexed _tokenId
);
event ApprovalForAll(
address indexed _owner,
address indexed _operator,
bool _approved
);
function balanceOf(address _owner) public view returns (uint256 _balance);
function ownerOf(uint256 _tokenId) public view returns (address _owner);
function exists(uint256 _tokenId) public view returns (bool _exists);
function approve(address _to, uint256 _tokenId) public;
function getApproved(uint256 _tokenId)
public view returns (address _operator);
function setApprovalForAll(address _operator, bool _approved) public;
function isApprovedForAll(address _owner, address _operator)
public view returns (bool);
function transferFrom(address _from, address _to, uint256 _tokenId) public;
function safeTransferFrom(address _from, address _to, uint256 _tokenId)
public;
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public;
}
// File: openzeppelin-zos/contracts/token/ERC721/ERC721.sol
/**
* @title ERC-721 Non-Fungible Token Standard, optional enumeration extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Enumerable is ERC721Basic {
function totalSupply() public view returns (uint256);
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256 _tokenId);
function tokenByIndex(uint256 _index) public view returns (uint256);
}
/**
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Metadata is ERC721Basic {
function name() external view returns (string _name);
function symbol() external view returns (string _symbol);
function tokenURI(uint256 _tokenId) public view returns (string);
}
/**
* @title ERC-721 Non-Fungible Token Standard, full implementation interface
* @dev See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721 is ERC721Basic, ERC721Enumerable, ERC721Metadata {
}
// File: openzeppelin-zos/contracts/token/ERC721/ERC721Receiver.sol
/**
* @title ERC721 token receiver interface
* @dev Interface for any contract that wants to support safeTransfers
* from ERC721 asset contracts.
*/
contract ERC721Receiver {
/**
* @dev Magic value to be returned upon successful reception of an NFT
* Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`,
* which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
*/
bytes4 internal constant ERC721_RECEIVED = 0x150b7a02;
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transfered
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
returns(bytes4);
}
// File: openzeppelin-zos/contracts/math/SafeMath.sol
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
// File: openzeppelin-zos/contracts/AddressUtils.sol
/**
* Utility library of inline functions on addresses
*/
library AddressUtils {
/**
* Returns whether the target address is a contract
* @dev This function will return false if invoked during the constructor of a contract,
* as the code is not actually created until after the constructor finishes.
* @param addr address to check
* @return whether the target address is a contract
*/
function isContract(address addr) internal view returns (bool) {
uint256 size;
// XXX Currently there is no better way to check if there is a contract in an address
// than to check the size of the code at that address.
// See https://ethereum.stackexchange.com/a/14016/36603
// for more details about how this works.
// TODO Check this again before the Serenity release, because all addresses will be
// contracts then.
assembly { size := extcodesize(addr) } // solium-disable-line security/no-inline-assembly
return size > 0;
}
}
// File: openzeppelin-zos/contracts/introspection/ERC165Support.sol
/**
* @title ERC165Support
* @dev Implements ERC165 returning true for ERC165 interface identifier
*/
contract ERC165Support is ERC165 {
bytes4 internal constant InterfaceId_ERC165 = 0x01ffc9a7;
/**
* 0x01ffc9a7 ===
* bytes4(keccak256('supportsInterface(bytes4)'))
*/
function supportsInterface(bytes4 _interfaceId)
external
view
returns (bool)
{
return _supportsInterface(_interfaceId);
}
function _supportsInterface(bytes4 _interfaceId)
internal
view
returns (bool)
{
return _interfaceId == InterfaceId_ERC165;
}
}
// File: openzeppelin-zos/contracts/token/ERC721/ERC721BasicToken.sol
/**
* @title ERC721 Non-Fungible Token Standard basic implementation
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721BasicToken is ERC165Support, ERC721Basic {
bytes4 private constant InterfaceId_ERC721 = 0x80ac58cd;
/*
* 0x80ac58cd ===
* bytes4(keccak256('balanceOf(address)')) ^
* bytes4(keccak256('ownerOf(uint256)')) ^
* bytes4(keccak256('approve(address,uint256)')) ^
* bytes4(keccak256('getApproved(uint256)')) ^
* bytes4(keccak256('setApprovalForAll(address,bool)')) ^
* bytes4(keccak256('isApprovedForAll(address,address)')) ^
* bytes4(keccak256('transferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256)')) ^
* bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)'))
*/
bytes4 private constant InterfaceId_ERC721Exists = 0x4f558e79;
/*
* 0x4f558e79 ===
* bytes4(keccak256('exists(uint256)'))
*/
using SafeMath for uint256;
using AddressUtils for address;
// Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
// which can be also obtained as `ERC721Receiver(0).onERC721Received.selector`
bytes4 private constant ERC721_RECEIVED = 0x150b7a02;
// Mapping from token ID to owner
mapping (uint256 => address) internal tokenOwner;
// Mapping from token ID to approved address
mapping (uint256 => address) internal tokenApprovals;
// Mapping from owner to number of owned token
mapping (address => uint256) internal ownedTokensCount;
// Mapping from owner to operator approvals
mapping (address => mapping (address => bool)) internal operatorApprovals;
/**
* @dev Guarantees msg.sender is owner of the given token
* @param _tokenId uint256 ID of the token to validate its ownership belongs to msg.sender
*/
modifier onlyOwnerOf(uint256 _tokenId) {
require(ownerOf(_tokenId) == msg.sender);
_;
}
/**
* @dev Checks msg.sender can transfer a token, by being owner, approved, or operator
* @param _tokenId uint256 ID of the token to validate
*/
modifier canTransfer(uint256 _tokenId) {
require(isApprovedOrOwner(msg.sender, _tokenId));
_;
}
function _supportsInterface(bytes4 _interfaceId)
internal
view
returns (bool)
{
return super._supportsInterface(_interfaceId) ||
_interfaceId == InterfaceId_ERC721 || _interfaceId == InterfaceId_ERC721Exists;
}
/**
* @dev Gets the balance of the specified address
* @param _owner address to query the balance of
* @return uint256 representing the amount owned by the passed address
*/
function balanceOf(address _owner) public view returns (uint256) {
require(_owner != address(0));
return ownedTokensCount[_owner];
}
/**
* @dev Gets the owner of the specified token ID
* @param _tokenId uint256 ID of the token to query the owner of
* @return owner address currently marked as the owner of the given token ID
*/
function ownerOf(uint256 _tokenId) public view returns (address) {
address owner = tokenOwner[_tokenId];
require(owner != address(0));
return owner;
}
/**
* @dev Returns whether the specified token exists
* @param _tokenId uint256 ID of the token to query the existence of
* @return whether the token exists
*/
function exists(uint256 _tokenId) public view returns (bool) {
address owner = tokenOwner[_tokenId];
return owner != address(0);
}
/**
* @dev Approves another address to transfer the given token ID
* The zero address indicates there is no approved address.
* There can only be one approved address per token at a given time.
* Can only be called by the token owner or an approved operator.
* @param _to address to be approved for the given token ID
* @param _tokenId uint256 ID of the token to be approved
*/
function approve(address _to, uint256 _tokenId) public {
address owner = ownerOf(_tokenId);
require(_to != owner);
require(msg.sender == owner || isApprovedForAll(owner, msg.sender));
tokenApprovals[_tokenId] = _to;
emit Approval(owner, _to, _tokenId);
}
/**
* @dev Gets the approved address for a token ID, or zero if no address set
* @param _tokenId uint256 ID of the token to query the approval of
* @return address currently approved for the given token ID
*/
function getApproved(uint256 _tokenId) public view returns (address) {
return tokenApprovals[_tokenId];
}
/**
* @dev Sets or unsets the approval of a given operator
* An operator is allowed to transfer all tokens of the sender on their behalf
* @param _to operator address to set the approval
* @param _approved representing the status of the approval to be set
*/
function setApprovalForAll(address _to, bool _approved) public {
require(_to != msg.sender);
operatorApprovals[msg.sender][_to] = _approved;
emit ApprovalForAll(msg.sender, _to, _approved);
}
/**
* @dev Tells whether an operator is approved by a given owner
* @param _owner owner address which you want to query the approval of
* @param _operator operator address which you want to query the approval of
* @return bool whether the given operator is approved by the given owner
*/
function isApprovedForAll(
address _owner,
address _operator
)
public
view
returns (bool)
{
return operatorApprovals[_owner][_operator];
}
/**
* @dev Transfers the ownership of a given token ID to another address
* Usage of this method is discouraged, use `safeTransferFrom` whenever possible
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
require(_from != address(0));
require(_to != address(0));
clearApproval(_from, _tokenId);
removeTokenFrom(_from, _tokenId);
addTokenTo(_to, _tokenId);
emit Transfer(_from, _to, _tokenId);
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
*
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId
)
public
canTransfer(_tokenId)
{
// solium-disable-next-line arg-overflow
safeTransferFrom(_from, _to, _tokenId, "");
}
/**
* @dev Safely transfers the ownership of a given token ID to another address
* If the target address is a contract, it must implement `onERC721Received`,
* which is called upon a safe transfer, and return the magic value
* `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise,
* the transfer is reverted.
* Requires the msg sender to be the owner, approved, or operator
* @param _from current owner of the token
* @param _to address to receive the ownership of the given token ID
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes data to send along with a safe transfer check
*/
function safeTransferFrom(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
public
canTransfer(_tokenId)
{
transferFrom(_from, _to, _tokenId);
// solium-disable-next-line arg-overflow
require(checkAndCallSafeTransfer(_from, _to, _tokenId, _data));
}
/**
* @dev Returns whether the given spender can transfer a given token ID
* @param _spender address of the spender to query
* @param _tokenId uint256 ID of the token to be transferred
* @return bool whether the msg.sender is approved for the given token ID,
* is an operator of the owner, or is the owner of the token
*/
function isApprovedOrOwner(
address _spender,
uint256 _tokenId
)
internal
view
returns (bool)
{
address owner = ownerOf(_tokenId);
// Disable solium check because of
// https://github.com/duaraghav8/Solium/issues/175
// solium-disable-next-line operator-whitespace
return (
_spender == owner ||
getApproved(_tokenId) == _spender ||
isApprovedForAll(owner, _spender)
);
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to The address that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
require(_to != address(0));
addTokenTo(_to, _tokenId);
emit Transfer(address(0), _to, _tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
clearApproval(_owner, _tokenId);
removeTokenFrom(_owner, _tokenId);
emit Transfer(_owner, address(0), _tokenId);
}
/**
* @dev Internal function to clear current approval of a given token ID
* Reverts if the given address is not indeed the owner of the token
* @param _owner owner of the token
* @param _tokenId uint256 ID of the token to be transferred
*/
function clearApproval(address _owner, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _owner);
if (tokenApprovals[_tokenId] != address(0)) {
tokenApprovals[_tokenId] = address(0);
}
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
require(tokenOwner[_tokenId] == address(0));
tokenOwner[_tokenId] = _to;
ownedTokensCount[_to] = ownedTokensCount[_to].add(1);
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
require(ownerOf(_tokenId) == _from);
ownedTokensCount[_from] = ownedTokensCount[_from].sub(1);
tokenOwner[_tokenId] = address(0);
}
/**
* @dev Internal function to invoke `onERC721Received` on a target address
* The call is not executed if the target address is not a contract
* @param _from address representing the previous owner of the given token ID
* @param _to target address that will receive the tokens
* @param _tokenId uint256 ID of the token to be transferred
* @param _data bytes optional data to send along with the call
* @return whether the call correctly returned the expected magic value
*/
function checkAndCallSafeTransfer(
address _from,
address _to,
uint256 _tokenId,
bytes _data
)
internal
returns (bool)
{
if (!_to.isContract()) {
return true;
}
bytes4 retval = ERC721Receiver(_to).onERC721Received(
msg.sender, _from, _tokenId, _data);
return (retval == ERC721_RECEIVED);
}
}
// File: zos-lib/contracts/migrations/Migratable.sol
/**
* @title Migratable
* Helper contract to support intialization and migration schemes between
* different implementations of a contract in the context of upgradeability.
* To use it, replace the constructor with a function that has the
* `isInitializer` modifier starting with `"0"` as `migrationId`.
* When you want to apply some migration code during an upgrade, increase
* the `migrationId`. Or, if the migration code must be applied only after
* another migration has been already applied, use the `isMigration` modifier.
* This helper supports multiple inheritance.
* WARNING: It is the developer's responsibility to ensure that migrations are
* applied in a correct order, or that they are run at all.
* See `Initializable` for a simpler version.
*/
contract Migratable {
/**
* @dev Emitted when the contract applies a migration.
* @param contractName Name of the Contract.
* @param migrationId Identifier of the migration applied.
*/
event Migrated(string contractName, string migrationId);
/**
* @dev Mapping of the already applied migrations.
* (contractName => (migrationId => bool))
*/
mapping (string => mapping (string => bool)) internal migrated;
/**
* @dev Internal migration id used to specify that a contract has already been initialized.
*/
string constant private INITIALIZED_ID = "initialized";
/**
* @dev Modifier to use in the initialization function of a contract.
* @param contractName Name of the contract.
* @param migrationId Identifier of the migration.
*/
modifier isInitializer(string contractName, string migrationId) {
validateMigrationIsPending(contractName, INITIALIZED_ID);
validateMigrationIsPending(contractName, migrationId);
_;
emit Migrated(contractName, migrationId);
migrated[contractName][migrationId] = true;
migrated[contractName][INITIALIZED_ID] = true;
}
/**
* @dev Modifier to use in the migration of a contract.
* @param contractName Name of the contract.
* @param requiredMigrationId Identifier of the previous migration, required
* to apply new one.
* @param newMigrationId Identifier of the new migration to be applied.
*/
modifier isMigration(string contractName, string requiredMigrationId, string newMigrationId) {
require(isMigrated(contractName, requiredMigrationId), "Prerequisite migration ID has not been run yet");
validateMigrationIsPending(contractName, newMigrationId);
_;
emit Migrated(contractName, newMigrationId);
migrated[contractName][newMigrationId] = true;
}
/**
* @dev Returns true if the contract migration was applied.
* @param contractName Name of the contract.
* @param migrationId Identifier of the migration.
* @return true if the contract migration was applied, false otherwise.
*/
function isMigrated(string contractName, string migrationId) public view returns(bool) {
return migrated[contractName][migrationId];
}
/**
* @dev Initializer that marks the contract as initialized.
* It is important to run this if you had deployed a previous version of a Migratable contract.
* For more information see https://github.com/zeppelinos/zos-lib/issues/158.
*/
function initialize() isInitializer("Migratable", "1.2.1") public {
}
/**
* @dev Reverts if the requested migration was already executed.
* @param contractName Name of the contract.
* @param migrationId Identifier of the migration.
*/
function validateMigrationIsPending(string contractName, string migrationId) private view {
require(!isMigrated(contractName, migrationId), "Requested target migration ID has already been run");
}
}
// File: openzeppelin-zos/contracts/token/ERC721/ERC721Token.sol
/**
* @title Full ERC721 Token
* This implementation includes all the required and some optional functionality of the ERC721 standard
* Moreover, it includes approve all functionality using operator terminology
* @dev see https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md
*/
contract ERC721Token is Migratable, ERC165Support, ERC721BasicToken, ERC721 {
bytes4 private constant InterfaceId_ERC721Enumerable = 0x780e9d63;
/**
* 0x780e9d63 ===
* bytes4(keccak256('totalSupply()')) ^
* bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) ^
* bytes4(keccak256('tokenByIndex(uint256)'))
*/
bytes4 private constant InterfaceId_ERC721Metadata = 0x5b5e139f;
/**
* 0x5b5e139f ===
* bytes4(keccak256('name()')) ^
* bytes4(keccak256('symbol()')) ^
* bytes4(keccak256('tokenURI(uint256)'))
*/
// Token name
string internal name_;
// Token symbol
string internal symbol_;
// Mapping from owner to list of owned token IDs
mapping(address => uint256[]) internal ownedTokens;
// Mapping from token ID to index of the owner tokens list
mapping(uint256 => uint256) internal ownedTokensIndex;
// Array with all token ids, used for enumeration
uint256[] internal allTokens;
// Mapping from token id to position in the allTokens array
mapping(uint256 => uint256) internal allTokensIndex;
// Optional mapping for token URIs
mapping(uint256 => string) internal tokenURIs;
/**
* @dev Constructor function
*/
function initialize(string _name, string _symbol) public isInitializer("ERC721Token", "1.9.0") {
name_ = _name;
symbol_ = _symbol;
}
function _supportsInterface(bytes4 _interfaceId)
internal
view
returns (bool)
{
return super._supportsInterface(_interfaceId) ||
_interfaceId == InterfaceId_ERC721Enumerable || _interfaceId == InterfaceId_ERC721Metadata;
}
/**
* @dev Gets the token name
* @return string representing the token name
*/
function name() external view returns (string) {
return name_;
}
/**
* @dev Gets the token symbol
* @return string representing the token symbol
*/
function symbol() external view returns (string) {
return symbol_;
}
/**
* @dev Returns an URI for a given token ID
* Throws if the token ID does not exist. May return an empty string.
* @param _tokenId uint256 ID of the token to query
*/
function tokenURI(uint256 _tokenId) public view returns (string) {
require(exists(_tokenId));
return tokenURIs[_tokenId];
}
/**
* @dev Gets the token ID at a given index of the tokens list of the requested owner
* @param _owner address owning the tokens list to be accessed
* @param _index uint256 representing the index to be accessed of the requested tokens list
* @return uint256 token ID at the given index of the tokens list owned by the requested address
*/
function tokenOfOwnerByIndex(
address _owner,
uint256 _index
)
public
view
returns (uint256)
{
require(_index < balanceOf(_owner));
return ownedTokens[_owner][_index];
}
/**
* @dev Gets the total amount of tokens stored by the contract
* @return uint256 representing the total amount of tokens
*/
function totalSupply() public view returns (uint256) {
return allTokens.length;
}
/**
* @dev Gets the token ID at a given index of all the tokens in this contract
* Reverts if the index is greater or equal to the total number of tokens
* @param _index uint256 representing the index to be accessed of the tokens list
* @return uint256 token ID at the given index of the tokens list
*/
function tokenByIndex(uint256 _index) public view returns (uint256) {
require(_index < totalSupply());
return allTokens[_index];
}
/**
* @dev Internal function to set the token URI for a given token
* Reverts if the token ID does not exist
* @param _tokenId uint256 ID of the token to set its URI
* @param _uri string URI to assign
*/
function _setTokenURI(uint256 _tokenId, string _uri) internal {
require(exists(_tokenId));
tokenURIs[_tokenId] = _uri;
}
/**
* @dev Internal function to add a token ID to the list of a given address
* @param _to address representing the new owner of the given token ID
* @param _tokenId uint256 ID of the token to be added to the tokens list of the given address
*/
function addTokenTo(address _to, uint256 _tokenId) internal {
super.addTokenTo(_to, _tokenId);
uint256 length = ownedTokens[_to].length;
ownedTokens[_to].push(_tokenId);
ownedTokensIndex[_tokenId] = length;
}
/**
* @dev Internal function to remove a token ID from the list of a given address
* @param _from address representing the previous owner of the given token ID
* @param _tokenId uint256 ID of the token to be removed from the tokens list of the given address
*/
function removeTokenFrom(address _from, uint256 _tokenId) internal {
super.removeTokenFrom(_from, _tokenId);
uint256 tokenIndex = ownedTokensIndex[_tokenId];
uint256 lastTokenIndex = ownedTokens[_from].length.sub(1);
uint256 lastToken = ownedTokens[_from][lastTokenIndex];
ownedTokens[_from][tokenIndex] = lastToken;
ownedTokens[_from][lastTokenIndex] = 0;
// Note that this will handle single-element arrays. In that case, both tokenIndex and lastTokenIndex are going to
// be zero. Then we can make sure that we will remove _tokenId from the ownedTokens list since we are first swapping
// the lastToken to the first position, and then dropping the element placed in the last position of the list
ownedTokens[_from].length--;
ownedTokensIndex[_tokenId] = 0;
ownedTokensIndex[lastToken] = tokenIndex;
}
/**
* @dev Internal function to mint a new token
* Reverts if the given token ID already exists
* @param _to address the beneficiary that will own the minted token
* @param _tokenId uint256 ID of the token to be minted by the msg.sender
*/
function _mint(address _to, uint256 _tokenId) internal {
super._mint(_to, _tokenId);
allTokensIndex[_tokenId] = allTokens.length;
allTokens.push(_tokenId);
}
/**
* @dev Internal function to burn a specific token
* Reverts if the token does not exist
* @param _owner owner of the token to burn
* @param _tokenId uint256 ID of the token being burned by the msg.sender
*/
function _burn(address _owner, uint256 _tokenId) internal {
super._burn(_owner, _tokenId);
// Clear metadata (if any)
if (bytes(tokenURIs[_tokenId]).length != 0) {
delete tokenURIs[_tokenId];
}
// Reorg all tokens array
uint256 tokenIndex = allTokensIndex[_tokenId];
uint256 lastTokenIndex = allTokens.length.sub(1);
uint256 lastToken = allTokens[lastTokenIndex];
allTokens[tokenIndex] = lastToken;
allTokens[lastTokenIndex] = 0;
allTokens.length--;
allTokensIndex[_tokenId] = 0;
allTokensIndex[lastToken] = tokenIndex;
}
}
// File: openzeppelin-zos/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 is Migratable {
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 initialize(address _sender) public isInitializer("Ownable", "1.9.0") {
owner = _sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param newOwner The address to transfer ownership to.
*/
function transferOwnership(address newOwner) public onlyOwner {
require(newOwner != address(0));
emit OwnershipTransferred(owner, newOwner);
owner = newOwner;
}
}
// File: contracts/estate/IEstateRegistry.sol
contract IEstateRegistry {
function mint(address to, string metadata) external returns (uint256);
function ownerOf(uint256 _tokenId) public view returns (address _owner); // from ERC721
// Events
event CreateEstate(
address indexed _owner,
uint256 indexed _estateId,
string _data
);
event AddLand(
uint256 indexed _estateId,
uint256 indexed _landId
);
event RemoveLand(
uint256 indexed _estateId,
uint256 indexed _landId,
address indexed _destinatary
);
event Update(
uint256 indexed _assetId,
address indexed _holder,
address indexed _operator,
string _data
);
event UpdateOperator(
uint256 indexed _estateId,
address indexed _operator
);
event UpdateManager(
address indexed _owner,
address indexed _operator,
address indexed _caller,
bool _approved
);
event SetLANDRegistry(
address indexed _registry
);
event SetEstateLandBalanceToken(
address indexed _previousEstateLandBalance,
address indexed _newEstateLandBalance
);
}
// File: contracts/minimeToken/IMinimeToken.sol
interface IMiniMeToken {
////////////////
// Generate and destroy tokens
////////////////
/// @notice Generates `_amount` tokens that are assigned to `_owner`
/// @param _owner The address that will be assigned the new tokens
/// @param _amount The quantity of tokens generated
/// @return True if the tokens are generated correctly
function generateTokens(address _owner, uint _amount) external returns (bool);
/// @notice Burns `_amount` tokens from `_owner`
/// @param _owner The address that will lose the tokens
/// @param _amount The quantity of tokens to burn
/// @return True if the tokens are burned correctly
function destroyTokens(address _owner, uint _amount) external returns (bool);
/// @param _owner The address that's balance is being requested
/// @return The balance of `_owner` at the current block
function balanceOf(address _owner) external view returns (uint256 balance);
event Transfer(address indexed _from, address indexed _to, uint256 _amount);
}
// File: contracts/estate/EstateStorage.sol
contract LANDRegistry {
function decodeTokenId(uint value) external pure returns (int, int);
function updateLandData(int x, int y, string data) external;
function setUpdateOperator(uint256 assetId, address operator) external;
function setManyUpdateOperator(uint256[] landIds, address operator) external;
function ping() public;
function ownerOf(uint256 tokenId) public returns (address);
function safeTransferFrom(address, address, uint256) public;
function updateOperator(uint256 landId) public returns (address);
}
contract EstateStorage {
bytes4 internal constant InterfaceId_GetMetadata = bytes4(keccak256("getMetadata(uint256)"));
bytes4 internal constant InterfaceId_VerifyFingerprint = bytes4(
keccak256("verifyFingerprint(uint256,bytes)")
);
LANDRegistry public registry;
// From Estate to list of owned LAND ids (LANDs)
mapping(uint256 => uint256[]) public estateLandIds;
// From LAND id (LAND) to its owner Estate id
mapping(uint256 => uint256) public landIdEstate;
// From Estate id to mapping of LAND id to index on the array above (estateLandIds)
mapping(uint256 => mapping(uint256 => uint256)) public estateLandIndex;
// Metadata of the Estate
mapping(uint256 => string) internal estateData;
// Operator of the Estate
mapping (uint256 => address) public updateOperator;
// From account to mapping of operator to bool whether is allowed to update content or not
mapping(address => mapping(address => bool)) public updateManager;
// Land balance minime token
IMiniMeToken public estateLandBalance;
// Registered balance accounts
mapping(address => bool) public registeredBalance;
}
// File: contracts/estate/EstateRegistry.sol
/**
* @title ERC721 registry of every minted Estate and their owned LANDs
* @dev Usings we are inheriting and depending on:
* From ERC721Token:
* - using SafeMath for uint256;
* - using AddressUtils for address;
*/
// solium-disable-next-line max-len
contract EstateRegistry is Migratable, IEstateRegistry, ERC721Token, ERC721Receiver, Ownable, EstateStorage {
modifier canTransfer(uint256 estateId) {
require(isApprovedOrOwner(msg.sender, estateId), "Only owner or operator can transfer");
_;
}
modifier onlyRegistry() {
require(msg.sender == address(registry), "Only the registry can make this operation");
_;
}
modifier onlyUpdateAuthorized(uint256 estateId) {
require(_isUpdateAuthorized(msg.sender, estateId), "Unauthorized user");
_;
}
modifier onlyLandUpdateAuthorized(uint256 estateId, uint256 landId) {
require(_isLandUpdateAuthorized(msg.sender, estateId, landId), "unauthorized user");
_;
}
modifier canSetUpdateOperator(uint256 estateId) {
address owner = ownerOf(estateId);
require(
isApprovedOrOwner(msg.sender, estateId) || updateManager[owner][msg.sender],
"unauthorized user"
);
_;
}
/**
* @dev Mint a new Estate with some metadata
* @param to The address that will own the minted token
* @param metadata Set an initial metadata
* @return An uint256 representing the new token id
*/
function mint(address to, string metadata) external onlyRegistry returns (uint256) {
return _mintEstate(to, metadata);
}
/**
* @notice Transfer a LAND owned by an Estate to a new owner
* @param estateId Current owner of the token
* @param landId LAND to be transfered
* @param destinatary New owner
*/
function transferLand(
uint256 estateId,
uint256 landId,
address destinatary
)
external
canTransfer(estateId)
{
return _transferLand(estateId, landId, destinatary);
}
/**
* @notice Transfer many tokens owned by an Estate to a new owner
* @param estateId Current owner of the token
* @param landIds LANDs to be transfered
* @param destinatary New owner
*/
function transferManyLands(
uint256 estateId,
uint256[] landIds,
address destinatary
)
external
canTransfer(estateId)
{
uint length = landIds.length;
for (uint i = 0; i < length; i++) {
_transferLand(estateId, landIds[i], destinatary);
}
}
/**
* @notice Get the Estate id for a given LAND id
* @dev This information also lives on estateLandIds,
* but it being a mapping you need to know the Estate id beforehand.
* @param landId LAND to search
* @return The corresponding Estate id
*/
function getLandEstateId(uint256 landId) external view returns (uint256) {
return landIdEstate[landId];
}
function setLANDRegistry(address _registry) external onlyOwner {
require(_registry.isContract(), "The LAND registry address should be a contract");
require(_registry != 0, "The LAND registry address should be valid");
registry = LANDRegistry(_registry);
emit SetLANDRegistry(registry);
}
function ping() external {
registry.ping();
}
/**
* @notice Return the amount of tokens for a given Estate
* @param estateId Estate id to search
* @return Tokens length
*/
function getEstateSize(uint256 estateId) external view returns (uint256) {
return estateLandIds[estateId].length;
}
/**
* @notice Return the amount of LANDs inside the Estates for a given address
* @param _owner of the estates
* @return the amount of LANDs
*/
function getLANDsSize(address _owner) public view returns (uint256) {
// Avoid balanceOf to not compute an unnecesary require
uint256 landsSize;
uint256 balance = ownedTokensCount[_owner];
for (uint256 i; i < balance; i++) {
uint256 estateId = ownedTokens[_owner][i];
landsSize += estateLandIds[estateId].length;
}
return landsSize;
}
/**
* @notice Update the metadata of an Estate
* @dev Reverts if the Estate does not exist or the user is not authorized
* @param estateId Estate id to update
* @param metadata string metadata
*/
function updateMetadata(
uint256 estateId,
string metadata
)
external
onlyUpdateAuthorized(estateId)
{
_updateMetadata(estateId, metadata);
emit Update(
estateId,
ownerOf(estateId),
msg.sender,
metadata
);
}
function getMetadata(uint256 estateId) external view returns (string) {
return estateData[estateId];
}
function isUpdateAuthorized(address operator, uint256 estateId) external view returns (bool) {
return _isUpdateAuthorized(operator, estateId);
}
/**
* @dev Set an updateManager for an account
* @param _owner - address of the account to set the updateManager
* @param _operator - address of the account to be set as the updateManager
* @param _approved - bool whether the address will be approved or not
*/
function setUpdateManager(address _owner, address _operator, bool _approved) external {
require(_operator != msg.sender, "The operator should be different from owner");
require(
_owner == msg.sender
|| operatorApprovals[_owner][msg.sender],
"Unauthorized user"
);
updateManager[_owner][_operator] = _approved;
emit UpdateManager(
_owner,
_operator,
msg.sender,
_approved
);
}
/**
* @notice Set Estate updateOperator
* @param estateId - Estate id
* @param operator - address of the account to be set as the updateOperator
*/
function setUpdateOperator(
uint256 estateId,
address operator
)
public
canSetUpdateOperator(estateId)
{
updateOperator[estateId] = operator;
emit UpdateOperator(estateId, operator);
}
/**
* @notice Set Estates updateOperator
* @param _estateIds - Estate ids
* @param _operator - address of the account to be set as the updateOperator
*/
function setManyUpdateOperator(
uint256[] _estateIds,
address _operator
)
public
{
for (uint i = 0; i < _estateIds.length; i++) {
setUpdateOperator(_estateIds[i], _operator);
}
}
/**
* @notice Set LAND updateOperator
* @param estateId - Estate id
* @param landId - LAND to set the updateOperator
* @param operator - address of the account to be set as the updateOperator
*/
function setLandUpdateOperator(
uint256 estateId,
uint256 landId,
address operator
)
public
canSetUpdateOperator(estateId)
{
require(landIdEstate[landId] == estateId, "The LAND is not part of the Estate");
registry.setUpdateOperator(landId, operator);
}
/**
* @notice Set many LAND updateOperator
* @param _estateId - Estate id
* @param _landIds - LANDs to set the updateOperator
* @param _operator - address of the account to be set as the updateOperator
*/
function setManyLandUpdateOperator(
uint256 _estateId,
uint256[] _landIds,
address _operator
)
public
canSetUpdateOperator(_estateId)
{
for (uint i = 0; i < _landIds.length; i++) {
require(landIdEstate[_landIds[i]] == _estateId, "The LAND is not part of the Estate");
}
registry.setManyUpdateOperator(_landIds, _operator);
}
function initialize(
string _name,
string _symbol,
address _registry
)
public
isInitializer("EstateRegistry", "0.0.2")
{
require(_registry != 0, "The registry should be a valid address");
ERC721Token.initialize(_name, _symbol);
Ownable.initialize(msg.sender);
registry = LANDRegistry(_registry);
}
/**
* @notice Handle the receipt of an NFT
* @dev The ERC721 smart contract calls this function on the recipient
* after a `safetransfer`. This function MAY throw to revert and reject the
* transfer. Return of other than the magic value MUST result in the
* transaction being reverted.
* Note: the contract address is always the message sender.
* @param _operator The address which called `safeTransferFrom` function
* @param _from The address which previously owned the token
* @param _tokenId The NFT identifier which is being transferred
* @param _data Additional data with no specified format
* @return `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`
*/
function onERC721Received(
address _operator,
address _from,
uint256 _tokenId,
bytes _data
)
public
onlyRegistry
returns (bytes4)
{
uint256 estateId = _bytesToUint(_data);
_pushLandId(estateId, _tokenId);
return ERC721_RECEIVED;
}
/**
* @dev Creates a checksum of the contents of the Estate
* @param estateId the estateId to be verified
*/
function getFingerprint(uint256 estateId)
public
view
returns (bytes32 result)
{
result = keccak256(abi.encodePacked("estateId", estateId));
uint256 length = estateLandIds[estateId].length;
for (uint i = 0; i < length; i++) {
result ^= keccak256(abi.encodePacked(estateLandIds[estateId][i]));
}
return result;
}
/**
* @dev Verifies a checksum of the contents of the Estate
* @param estateId the estateid to be verified
* @param fingerprint the user provided identification of the Estate contents
*/
function verifyFingerprint(uint256 estateId, bytes fingerprint) public view returns (bool) {
return getFingerprint(estateId) == _bytesToBytes32(fingerprint);
}
/**
* @dev Safely transfers the ownership of multiple Estate IDs to another address
* @dev Delegates to safeTransferFrom for each transfer
* @dev Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param estateIds uint256 array of IDs to be transferred
*/
function safeTransferManyFrom(address from, address to, uint256[] estateIds) public {
safeTransferManyFrom(
from,
to,
estateIds,
""
);
}
/**
* @dev Safely transfers the ownership of multiple Estate IDs to another address
* @dev Delegates to safeTransferFrom for each transfer
* @dev Requires the msg sender to be the owner, approved, or operator
* @param from current owner of the token
* @param to address to receive the ownership of the given token ID
* @param estateIds uint256 array of IDs to be transferred
* @param data bytes data to send along with a safe transfer check
*/
function safeTransferManyFrom(
address from,
address to,
uint256[] estateIds,
bytes data
)
public
{
for (uint i = 0; i < estateIds.length; i++) {
safeTransferFrom(
from,
to,
estateIds[i],
data
);
}
}
/**
* @dev update LAND data owned by an Estate
* @param estateId Estate
* @param landId LAND to be updated
* @param data string metadata
*/
function updateLandData(uint256 estateId, uint256 landId, string data) public {
_updateLandData(estateId, landId, data);
}
/**
* @dev update LANDs data owned by an Estate
* @param estateId Estate id
* @param landIds LANDs to be updated
* @param data string metadata
*/
function updateManyLandData(uint256 estateId, uint256[] landIds, string data) public {
uint length = landIds.length;
for (uint i = 0; i < length; i++) {
_updateLandData(estateId, landIds[i], data);
}
}
function transferFrom(address _from, address _to, uint256 _tokenId)
public
{
updateOperator[_tokenId] = address(0);
_updateEstateLandBalance(_from, _to, estateLandIds[_tokenId].length);
super.transferFrom(_from, _to, _tokenId);
}
// check the supported interfaces via ERC165
function _supportsInterface(bytes4 _interfaceId) internal view returns (bool) {
// solium-disable-next-line operator-whitespace
return super._supportsInterface(_interfaceId)
|| _interfaceId == InterfaceId_GetMetadata
|| _interfaceId == InterfaceId_VerifyFingerprint;
}
/**
* @dev Internal function to mint a new Estate with some metadata
* @param to The address that will own the minted token
* @param metadata Set an initial metadata
* @return An uint256 representing the new token id
*/
function _mintEstate(address to, string metadata) internal returns (uint256) {
require(to != address(0), "You can not mint to an empty address");
uint256 estateId = _getNewEstateId();
_mint(to, estateId);
_updateMetadata(estateId, metadata);
emit CreateEstate(to, estateId, metadata);
return estateId;
}
/**
* @dev Internal function to update an Estate metadata
* @dev Does not require the Estate to exist, for a public interface use `updateMetadata`
* @param estateId Estate id to update
* @param metadata string metadata
*/
function _updateMetadata(uint256 estateId, string metadata) internal {
estateData[estateId] = metadata;
}
/**
* @notice Return a new unique id
* @dev It uses totalSupply to determine the next id
* @return uint256 Representing the new Estate id
*/
function _getNewEstateId() internal view returns (uint256) {
return totalSupply().add(1);
}
/**
* @dev Appends a new LAND id to an Estate updating all related storage
* @param estateId Estate where the LAND should go
* @param landId Transfered LAND
*/
function _pushLandId(uint256 estateId, uint256 landId) internal {
require(exists(estateId), "The Estate id should exist");
require(landIdEstate[landId] == 0, "The LAND is already owned by an Estate");
require(registry.ownerOf(landId) == address(this), "The EstateRegistry cannot manage the LAND");
estateLandIds[estateId].push(landId);
landIdEstate[landId] = estateId;
estateLandIndex[estateId][landId] = estateLandIds[estateId].length;
address owner = ownerOf(estateId);
_updateEstateLandBalance(address(registry), owner, 1);
emit AddLand(estateId, landId);
}
/**
* @dev Removes a LAND from an Estate and transfers it to a new owner
* @param estateId Current owner of the LAND
* @param landId LAND to be transfered
* @param destinatary New owner
*/
function _transferLand(
uint256 estateId,
uint256 landId,
address destinatary
)
internal
{
require(destinatary != address(0), "You can not transfer LAND to an empty address");
uint256[] storage landIds = estateLandIds[estateId];
mapping(uint256 => uint256) landIndex = estateLandIndex[estateId];
/**
* Using 1-based indexing to be able to make this check
*/
require(landIndex[landId] != 0, "The LAND is not part of the Estate");
uint lastIndexInArray = landIds.length.sub(1);
/**
* Get the landIndex of this token in the landIds list
*/
uint indexInArray = landIndex[landId].sub(1);
/**
* Get the landId at the end of the landIds list
*/
uint tempTokenId = landIds[lastIndexInArray];
/**
* Store the last token in the position previously occupied by landId
*/
landIndex[tempTokenId] = indexInArray.add(1);
landIds[indexInArray] = tempTokenId;
/**
* Delete the landIds[last element]
*/
delete landIds[lastIndexInArray];
landIds.length = lastIndexInArray;
/**
* Drop this landId from both the landIndex and landId list
*/
landIndex[landId] = 0;
/**
* Drop this landId Estate
*/
landIdEstate[landId] = 0;
address owner = ownerOf(estateId);
_updateEstateLandBalance(owner, address(registry), 1);
registry.safeTransferFrom(this, destinatary, landId);
emit RemoveLand(estateId, landId, destinatary);
}
function _isUpdateAuthorized(address operator, uint256 estateId) internal view returns (bool) {
address owner = ownerOf(estateId);
return isApprovedOrOwner(operator, estateId)
|| updateOperator[estateId] == operator
|| updateManager[owner][operator];
}
function _isLandUpdateAuthorized(
address operator,
uint256 estateId,
uint256 landId
)
internal returns (bool)
{
return _isUpdateAuthorized(operator, estateId) || registry.updateOperator(landId) == operator;
}
function _bytesToUint(bytes b) internal pure returns (uint256) {
return uint256(_bytesToBytes32(b));
}
function _bytesToBytes32(bytes b) internal pure returns (bytes32) {
bytes32 out;
for (uint i = 0; i < b.length; i++) {
out |= bytes32(b[i] & 0xFF) >> i.mul(8);
}
return out;
}
function _updateLandData(
uint256 estateId,
uint256 landId,
string data
)
internal
onlyLandUpdateAuthorized(estateId, landId)
{
require(landIdEstate[landId] == estateId, "The LAND is not part of the Estate");
int x;
int y;
(x, y) = registry.decodeTokenId(landId);
registry.updateLandData(x, y, data);
}
/**
* @dev Set a new estate land balance minime token
* @param _newEstateLandBalance address of the new estate land balance token
*/
function _setEstateLandBalanceToken(address _newEstateLandBalance) internal {
require(_newEstateLandBalance != address(0), "New estateLandBalance should not be zero address");
emit SetEstateLandBalanceToken(estateLandBalance, _newEstateLandBalance);
estateLandBalance = IMiniMeToken(_newEstateLandBalance);
}
/**
* @dev Register an account balance
* @notice Register land Balance
*/
function registerBalance() external {
require(!registeredBalance[msg.sender], "Register Balance::The user is already registered");
// Get balance of the sender
uint256 currentBalance = estateLandBalance.balanceOf(msg.sender);
if (currentBalance > 0) {
require(
estateLandBalance.destroyTokens(msg.sender, currentBalance),
"Register Balance::Could not destroy tokens"
);
}
// Set balance as registered
registeredBalance[msg.sender] = true;
// Get LAND balance
uint256 newBalance = getLANDsSize(msg.sender);
// Generate Tokens
require(
estateLandBalance.generateTokens(msg.sender, newBalance),
"Register Balance::Could not generate tokens"
);
}
/**
* @dev Unregister an account balance
* @notice Unregister land Balance
*/
function unregisterBalance() external {
require(registeredBalance[msg.sender], "Unregister Balance::The user not registered");
// Set balance as unregistered
registeredBalance[msg.sender] = false;
// Get balance
uint256 currentBalance = estateLandBalance.balanceOf(msg.sender);
// Destroy Tokens
require(
estateLandBalance.destroyTokens(msg.sender, currentBalance),
"Unregister Balance::Could not destroy tokens"
);
}
/**
* @dev Update account balances
* @param _from account
* @param _to account
* @param _amount to update
*/
function _updateEstateLandBalance(address _from, address _to, uint256 _amount) internal {
if (registeredBalance[_from]) {
estateLandBalance.destroyTokens(_from, _amount);
}
if (registeredBalance[_to]) {
estateLandBalance.generateTokens(_to, _amount);
}
}
/**
* @dev Set a estate land balance minime token hardcoded because of the
* contraint of the proxy for using an owner
* Mainnet: 0x8568f23f343694650370fe5e254b55bfb704a6c7
*/
function setEstateLandBalanceToken() external {
require(estateLandBalance == address(0), "estateLandBalance was set");
_setEstateLandBalanceToken(address(0x8568f23f343694650370fe5e254b55bfb704a6c7));
}
}
|
Internal function to mint a new Estate with some metadata to The address that will own the minted token metadata Set an initial metadata return An uint256 representing the new token id/
|
function _mintEstate(address to, string metadata) internal returns (uint256) {
require(to != address(0), "You can not mint to an empty address");
uint256 estateId = _getNewEstateId();
_mint(to, estateId);
_updateMetadata(estateId, metadata);
emit CreateEstate(to, estateId, metadata);
return estateId;
}
| 1,763,334 |
// SPDX-License-Identifier: Apache-2.0
pragma solidity ^0.8.3;
import "../interfaces/IERC20.sol";
import "../libraries/History.sol";
import "../libraries/VestingVaultStorage.sol";
import "../libraries/Storage.sol";
import "../interfaces/IVotingVault.sol";
abstract contract AbstractVestingVault is IVotingVault {
// Bring our libraries into scope
using History for *;
using VestingVaultStorage for *;
using Storage for *;
// NOTE: There is no emergency withdrawal, any funds not sent via deposit() are
// unrecoverable by this version of the VestingVault
// This contract has a privileged grant manager who can add grants or remove grants
// It will not transfer in on each grant but rather check for solvency via state variables.
// Immutables are in bytecode so don't need special storage treatment
IERC20 public immutable token;
// A constant which is how far back stale blocks are
uint256 public immutable staleBlockLag;
event VoteChange(address indexed to, address indexed from, int256 amount);
/// @notice Constructs the contract.
/// @param _token The erc20 token to grant.
/// @param _stale Stale block used for voting power calculations.
constructor(IERC20 _token, uint256 _stale) {
token = _token;
staleBlockLag = _stale;
}
/// @notice initialization function to set initial variables.
/// @dev Can only be called once after deployment.
/// @param manager_ The vault manager can add and remove grants.
/// @param timelock_ The timelock address can change the unvested multiplier.
function initialize(address manager_, address timelock_) public {
require(Storage.uint256Ptr("initialized").data == 0, "initialized");
Storage.set(Storage.uint256Ptr("initialized"), 1);
Storage.set(Storage.addressPtr("manager"), manager_);
Storage.set(Storage.addressPtr("timelock"), timelock_);
Storage.set(Storage.uint256Ptr("unvestedMultiplier"), 100);
}
// deposits mapping(address => Grant)
/// @notice A single function endpoint for loading grant storage
/// @dev Only one Grant is allowed per address. Grants SHOULD NOT
/// be modified.
/// @return returns a storage mapping which can be used to look up grant data
function _grants()
internal
pure
returns (mapping(address => VestingVaultStorage.Grant) storage)
{
// This call returns a storage mapping with a unique non overwrite-able storage location
// which can be persisted through upgrades, even if they change storage layout
return (VestingVaultStorage.mappingAddressToGrantPtr("grants"));
}
/// @notice A single function endpoint for loading the starting
/// point of the range for each accepted grant
/// @dev This is modified any time a grant is accepted
/// @return returns the starting point uint
function _loadBound() internal pure returns (Storage.Uint256 memory) {
// This call returns a storage mapping with a unique non overwrite-able storage location
// which can be persisted through upgrades, even if they change storage layout
return Storage.uint256Ptr("bound");
}
/// @notice A function to access the storage of the unassigned token value
/// @dev The unassigned tokens are not part of any grant and ca be used
/// for a future grant or withdrawn by the manager.
/// @return A struct containing the unassigned uint.
function _unassigned() internal pure returns (Storage.Uint256 storage) {
return Storage.uint256Ptr("unassigned");
}
/// @notice A function to access the storage of the manager address.
/// @dev The manager can access all functions with the onlyManager modifier.
/// @return A struct containing the manager address.
function _manager() internal pure returns (Storage.Address memory) {
return Storage.addressPtr("manager");
}
/// @notice A function to access the storage of the timelock address
/// @dev The timelock can access all functions with the onlyTimelock modifier.
/// @return A struct containing the timelock address.
function _timelock() internal pure returns (Storage.Address memory) {
return Storage.addressPtr("timelock");
}
/// @notice A function to access the storage of the unvestedMultiplier value
/// @dev The unvested multiplier is a number that represents the voting power of each
/// unvested token as a percentage of a vested token. For example if
/// unvested tokens have 50% voting power compared to vested ones, this value would be 50.
/// This can be changed by governance in the future.
/// @return A struct containing the unvestedMultiplier uint.
function _unvestedMultiplier()
internal
pure
returns (Storage.Uint256 memory)
{
return Storage.uint256Ptr("unvestedMultiplier");
}
modifier onlyManager() {
require(msg.sender == _manager().data, "!manager");
_;
}
modifier onlyTimelock() {
require(msg.sender == _timelock().data, "!timelock");
_;
}
/// @notice Getter for the grants mapping
/// @param _who The owner of the grant to query
/// @return Grant of the provided address
function getGrant(address _who)
external
view
returns (VestingVaultStorage.Grant memory)
{
return _grants()[_who];
}
/// @notice Accepts a grant
/// @dev Sends token from the contract to the sender and back to the contract
/// while assigning a numerical range to the unwithdrawn granted tokens.
function acceptGrant() public {
// load the grant
VestingVaultStorage.Grant storage grant = _grants()[msg.sender];
uint256 availableTokens = grant.allocation - grant.withdrawn;
// check that grant has unwithdrawn tokens
require(availableTokens > 0, "no grant available");
// transfer the token to the user
token.transfer(msg.sender, availableTokens);
// transfer from the user back to the contract
token.transferFrom(msg.sender, address(this), availableTokens);
uint256 bound = _loadBound().data;
grant.range = [bound, bound + availableTokens];
Storage.set(Storage.uint256Ptr("bound"), bound + availableTokens);
}
/// @notice Adds a new grant.
/// @dev Manager can set who the voting power will be delegated to initially.
/// This potentially avoids the need for a delegation transaction by the grant recipient.
/// @param _who The Grant recipient.
/// @param _amount The total grant value.
/// @param _startTime Optionally set a non standard start time. If set to zero then the start time
/// will be made the block this is executed in.
/// @param _expiration timestamp when the grant ends (all tokens count as unlocked).
/// @param _cliff Timestamp when the cliff ends. No tokens are unlocked until this
/// timestamp is reached.
/// @param _delegatee Optional param. The address to delegate the voting power
/// associated with this grant to
function addGrantAndDelegate(
address _who,
uint128 _amount,
uint128 _startTime,
uint128 _expiration,
uint128 _cliff,
address _delegatee
) public onlyManager {
// Consistency check
require(
_cliff <= _expiration && _startTime <= _expiration,
"Invalid configuration"
);
// If no custom start time is needed we use this block.
if (_startTime == 0) {
_startTime = uint128(block.number);
}
Storage.Uint256 storage unassigned = _unassigned();
Storage.Uint256 memory unvestedMultiplier = _unvestedMultiplier();
require(unassigned.data >= _amount, "Insufficient balance");
// load the grant.
VestingVaultStorage.Grant storage grant = _grants()[_who];
// If this address already has a grant, a different address must be provided
// topping up or editing active grants is not supported.
require(grant.allocation == 0, "Has Grant");
// load the delegate. Defaults to the grant owner
_delegatee = _delegatee == address(0) ? _who : _delegatee;
// calculate the voting power. Assumes all voting power is initially locked.
// Come back to this assumption.
uint128 newVotingPower =
(_amount * uint128(unvestedMultiplier.data)) / 100;
// set the new grant
_grants()[_who] = VestingVaultStorage.Grant(
_amount,
0,
_startTime,
_expiration,
_cliff,
newVotingPower,
_delegatee,
[uint256(0), uint256(0)]
);
// update the amount of unassigned tokens
unassigned.data -= _amount;
// update the delegatee's voting power
History.HistoricalBalances memory votingPower = _votingPower();
uint256 delegateeVotes = votingPower.loadTop(grant.delegatee);
votingPower.push(grant.delegatee, delegateeVotes + newVotingPower);
emit VoteChange(grant.delegatee, _who, int256(uint256(newVotingPower)));
}
/// @notice Removes a grant.
/// @dev The manager has the power to remove a grant at any time. Any withdrawable tokens will be
/// sent to the grant owner.
/// @param _who The Grant owner.
function removeGrant(address _who) public virtual onlyManager {
// load the grant
VestingVaultStorage.Grant storage grant = _grants()[_who];
// get the amount of withdrawable tokens
uint256 withdrawable = _getWithdrawableAmount(grant);
// it is simpler to just transfer withdrawable tokens instead of modifying the struct storage
// to allow withdrawal through claim()
token.transfer(_who, withdrawable);
Storage.Uint256 storage unassigned = _unassigned();
uint256 locked = grant.allocation - (grant.withdrawn + withdrawable);
// return the unused tokens so they can be used for a different grant
unassigned.data += locked;
// update the delegatee's voting power
History.HistoricalBalances memory votingPower = _votingPower();
uint256 delegateeVotes = votingPower.loadTop(grant.delegatee);
votingPower.push(
grant.delegatee,
delegateeVotes - grant.latestVotingPower
);
// Emit the vote change event
emit VoteChange(
grant.delegatee,
_who,
-1 * int256(uint256(grant.latestVotingPower))
);
// delete the grant
delete _grants()[_who];
}
/// @notice Claim all withdrawable value from a grant.
/// @dev claiming value resets the voting power, This could either increase or reduce the
/// total voting power associated with the caller's grant.
function claim() public virtual {
// load the grant
VestingVaultStorage.Grant storage grant = _grants()[msg.sender];
// get the withdrawable amount
uint256 withdrawable = _getWithdrawableAmount(grant);
// transfer the available amount
token.transfer(msg.sender, withdrawable);
grant.withdrawn += uint128(withdrawable);
// only move range bound if grant was accepted
if (grant.range[1] > 0) {
grant.range[1] -= withdrawable;
}
// update the user's voting power
_syncVotingPower(msg.sender, grant);
}
/// @notice Changes the caller's token grant voting power delegation.
/// @dev The total voting power is not guaranteed to go up because
/// the unvested token multiplier can be updated at any time.
/// @param _to the address to delegate to
function delegate(address _to) public {
VestingVaultStorage.Grant storage grant = _grants()[msg.sender];
// If the delegation has already happened we don't want the tx to send
require(_to != grant.delegatee, "Already delegated");
History.HistoricalBalances memory votingPower = _votingPower();
uint256 oldDelegateeVotes = votingPower.loadTop(grant.delegatee);
uint256 newVotingPower = _currentVotingPower(grant);
// Remove old delegatee's voting power and emit event
votingPower.push(
grant.delegatee,
oldDelegateeVotes - grant.latestVotingPower
);
emit VoteChange(
grant.delegatee,
msg.sender,
-1 * int256(uint256(grant.latestVotingPower))
);
// Note - It is important that this is loaded here and not before the previous state change because if
// _to == grant.delegatee and re-delegation was allowed we could be working with out of date state.
uint256 newDelegateeVotes = votingPower.loadTop(_to);
// add voting power to the target delegatee and emit event
emit VoteChange(_to, msg.sender, int256(newVotingPower));
votingPower.push(_to, newDelegateeVotes + newVotingPower);
// update grant info
grant.latestVotingPower = uint128(newVotingPower);
grant.delegatee = _to;
}
/// @notice Manager-only token deposit function.
/// @dev Deposited tokens are added to `_unassigned` and can be used to create grants.
/// WARNING: This is the only way to deposit tokens into the contract. Any tokens sent
/// via other means are not recoverable by this contract.
/// @param _amount The amount of tokens to deposit.
function deposit(uint256 _amount) public onlyManager {
Storage.Uint256 storage unassigned = _unassigned();
// update unassigned value
unassigned.data += _amount;
token.transferFrom(msg.sender, address(this), _amount);
}
/// @notice Manager-only token withdrawal function.
/// @dev The manager can withdraw tokens that are not being used by a grant.
/// This function cannot be used to recover tokens that were sent to this contract
/// by any means other than `deposit()`
/// @param _amount the amount to withdraw
/// @param _recipient the address to withdraw to
function withdraw(uint256 _amount, address _recipient)
public
virtual
onlyManager
{
Storage.Uint256 storage unassigned = _unassigned();
require(unassigned.data >= _amount, "Insufficient balance");
// update unassigned value
unassigned.data -= _amount;
token.transfer(_recipient, _amount);
}
/// @notice Update a delegatee's voting power.
/// @dev Voting power is only updated for this block onward.
/// see `History` for more on how voting power is tracked and queried.
/// Anybody can update a grant's voting power.
/// @param _who the address who's voting power this function updates
function updateVotingPower(address _who) public {
VestingVaultStorage.Grant storage grant = _grants()[_who];
_syncVotingPower(_who, grant);
}
/// @notice Helper to update a delegatee's voting power.
/// @param _who the address who's voting power we need to sync
/// @param _grant the storage pointer to the grant of that user
function _syncVotingPower(
address _who,
VestingVaultStorage.Grant storage _grant
) internal {
History.HistoricalBalances memory votingPower = _votingPower();
uint256 delegateeVotes = votingPower.loadTop(_grant.delegatee);
uint256 newVotingPower = _currentVotingPower(_grant);
// get the change in voting power. Negative if the voting power is reduced
int256 change =
int256(newVotingPower) - int256(uint256(_grant.latestVotingPower));
// do nothing if there is no change
if (change == 0) return;
if (change > 0) {
votingPower.push(
_grant.delegatee,
delegateeVotes + uint256(change)
);
} else {
// if the change is negative, we multiply by -1 to avoid underflow when casting
votingPower.push(
_grant.delegatee,
delegateeVotes - uint256(change * -1)
);
}
emit VoteChange(_grant.delegatee, _who, change);
_grant.latestVotingPower = uint128(newVotingPower);
}
/// @notice Attempts to load the voting power of a user
/// @param user The address we want to load the voting power of
/// @param blockNumber the block number we want the user's voting power at
// @param calldata the extra calldata is unused in this contract
/// @return the number of votes
function queryVotePower(
address user,
uint256 blockNumber,
bytes calldata
) external override returns (uint256) {
// Get our reference to historical data
History.HistoricalBalances memory votingPower = _votingPower();
// Find the historical data and clear everything more than 'staleBlockLag' into the past
return
votingPower.findAndClear(
user,
blockNumber,
block.number - staleBlockLag
);
}
/// @notice Loads the voting power of a user without changing state
/// @param user The address we want to load the voting power of
/// @param blockNumber the block number we want the user's voting power at
/// @return the number of votes
function queryVotePowerView(address user, uint256 blockNumber)
external
view
returns (uint256)
{
// Get our reference to historical data
History.HistoricalBalances memory votingPower = _votingPower();
// Find the historical data
return votingPower.find(user, blockNumber);
}
/// @notice Calculates how much a grantee can withdraw
/// @param _grant the memory location of the loaded grant
/// @return the amount which can be withdrawn
function _getWithdrawableAmount(VestingVaultStorage.Grant memory _grant)
internal
view
returns (uint256)
{
if (block.number < _grant.cliff || block.number < _grant.created) {
return 0;
}
if (block.number >= _grant.expiration) {
return (_grant.allocation - _grant.withdrawn);
}
uint256 unlocked =
(_grant.allocation * (block.number - _grant.created)) /
(_grant.expiration - _grant.created);
return (unlocked - _grant.withdrawn);
}
/// @notice Returns the historical voting power tracker.
/// @return A struct which can push to and find items in block indexed storage.
function _votingPower()
internal
pure
returns (History.HistoricalBalances memory)
{
// This call returns a storage mapping with a unique non overwrite-able storage location
// which can be persisted through upgrades, even if they change storage layout.
return (History.load("votingPower"));
}
/// @notice Helper that returns the current voting power of a grant
/// @dev This is not always the recorded voting power since it uses the latest
/// _unvestedMultiplier.
/// @param _grant The grant to check for voting power.
/// @return The current voting power of the grant.
function _currentVotingPower(VestingVaultStorage.Grant memory _grant)
internal
view
returns (uint256)
{
uint256 withdrawable = _getWithdrawableAmount(_grant);
uint256 locked = _grant.allocation - (withdrawable + _grant.withdrawn);
return (withdrawable + (locked * _unvestedMultiplier().data) / 100);
}
/// @notice timelock-only unvestedMultiplier update function.
/// @dev Allows the timelock to update the unvestedMultiplier.
/// @param _multiplier The new multiplier.
function changeUnvestedMultiplier(uint256 _multiplier) public onlyTimelock {
require(_multiplier <= 100, "Above 100%");
Storage.set(Storage.uint256Ptr("unvestedMultiplier"), _multiplier);
}
/// @notice timelock-only timelock update function.
/// @dev Allows the timelock to update the timelock address.
/// @param timelock_ The new timelock.
function setTimelock(address timelock_) public onlyTimelock {
Storage.set(Storage.addressPtr("timelock"), timelock_);
}
/// @notice timelock-only manager update function.
/// @dev Allows the timelock to update the manager address.
/// @param manager_ The new manager.
function setManager(address manager_) public onlyTimelock {
Storage.set(Storage.addressPtr("manager"), manager_);
}
/// @notice A function to access the storage of the timelock address
/// @dev The timelock can access all functions with the onlyTimelock modifier.
/// @return The timelock address.
function timelock() public pure returns (address) {
return _timelock().data;
}
/// @notice A function to access the storage of the unvested token vote power multiplier.
/// @return The unvested token multiplier
function unvestedMultiplier() external pure returns (uint256) {
return _unvestedMultiplier().data;
}
/// @notice A function to access the storage of the manager address.
/// @dev The manager can access all functions with the olyManager modifier.
/// @return The manager address.
function manager() public pure returns (address) {
return _manager().data;
}
}
// Deployable version of the abstract contract
contract VestingVault is AbstractVestingVault {
/// @notice Constructs the contract.
/// @param _token The erc20 token to grant.
/// @param _stale Stale block used for voting power calculations.
constructor(IERC20 _token, uint256 _stale)
AbstractVestingVault(_token, _stale)
{}
}
|
A function to access the storage of the unvestedMultiplier value The unvested multiplier is a number that represents the voting power of each unvested token as a percentage of a vested token. For example if unvested tokens have 50% voting power compared to vested ones, this value would be 50. This can be changed by governance in the future. return A struct containing the unvestedMultiplier uint.
|
function _unvestedMultiplier()
internal
pure
returns (Storage.Uint256 memory)
{
return Storage.uint256Ptr("unvestedMultiplier");
}
| 6,364,466 |
./partial_match/1/0x53cffb579143B08025D2f1353CCB7e36D1b9CC94/sources/contracts/DelegatorInterface.sol
|
Implementation address for this contract/ Emitted when implementation is changed/ Called by the admin to update the implementation of the delegator implementation_ The address of the new implementation for delegation/ Internal method to delegate execution to another contract It returns to the external caller whatever the implementation returns or forwards reverts callee The contract to delegatecall data The raw data to delegatecall return The returned bytes from the delegatecall/
|
function delegateTo(address callee, bytes memory data) internal returns (bytes memory) {
(bool success, bytes memory returnData) = callee.delegatecall(data);
assembly {
}
return returnData;
}
| 4,294,291 |
/*
* This file was generated by MyWish Platform (https://mywish.io/)
* The complete code could be found at https://github.com/MyWishPlatform/
* Copyright (C) 2018 MyWish
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
pragma solidity ^0.4.23;
/**
* @title ERC20Basic
* @dev Simpler version of ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/179
*/
contract ERC20Basic {
function totalSupply() public view returns (uint256);
function balanceOf(address who) public view returns (uint256);
function transfer(address to, uint256 value) public returns (bool);
event Transfer(address indexed from, address indexed to, uint256 value);
}
/**
* @title ERC20 interface
* @dev see https://github.com/ethereum/EIPs/issues/20
*/
contract ERC20 is ERC20Basic {
function allowance(address owner, address spender)
public view returns (uint256);
function transferFrom(address from, address to, uint256 value)
public returns (bool);
function approve(address spender, uint256 value) public returns (bool);
event Approval(
address indexed owner,
address indexed spender,
uint256 value
);
}
/**
* @title SafeMath
* @dev Math operations with safety checks that throw on error
*/
library SafeMath {
/**
* @dev Multiplies two numbers, throws on overflow.
*/
function mul(uint256 a, uint256 b) internal pure returns (uint256 c) {
// Gas optimization: this is cheaper than asserting 'a' not being zero, but the
// benefit is lost if 'b' is also tested.
// See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522
if (a == 0) {
return 0;
}
c = a * b;
assert(c / a == b);
return c;
}
/**
* @dev Integer division of two numbers, truncating the quotient.
*/
function div(uint256 a, uint256 b) internal pure returns (uint256) {
// assert(b > 0); // Solidity automatically throws when dividing by 0
// uint256 c = a / b;
// assert(a == b * c + a % b); // There is no case in which this doesn't hold
return a / b;
}
/**
* @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend).
*/
function sub(uint256 a, uint256 b) internal pure returns (uint256) {
assert(b <= a);
return a - b;
}
/**
* @dev Adds two numbers, throws on overflow.
*/
function add(uint256 a, uint256 b) internal pure returns (uint256 c) {
c = a + b;
assert(c >= a);
return c;
}
}
/**
* @title Crowdsale
* @dev Crowdsale is a base contract for managing a token crowdsale,
* allowing investors to purchase tokens with ether. This contract implements
* such functionality in its most fundamental form and can be extended to provide additional
* functionality and/or custom behavior.
* The external interface represents the basic interface for purchasing tokens, and conform
* the base architecture for crowdsales. They are *not* intended to be modified / overriden.
* The internal interface conforms the extensible and modifiable surface of crowdsales. Override
* the methods to add functionality. Consider using 'super' where appropiate to concatenate
* behavior.
*/
contract Crowdsale {
using SafeMath for uint256;
// The token being sold
ERC20 public token;
// Address where funds are collected
address public wallet;
// How many token units a buyer gets per wei.
// The rate is the conversion between wei and the smallest and indivisible token unit.
// So, if you are using a rate of 1 with a DetailedERC20 token with 3 decimals called TOK
// 1 wei will give you 1 unit, or 0.001 TOK.
uint256 public rate;
// Amount of wei raised
uint256 public weiRaised;
/**
* Event for token purchase logging
* @param purchaser who paid for the tokens
* @param beneficiary who got the tokens
* @param value weis paid for purchase
* @param amount amount of tokens purchased
*/
event TokenPurchase(
address indexed purchaser,
address indexed beneficiary,
uint256 value,
uint256 amount
);
/**
* @param _rate Number of token units a buyer gets per wei
* @param _wallet Address where collected funds will be forwarded to
* @param _token Address of the token being sold
*/
constructor(uint256 _rate, address _wallet, ERC20 _token) public {
require(_rate > 0);
require(_wallet != address(0));
require(_token != address(0));
rate = _rate;
wallet = _wallet;
token = _token;
}
// -----------------------------------------
// Crowdsale external interface
// -----------------------------------------
/**
* @dev fallback function ***DO NOT OVERRIDE***
*/
function () external payable {
buyTokens(msg.sender);
}
/**
* @dev low level token purchase ***DO NOT OVERRIDE***
* @param _beneficiary Address performing the token purchase
*/
function buyTokens(address _beneficiary) public payable {
uint256 weiAmount = msg.value;
_preValidatePurchase(_beneficiary, weiAmount);
// calculate token amount to be created
uint256 tokens = _getTokenAmount(weiAmount);
// update state
weiRaised = weiRaised.add(weiAmount);
_processPurchase(_beneficiary, tokens);
emit TokenPurchase(
msg.sender,
_beneficiary,
weiAmount,
tokens
);
_updatePurchasingState(_beneficiary, weiAmount);
_forwardFunds();
_postValidatePurchase(_beneficiary, weiAmount);
}
// -----------------------------------------
// Internal interface (extensible)
// -----------------------------------------
/**
* @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. Use super to concatenate validations.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(_beneficiary != address(0));
require(_weiAmount != 0);
}
/**
* @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid conditions are not met.
* @param _beneficiary Address performing the token purchase
* @param _weiAmount Value in wei involved in the purchase
*/
function _postValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens.
* @param _beneficiary Address performing the token purchase
* @param _tokenAmount Number of tokens to be emitted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
token.transfer(_beneficiary, _tokenAmount);
}
/**
* @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens.
* @param _beneficiary Address receiving the tokens
* @param _tokenAmount Number of tokens to be purchased
*/
function _processPurchase(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
_deliverTokens(_beneficiary, _tokenAmount);
}
/**
* @dev Override for extensions that require an internal state to check for validity (current user contributions, etc.)
* @param _beneficiary Address receiving the tokens
* @param _weiAmount Value in wei involved in the purchase
*/
function _updatePurchasingState(
address _beneficiary,
uint256 _weiAmount
)
internal
{
// optional override
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate);
}
/**
* @dev Determines how ETH is stored/forwarded on purchases.
*/
function _forwardFunds() internal {
wallet.transfer(msg.value);
}
}
/**
* @title Ownable
* @dev The Ownable contract has an owner address, and provides basic authorization control
* functions, this simplifies the implementation of "user permissions".
*/
contract Ownable {
address public owner;
event OwnershipRenounced(address indexed previousOwner);
event OwnershipTransferred(
address indexed previousOwner,
address indexed newOwner
);
/**
* @dev The Ownable constructor sets the original `owner` of the contract to the sender
* account.
*/
constructor() public {
owner = msg.sender;
}
/**
* @dev Throws if called by any account other than the owner.
*/
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
/**
* @dev Allows the current owner to relinquish control of the contract.
*/
function renounceOwnership() public onlyOwner {
emit OwnershipRenounced(owner);
owner = address(0);
}
/**
* @dev Allows the current owner to transfer control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function transferOwnership(address _newOwner) public onlyOwner {
_transferOwnership(_newOwner);
}
/**
* @dev Transfers control of the contract to a newOwner.
* @param _newOwner The address to transfer ownership to.
*/
function _transferOwnership(address _newOwner) internal {
require(_newOwner != address(0));
emit OwnershipTransferred(owner, _newOwner);
owner = _newOwner;
}
}
/**
* @title TimedCrowdsale
* @dev Crowdsale accepting contributions only within a time frame.
*/
contract TimedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public openingTime;
uint256 public closingTime;
/**
* @dev Reverts if not in crowdsale time range.
*/
modifier onlyWhileOpen {
// solium-disable-next-line security/no-block-members
require(block.timestamp >= openingTime && block.timestamp <= closingTime);
_;
}
/**
* @dev Constructor, takes crowdsale opening and closing times.
* @param _openingTime Crowdsale opening time
* @param _closingTime Crowdsale closing time
*/
constructor(uint256 _openingTime, uint256 _closingTime) public {
// solium-disable-next-line security/no-block-members
require(_openingTime >= block.timestamp);
require(_closingTime >= _openingTime);
openingTime = _openingTime;
closingTime = _closingTime;
}
/**
* @dev Checks whether the period in which the crowdsale is open has already elapsed.
* @return Whether crowdsale period has elapsed
*/
function hasClosed() public view returns (bool) {
// solium-disable-next-line security/no-block-members
return block.timestamp > closingTime;
}
/**
* @dev Extend parent behavior requiring to be within contributing period
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
onlyWhileOpen
{
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
/**
* @title Basic token
* @dev Basic version of StandardToken, with no allowances.
*/
contract BasicToken is ERC20Basic {
using SafeMath for uint256;
mapping(address => uint256) balances;
uint256 totalSupply_;
/**
* @dev total number of tokens in existence
*/
function totalSupply() public view returns (uint256) {
return totalSupply_;
}
/**
* @dev transfer token for a specified address
* @param _to The address to transfer to.
* @param _value The amount to be transferred.
*/
function transfer(address _to, uint256 _value) public returns (bool) {
require(_to != address(0));
require(_value <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_value);
balances[_to] = balances[_to].add(_value);
emit Transfer(msg.sender, _to, _value);
return true;
}
/**
* @dev Gets the balance of the specified address.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256) {
return balances[_owner];
}
}
/**
* @title Standard ERC20 token
*
* @dev Implementation of the basic standard token.
* @dev https://github.com/ethereum/EIPs/issues/20
* @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol
*/
contract StandardToken is ERC20, BasicToken {
mapping (address => mapping (address => uint256)) internal allowed;
/**
* @dev Transfer tokens from one address to another
* @param _from address The address which you want to send tokens from
* @param _to address The address which you want to transfer to
* @param _value uint256 the amount of tokens to be transferred
*/
function transferFrom(
address _from,
address _to,
uint256 _value
)
public
returns (bool)
{
require(_to != address(0));
require(_value <= balances[_from]);
require(_value <= allowed[_from][msg.sender]);
balances[_from] = balances[_from].sub(_value);
balances[_to] = balances[_to].add(_value);
allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value);
emit Transfer(_from, _to, _value);
return true;
}
/**
* @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender.
*
* Beware that changing an allowance with this method brings the risk that someone may use both the old
* and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this
* race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards:
* https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729
* @param _spender The address which will spend the funds.
* @param _value The amount of tokens to be spent.
*/
function approve(address _spender, uint256 _value) public returns (bool) {
allowed[msg.sender][_spender] = _value;
emit Approval(msg.sender, _spender, _value);
return true;
}
/**
* @dev Function to check the amount of tokens that an owner allowed to a spender.
* @param _owner address The address which owns the funds.
* @param _spender address The address which will spend the funds.
* @return A uint256 specifying the amount of tokens still available for the spender.
*/
function allowance(
address _owner,
address _spender
)
public
view
returns (uint256)
{
return allowed[_owner][_spender];
}
/**
* @dev Increase the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To increment
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _addedValue The amount of tokens to increase the allowance by.
*/
function increaseApproval(
address _spender,
uint _addedValue
)
public
returns (bool)
{
allowed[msg.sender][_spender] = (
allowed[msg.sender][_spender].add(_addedValue));
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
/**
* @dev Decrease the amount of tokens that an owner allowed to a spender.
*
* approve should be called when allowed[_spender] == 0. To decrement
* allowed value is better to use this function to avoid 2 calls (and wait until
* the first transaction is mined)
* From MonolithDAO Token.sol
* @param _spender The address which will spend the funds.
* @param _subtractedValue The amount of tokens to decrease the allowance by.
*/
function decreaseApproval(
address _spender,
uint _subtractedValue
)
public
returns (bool)
{
uint oldValue = allowed[msg.sender][_spender];
if (_subtractedValue > oldValue) {
allowed[msg.sender][_spender] = 0;
} else {
allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue);
}
emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]);
return true;
}
}
/**
* @title Mintable token
* @dev Simple ERC20 Token example, with mintable token creation
* @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120
* Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol
*/
contract MintableToken is StandardToken, Ownable {
event Mint(address indexed to, uint256 amount);
event MintFinished();
bool public mintingFinished = false;
modifier canMint() {
require(!mintingFinished);
_;
}
modifier hasMintPermission() {
require(msg.sender == owner);
_;
}
/**
* @dev Function to mint tokens
* @param _to The address that will receive the minted tokens.
* @param _amount The amount of tokens to mint.
* @return A boolean that indicates if the operation was successful.
*/
function mint(
address _to,
uint256 _amount
)
hasMintPermission
canMint
public
returns (bool)
{
totalSupply_ = totalSupply_.add(_amount);
balances[_to] = balances[_to].add(_amount);
emit Mint(_to, _amount);
emit Transfer(address(0), _to, _amount);
return true;
}
/**
* @dev Function to stop minting new tokens.
* @return True if the operation was successful.
*/
function finishMinting() onlyOwner canMint public returns (bool) {
mintingFinished = true;
emit MintFinished();
return true;
}
}
contract FreezableToken is StandardToken {
// freezing chains
mapping (bytes32 => uint64) internal chains;
// freezing amounts for each chain
mapping (bytes32 => uint) internal freezings;
// total freezing balance per address
mapping (address => uint) internal freezingBalance;
event Freezed(address indexed to, uint64 release, uint amount);
event Released(address indexed owner, uint amount);
/**
* @dev Gets the balance of the specified address include freezing tokens.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function balanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner) + freezingBalance[_owner];
}
/**
* @dev Gets the balance of the specified address without freezing tokens.
* @param _owner The address to query the the balance of.
* @return An uint256 representing the amount owned by the passed address.
*/
function actualBalanceOf(address _owner) public view returns (uint256 balance) {
return super.balanceOf(_owner);
}
function freezingBalanceOf(address _owner) public view returns (uint256 balance) {
return freezingBalance[_owner];
}
/**
* @dev gets freezing count
* @param _addr Address of freeze tokens owner.
*/
function freezingCount(address _addr) public view returns (uint count) {
uint64 release = chains[toKey(_addr, 0)];
while (release != 0) {
count++;
release = chains[toKey(_addr, release)];
}
}
/**
* @dev gets freezing end date and freezing balance for the freezing portion specified by index.
* @param _addr Address of freeze tokens owner.
* @param _index Freezing portion index. It ordered by release date descending.
*/
function getFreezing(address _addr, uint _index) public view returns (uint64 _release, uint _balance) {
for (uint i = 0; i < _index + 1; i++) {
_release = chains[toKey(_addr, _release)];
if (_release == 0) {
return;
}
}
_balance = freezings[toKey(_addr, _release)];
}
/**
* @dev freeze your tokens to the specified address.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to freeze.
* @param _until Release date, must be in future.
*/
function freezeTo(address _to, uint _amount, uint64 _until) public {
require(_to != address(0));
require(_amount <= balances[msg.sender]);
balances[msg.sender] = balances[msg.sender].sub(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Transfer(msg.sender, _to, _amount);
emit Freezed(_to, _until, _amount);
}
/**
* @dev release first available freezing tokens.
*/
function releaseOnce() public {
bytes32 headKey = toKey(msg.sender, 0);
uint64 head = chains[headKey];
require(head != 0);
require(uint64(block.timestamp) > head);
bytes32 currentKey = toKey(msg.sender, head);
uint64 next = chains[currentKey];
uint amount = freezings[currentKey];
delete freezings[currentKey];
balances[msg.sender] = balances[msg.sender].add(amount);
freezingBalance[msg.sender] = freezingBalance[msg.sender].sub(amount);
if (next == 0) {
delete chains[headKey];
} else {
chains[headKey] = next;
delete chains[currentKey];
}
emit Released(msg.sender, amount);
}
/**
* @dev release all available for release freezing tokens. Gas usage is not deterministic!
* @return how many tokens was released
*/
function releaseAll() public returns (uint tokens) {
uint release;
uint balance;
(release, balance) = getFreezing(msg.sender, 0);
while (release != 0 && block.timestamp > release) {
releaseOnce();
tokens += balance;
(release, balance) = getFreezing(msg.sender, 0);
}
}
function toKey(address _addr, uint _release) internal pure returns (bytes32 result) {
// WISH masc to increase entropy
result = 0x5749534800000000000000000000000000000000000000000000000000000000;
assembly {
result := or(result, mul(_addr, 0x10000000000000000))
result := or(result, _release)
}
}
function freeze(address _to, uint64 _until) internal {
require(_until > block.timestamp);
bytes32 key = toKey(_to, _until);
bytes32 parentKey = toKey(_to, uint64(0));
uint64 next = chains[parentKey];
if (next == 0) {
chains[parentKey] = _until;
return;
}
bytes32 nextKey = toKey(_to, next);
uint parent;
while (next != 0 && _until > next) {
parent = next;
parentKey = nextKey;
next = chains[nextKey];
nextKey = toKey(_to, next);
}
if (_until == next) {
return;
}
if (next != 0) {
chains[key] = next;
}
chains[parentKey] = _until;
}
}
/**
* @title Burnable Token
* @dev Token that can be irreversibly burned (destroyed).
*/
contract BurnableToken is BasicToken {
event Burn(address indexed burner, uint256 value);
/**
* @dev Burns a specific amount of tokens.
* @param _value The amount of token to be burned.
*/
function burn(uint256 _value) public {
_burn(msg.sender, _value);
}
function _burn(address _who, uint256 _value) internal {
require(_value <= balances[_who]);
// no need to require value <= totalSupply, since that would imply the
// sender's balance is greater than the totalSupply, which *should* be an assertion failure
balances[_who] = balances[_who].sub(_value);
totalSupply_ = totalSupply_.sub(_value);
emit Burn(_who, _value);
emit Transfer(_who, address(0), _value);
}
}
/**
* @title Pausable
* @dev Base contract which allows children to implement an emergency stop mechanism.
*/
contract Pausable is Ownable {
event Pause();
event Unpause();
bool public paused = false;
/**
* @dev Modifier to make a function callable only when the contract is not paused.
*/
modifier whenNotPaused() {
require(!paused);
_;
}
/**
* @dev Modifier to make a function callable only when the contract is paused.
*/
modifier whenPaused() {
require(paused);
_;
}
/**
* @dev called by the owner to pause, triggers stopped state
*/
function pause() onlyOwner whenNotPaused public {
paused = true;
emit Pause();
}
/**
* @dev called by the owner to unpause, returns to normal state
*/
function unpause() onlyOwner whenPaused public {
paused = false;
emit Unpause();
}
}
contract FreezableMintableToken is FreezableToken, MintableToken {
/**
* @dev Mint the specified amount of token to the specified address and freeze it until the specified date.
* Be careful, gas usage is not deterministic,
* and depends on how many freezes _to address already has.
* @param _to Address to which token will be freeze.
* @param _amount Amount of token to mint and freeze.
* @param _until Release date, must be in future.
* @return A boolean that indicates if the operation was successful.
*/
function mintAndFreeze(address _to, uint _amount, uint64 _until) public onlyOwner canMint returns (bool) {
totalSupply_ = totalSupply_.add(_amount);
bytes32 currentKey = toKey(_to, _until);
freezings[currentKey] = freezings[currentKey].add(_amount);
freezingBalance[_to] = freezingBalance[_to].add(_amount);
freeze(_to, _until);
emit Mint(_to, _amount);
emit Freezed(_to, _until, _amount);
emit Transfer(msg.sender, _to, _amount);
return true;
}
}
contract Consts {
uint public constant TOKEN_DECIMALS = 18;
uint8 public constant TOKEN_DECIMALS_UINT8 = 18;
uint public constant TOKEN_DECIMAL_MULTIPLIER = 10 ** TOKEN_DECIMALS;
string public constant TOKEN_NAME = "AGMG Coin";
string public constant TOKEN_SYMBOL = "AGMG";
bool public constant PAUSED = false;
address public constant TARGET_USER = 0x04D9DA6D64125F438a86D823a5D3253d887Cf92d;
uint public constant START_TIME = 1533034827;
bool public constant CONTINUE_MINTING = true;
}
/**
* @title FinalizableCrowdsale
* @dev Extension of Crowdsale where an owner can do extra work
* after finishing.
*/
contract FinalizableCrowdsale is TimedCrowdsale, Ownable {
using SafeMath for uint256;
bool public isFinalized = false;
event Finalized();
/**
* @dev Must be called after crowdsale ends, to do some extra finalization
* work. Calls the contract's finalization function.
*/
function finalize() onlyOwner public {
require(!isFinalized);
require(hasClosed());
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev Can be overridden to add finalization logic. The overriding function
* should call super.finalization() to ensure the chain of finalization is
* executed entirely.
*/
function finalization() internal {
}
}
/**
* @title CappedCrowdsale
* @dev Crowdsale with a limit for total contributions.
*/
contract CappedCrowdsale is Crowdsale {
using SafeMath for uint256;
uint256 public cap;
/**
* @dev Constructor, takes maximum amount of wei accepted in the crowdsale.
* @param _cap Max amount of wei to be contributed
*/
constructor(uint256 _cap) public {
require(_cap > 0);
cap = _cap;
}
/**
* @dev Checks whether the cap has been reached.
* @return Whether the cap was reached
*/
function capReached() public view returns (bool) {
return weiRaised >= cap;
}
/**
* @dev Extend parent behavior requiring purchase to respect the funding cap.
* @param _beneficiary Token purchaser
* @param _weiAmount Amount of wei contributed
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
super._preValidatePurchase(_beneficiary, _weiAmount);
require(weiRaised.add(_weiAmount) <= cap);
}
}
/**
* @title MintedCrowdsale
* @dev Extension of Crowdsale contract whose tokens are minted in each purchase.
* Token ownership should be transferred to MintedCrowdsale for minting.
*/
contract MintedCrowdsale is Crowdsale {
/**
* @dev Overrides delivery by minting tokens upon purchase.
* @param _beneficiary Token purchaser
* @param _tokenAmount Number of tokens to be minted
*/
function _deliverTokens(
address _beneficiary,
uint256 _tokenAmount
)
internal
{
require(MintableToken(token).mint(_beneficiary, _tokenAmount));
}
}
contract MainToken is Consts, FreezableMintableToken, BurnableToken, Pausable
{
function name() public pure returns (string _name) {
return TOKEN_NAME;
}
function symbol() public pure returns (string _symbol) {
return TOKEN_SYMBOL;
}
function decimals() public pure returns (uint8 _decimals) {
return TOKEN_DECIMALS_UINT8;
}
function transferFrom(address _from, address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transferFrom(_from, _to, _value);
}
function transfer(address _to, uint256 _value) public returns (bool _success) {
require(!paused);
return super.transfer(_to, _value);
}
}
contract MainCrowdsale is Consts, FinalizableCrowdsale, MintedCrowdsale, CappedCrowdsale {
function hasStarted() public view returns (bool) {
return now >= openingTime;
}
function startTime() public view returns (uint256) {
return openingTime;
}
function endTime() public view returns (uint256) {
return closingTime;
}
function hasClosed() public view returns (bool) {
return super.hasClosed() || capReached();
}
function hasEnded() public view returns (bool) {
return hasClosed();
}
function finalization() internal {
super.finalization();
if (PAUSED) {
MainToken(token).unpause();
}
if (!CONTINUE_MINTING) {
require(MintableToken(token).finishMinting());
}
Ownable(token).transferOwnership(TARGET_USER);
}
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
return _weiAmount.mul(rate).div(1 ether);
}
}
contract Checkable {
address private serviceAccount;
/**
* Flag means that contract accident already occurs.
*/
bool private triggered = false;
/**
* Occurs when accident happened.
*/
event Triggered(uint balance);
/**
* Occurs when check finished.
* isAccident is accident occurred
*/
event Checked(bool isAccident);
constructor() public {
serviceAccount = msg.sender;
}
/**
* @dev Replace service account with new one.
* @param _account Valid service account address.
*/
function changeServiceAccount(address _account) public onlyService {
require(_account != 0);
serviceAccount = _account;
}
/**
* @dev Is caller (sender) service account.
*/
function isServiceAccount() public view returns (bool) {
return msg.sender == serviceAccount;
}
/**
* Public check method.
*/
function check() public payable onlyService notTriggered {
if (internalCheck()) {
emit Triggered(address(this).balance);
triggered = true;
internalAction();
}
}
/**
* @dev Do inner check.
* @return bool true of accident triggered, false otherwise.
*/
function internalCheck() internal returns (bool);
/**
* @dev Do inner action if check was success.
*/
function internalAction() internal;
modifier onlyService {
require(msg.sender == serviceAccount);
_;
}
modifier notTriggered {
require(!triggered);
_;
}
}
contract BonusableCrowdsale is Consts, Crowdsale {
/**
* @dev Override to extend the way in which ether is converted to tokens.
* @param _weiAmount Value in wei to be converted into tokens
* @return Number of tokens that can be purchased with the specified _weiAmount
*/
function _getTokenAmount(uint256 _weiAmount)
internal view returns (uint256)
{
uint256 bonusRate = getBonusRate(_weiAmount);
return _weiAmount.mul(bonusRate).div(1 ether);
}
function getBonusRate(uint256 _weiAmount) internal view returns (uint256) {
uint256 bonusRate = rate;
// apply bonus for time & weiRaised
uint[4] memory weiRaisedStartsBounds = [uint(0),uint(250000000000000000000),uint(500000000000000000000),uint(750000000000000000000)];
uint[4] memory weiRaisedEndsBounds = [uint(250000000000000000000),uint(500000000000000000000),uint(750000000000000000000),uint(1000000000000000000000)];
uint64[4] memory timeStartsBounds = [uint64(1533034827),uint64(1533034827),uint64(1533034827),uint64(1533034827)];
uint64[4] memory timeEndsBounds = [uint64(1552492795),uint64(1552492795),uint64(1552492795),uint64(1552492795)];
uint[4] memory weiRaisedAndTimeRates = [uint(400),uint(300),uint(200),uint(100)];
for (uint i = 0; i < 4; i++) {
bool weiRaisedInBound = (weiRaisedStartsBounds[i] <= weiRaised) && (weiRaised < weiRaisedEndsBounds[i]);
bool timeInBound = (timeStartsBounds[i] <= now) && (now < timeEndsBounds[i]);
if (weiRaisedInBound && timeInBound) {
bonusRate += bonusRate * weiRaisedAndTimeRates[i] / 1000;
}
}
return bonusRate;
}
}
contract TemplateCrowdsale is Consts, MainCrowdsale
, BonusableCrowdsale
, Checkable
{
event Initialized();
event TimesChanged(uint startTime, uint endTime, uint oldStartTime, uint oldEndTime);
bool public initialized = false;
constructor(MintableToken _token) public
Crowdsale(1000 * TOKEN_DECIMAL_MULTIPLIER, 0x04D9DA6D64125F438a86D823a5D3253d887Cf92d, _token)
TimedCrowdsale(START_TIME > now ? START_TIME : now, 1552492800)
CappedCrowdsale(3500000000000000000000)
{
}
function init() public onlyOwner {
require(!initialized);
initialized = true;
if (PAUSED) {
MainToken(token).pause();
}
address[2] memory addresses = [address(0x8027bd8a451c134e9dc39d612d4ea65908df3886),address(0x4cd8225477f0bd421c395dcbbf2ea55e0be22408)];
uint[2] memory amounts = [uint(2000000000000000000000000),uint(1000000000000000000000000)];
uint64[2] memory freezes = [uint64(0),uint64(0)];
for (uint i = 0; i < addresses.length; i++) {
if (freezes[i] == 0) {
MainToken(token).mint(addresses[i], amounts[i]);
} else {
MainToken(token).mintAndFreeze(addresses[i], amounts[i], freezes[i]);
}
}
transferOwnership(TARGET_USER);
emit Initialized();
}
function setEndTime(uint _endTime) public onlyOwner {
// only if CS was not ended
require(now < closingTime);
// only if new end time in future
require(now < _endTime);
require(_endTime > openingTime);
emit TimesChanged(openingTime, _endTime, openingTime, closingTime);
closingTime = _endTime;
}
/**
* @dev Do inner check.
* @return bool true of accident triggered, false otherwise.
*/
function internalCheck() internal returns (bool) {
bool result = !isFinalized && hasClosed();
emit Checked(result);
return result;
}
/**
* @dev Do inner action if check was success.
*/
function internalAction() internal {
finalization();
emit Finalized();
isFinalized = true;
}
/**
* @dev override purchase validation to add extra value logic.
* @return true if sended more than minimal value
*/
function _preValidatePurchase(
address _beneficiary,
uint256 _weiAmount
)
internal
{
require(msg.value <= 1000000000000000000000);
super._preValidatePurchase(_beneficiary, _weiAmount);
}
}
|
only if CS was not ended only if new end time in future
|
function setEndTime(uint _endTime) public onlyOwner {
require(now < closingTime);
require(now < _endTime);
require(_endTime > openingTime);
emit TimesChanged(openingTime, _endTime, openingTime, closingTime);
closingTime = _endTime;
}
| 5,791,500 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.